{"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: Description Keep your CRM and task system perfectly in sync — automatically. This workflow monitors a Google Sheet for lead reply updates, instantly updates the corresponding contact in GoHighLevel (GHL), and creates a ClickUp follow-up task when a response is detected. It ensures your sales team never misses a warm lead and every reply is logged, tracked, and acted upon. ⚡ What This Template Does Watches a Google Sheet for reply status changes (“Yes” in the Replied column). 📄 Filters only rows where a lead has replied. 🔍 Updates the corresponding contact record in GoHighLevel (GHL). 🔗 Automatically creates a follow-up task in ClickUp with lead details. 🗂️ Merges updates from both GHL and ClickUp into a single result. 🔄 Logs sync status and timestamps in a tracking sheet (Sheet2) for audit"}, {"role": "assistant", "content": "\n**Analyse du besoin**: Description\n\nKeep your CRM and task system perfectly in sync — automatically. This workflow monitors a Google Sheet for lead reply updates, instantly updates the corresponding contact in GoHighLevel (...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 8 nodes utilisant google.\nStructure: logique conditionnelle, flux standard.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"UG6m2I5WqfBDRROW\",\"meta\":{\"instanceId\":\"8443f10082278c46aa5cf3acf8ff0f70061a2c58bce76efac814b16290845177\",\"templateCredsSetupCompleted\":true},\"name\":\"Reply Status Sync to GHL\",\"tags\":[],\"nodes\":[{\"id\":\"ee10373f-7df7-4acc-ab0f-96d95659b06b\",\"name\":\"Monitor Reply Status Changes\",\"type\":\"n8n-nodes-base.googleSheetsTrigger\",\"position\":[-384,880],\"parameters\":{\"options\":{},\"pollTimes\":{\"item\":[{\"mode\":\"everyMinute\"}]},\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gid=0\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1hoAwuZ7Dn_VL02zs-064EKK0mOzx0oUlwbkJLZZTUzs/edit#gid=0\",\"cachedResultName\":\"Sheet1\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1hoAwuZ7Dn_VL02zs-064EKK0mOzx0oUlwbkJLZZTUzs\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1hoAwuZ7Dn_VL02zs-064EKK0mOzx0oUlwbkJLZZTUzs/edit?usp=drivesdk\",\"cachedResultName\":\"Reply Status Sheet\"}},\"typeVersion\":1},{\"id\":\"6ca6963e-c9bf-44bd-8fa2-97fbab1373d7\",\"name\":\"Filter: Only Process Replies\",\"type\":\"n8n-nodes-base.if\",\"position\":[-160,880],\"parameters\":{\"conditions\":{\"string\":[{\"value1\":\"={{$json[\\\"Replied\\\"]}}\",\"value2\":\"Yes\"}]}},\"typeVersion\":1},{\"id\":\"e24a9517-64bf-4316-82f6-0c6f99129806\",\"name\":\"Update GHL Contact Status\",\"type\":\"n8n-nodes-base.highLevel\",\"position\":[64,784],\"parameters\":{\"contactId\":\"={{ $json.GHL_ID }}\",\"operation\":\"update\",\"updateFields\":{},\"requestOptions\":{}},\"typeVersion\":2},{\"id\":\"d3164500-55a1-43d5-94a7-3874e58fa26e\",\"name\":\"Set GHL Success Status\",\"type\":\"n8n-nodes-base.set\",\"position\":[336,784],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"3e9b0c90-494f-4c17-b7f0-878343c39e77\",\"name\":\"Next_Step\",\"type\":\"string\",\"value\":\"GHL Updated ✓\"},{\"id\":\"b2f8a1c3-5d6e-4f7a-8b9c-0d1e2f3a4b5c\",\"name\":\"Sync_Timestamp\",\"type\":\"string\",\"value\":\"={{ $now.toISO() }}\"}]},\"includeOtherFields\":true},\"typeVersion\":3.4},{\"id\":\"f477df98-457c-4d24-9527-853d4f656362\",\"name\":\"Create Follow-Up Task\",\"type\":\"n8n-nodes-base.clickUp\",\"position\":[64,976],\"parameters\":{\"list\":\"901611225386\",\"name\":\"=Follow-up: {{ $json.Name }} replied!\",\"team\":\"90161261705\",\"space\":\"90165174252\",\"folderless\":true,\"additionalFields\":{\"priority\":3}},\"typeVersion\":1},{\"id\":\"cc263cbd-5074-45b2-842c-b823418684b3\",\"name\":\"Set ClickUp Success Status\",\"type\":\"n8n-nodes-base.set\",\"position\":[336,976],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"3e9b0c90-494f-4c17-b7f0-878343c39e77\",\"name\":\"Next_Step\",\"type\":\"string\",\"value\":\"ClickUp Task Created ✓\"},{\"id\":\"c4d5e6f7-8a9b-0c1d-2e3f-4a5b6c7d8e9f\",\"name\":\"Sync_Timestamp\",\"type\":\"string\",\"value\":\"={{ $now.toISO() }}\"}]},\"includeOtherFields\":true},\"typeVersion\":3.4},{\"id\":\"78d9431a-a0f0-471c-8faf-553cbb027f78\",\"name\":\"Merge Both Paths\",\"type\":\"n8n-nodes-base.merge\",\"position\":[656,880],\"parameters\":{},\"typeVersion\":3.2},{\"id\":\"b7d68642-c6c0-4d52-8ced-6132efa52aab\",\"name\":\"Update Sheet - Log Sync Status\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[944,880],\"parameters\":{\"options\":{},\"fieldsUi\":{\"values\":[{\"column\":\"Next_Step\",\"fieldValue\":\"={{ $json.Next_Step }}\"},{\"column\":\"Sync_Timestamp\",\"fieldValue\":\"={{ $json.Sync_Timestamp }}\"},{\"column\":\"Sync_Status\",\"fieldValue\":\"Completed\"}]},\"operation\":\"update\",\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":595839936,\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1hoAwuZ7Dn_VL02zs-064EKK0mOzx0oUlwbkJLZZTUzs/edit#gid=595839936\",\"cachedResultName\":\"Sheet2\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1hoAwuZ7Dn_VL02zs-064EKK0mOzx0oUlwbkJLZZTUzs\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1hoAwuZ7Dn_VL02zs-064EKK0mOzx0oUlwbkJLZZTUzs/edit?usp=drivesdk\",\"cachedResultName\":\"Reply Status Sheet\"},\"valueToMatchOn\":\"={{ $json.GHL_ID }}\",\"columnToMatchOn\":\"GHL_ID\"},\"typeVersion\":3}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Merge Both Paths\":{\"main\":[[{\"node\":\"Update Sheet - Log Sync Status\",\"type\":\"main\",\"index\":0}]]},\"Create Follow-Up Task\":{\"main\":[[{\"node\":\"Set ClickUp Success Status\",\"type\":\"main\",\"index\":0}]]},\"Set GHL Success Status\":{\"main\":[[{\"node\":\"Merge Both Paths\",\"type\":\"main\",\"index\":0}]]},\"Update GHL Contact Status\":{\"main\":[[{\"node\":\"Set GHL Success Status\",\"type\":\"main\",\"index\":0}]]},\"Set ClickUp Success Status\":{\"main\":[[{\"node\":\"Merge Both Paths\",\"type\":\"main\",\"index\":1}]]},\"Filter: Only Process Replies\":{\"main\":[[{\"node\":\"Update GHL Contact Status\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Create Follow-Up Task\",\"type\":\"main\",\"index\":0}]]},\"Monitor Reply Status Changes\":{\"main\":[[{\"node\":\"Filter: Only Process Replies\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 8, "node_types": {"googleSheetsTrigger": 1, "if": 1, "highLevel": 1, "set": 2, "clickUp": 1, "merge": 1, "googleSheets": 1}, "services": ["google"], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": false, "has_ai": false}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Sync Lead Replies from Google Sheets to GHL CRM & Create ClickUp Follow-up Tasks"}, {"role": "assistant", "content": "\n**Analyse du besoin**: Description\n\nKeep your CRM and task system perfectly in sync — automatically. This workflow monitors a Google Sheet for lead reply updates, instantly updates the corresponding contact in GoHighLevel (...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 8 nodes utilisant google.\nStructure: logique conditionnelle, flux standard.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"UG6m2I5WqfBDRROW\",\"meta\":{\"instanceId\":\"8443f10082278c46aa5cf3acf8ff0f70061a2c58bce76efac814b16290845177\",\"templateCredsSetupCompleted\":true},\"name\":\"Reply Status Sync to GHL\",\"tags\":[],\"nodes\":[{\"id\":\"ee10373f-7df7-4acc-ab0f-96d95659b06b\",\"name\":\"Monitor Reply Status Changes\",\"type\":\"n8n-nodes-base.googleSheetsTrigger\",\"position\":[-384,880],\"parameters\":{\"options\":{},\"pollTimes\":{\"item\":[{\"mode\":\"everyMinute\"}]},\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gid=0\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1hoAwuZ7Dn_VL02zs-064EKK0mOzx0oUlwbkJLZZTUzs/edit#gid=0\",\"cachedResultName\":\"Sheet1\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1hoAwuZ7Dn_VL02zs-064EKK0mOzx0oUlwbkJLZZTUzs\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1hoAwuZ7Dn_VL02zs-064EKK0mOzx0oUlwbkJLZZTUzs/edit?usp=drivesdk\",\"cachedResultName\":\"Reply Status Sheet\"}},\"typeVersion\":1},{\"id\":\"6ca6963e-c9bf-44bd-8fa2-97fbab1373d7\",\"name\":\"Filter: Only Process Replies\",\"type\":\"n8n-nodes-base.if\",\"position\":[-160,880],\"parameters\":{\"conditions\":{\"string\":[{\"value1\":\"={{$json[\\\"Replied\\\"]}}\",\"value2\":\"Yes\"}]}},\"typeVersion\":1},{\"id\":\"e24a9517-64bf-4316-82f6-0c6f99129806\",\"name\":\"Update GHL Contact Status\",\"type\":\"n8n-nodes-base.highLevel\",\"position\":[64,784],\"parameters\":{\"contactId\":\"={{ $json.GHL_ID }}\",\"operation\":\"update\",\"updateFields\":{},\"requestOptions\":{}},\"typeVersion\":2},{\"id\":\"d3164500-55a1-43d5-94a7-3874e58fa26e\",\"name\":\"Set GHL Success Status\",\"type\":\"n8n-nodes-base.set\",\"position\":[336,784],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"3e9b0c90-494f-4c17-b7f0-878343c39e77\",\"name\":\"Next_Step\",\"type\":\"string\",\"value\":\"GHL Updated ✓\"},{\"id\":\"b2f8a1c3-5d6e-4f7a-8b9c-0d1e2f3a4b5c\",\"name\":\"Sync_Timestamp\",\"type\":\"string\",\"value\":\"={{ $now.toISO() }}\"}]},\"includeOtherFields\":true},\"typeVersion\":3.4},{\"id\":\"f477df98-457c-4d24-9527-853d4f656362\",\"name\":\"Create Follow-Up Task\",\"type\":\"n8n-nodes-base.clickUp\",\"position\":[64,976],\"parameters\":{\"list\":\"901611225386\",\"name\":\"=Follow-up: {{ $json.Name }} replied!\",\"team\":\"90161261705\",\"space\":\"90165174252\",\"folderless\":true,\"additionalFields\":{\"priority\":3}},\"typeVersion\":1},{\"id\":\"cc263cbd-5074-45b2-842c-b823418684b3\",\"name\":\"Set ClickUp Success Status\",\"type\":\"n8n-nodes-base.set\",\"position\":[336,976],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"3e9b0c90-494f-4c17-b7f0-878343c39e77\",\"name\":\"Next_Step\",\"type\":\"string\",\"value\":\"ClickUp Task Created ✓\"},{\"id\":\"c4d5e6f7-8a9b-0c1d-2e3f-4a5b6c7d8e9f\",\"name\":\"Sync_Timestamp\",\"type\":\"string\",\"value\":\"={{ $now.toISO() }}\"}]},\"includeOtherFields\":true},\"typeVersion\":3.4},{\"id\":\"78d9431a-a0f0-471c-8faf-553cbb027f78\",\"name\":\"Merge Both Paths\",\"type\":\"n8n-nodes-base.merge\",\"position\":[656,880],\"parameters\":{},\"typeVersion\":3.2},{\"id\":\"b7d68642-c6c0-4d52-8ced-6132efa52aab\",\"name\":\"Update Sheet - Log Sync Status\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[944,880],\"parameters\":{\"options\":{},\"fieldsUi\":{\"values\":[{\"column\":\"Next_Step\",\"fieldValue\":\"={{ $json.Next_Step }}\"},{\"column\":\"Sync_Timestamp\",\"fieldValue\":\"={{ $json.Sync_Timestamp }}\"},{\"column\":\"Sync_Status\",\"fieldValue\":\"Completed\"}]},\"operation\":\"update\",\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":595839936,\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1hoAwuZ7Dn_VL02zs-064EKK0mOzx0oUlwbkJLZZTUzs/edit#gid=595839936\",\"cachedResultName\":\"Sheet2\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1hoAwuZ7Dn_VL02zs-064EKK0mOzx0oUlwbkJLZZTUzs\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1hoAwuZ7Dn_VL02zs-064EKK0mOzx0oUlwbkJLZZTUzs/edit?usp=drivesdk\",\"cachedResultName\":\"Reply Status Sheet\"},\"valueToMatchOn\":\"={{ $json.GHL_ID }}\",\"columnToMatchOn\":\"GHL_ID\"},\"typeVersion\":3}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Merge Both Paths\":{\"main\":[[{\"node\":\"Update Sheet - Log Sync Status\",\"type\":\"main\",\"index\":0}]]},\"Create Follow-Up Task\":{\"main\":[[{\"node\":\"Set ClickUp Success Status\",\"type\":\"main\",\"index\":0}]]},\"Set GHL Success Status\":{\"main\":[[{\"node\":\"Merge Both Paths\",\"type\":\"main\",\"index\":0}]]},\"Update GHL Contact Status\":{\"main\":[[{\"node\":\"Set GHL Success Status\",\"type\":\"main\",\"index\":0}]]},\"Set ClickUp Success Status\":{\"main\":[[{\"node\":\"Merge Both Paths\",\"type\":\"main\",\"index\":1}]]},\"Filter: Only Process Replies\":{\"main\":[[{\"node\":\"Update GHL Contact Status\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Create Follow-Up Task\",\"type\":\"main\",\"index\":0}]]},\"Monitor Reply Status Changes\":{\"main\":[[{\"node\":\"Filter: Only Process Replies\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 8, "node_types": {"googleSheetsTrigger": 1, "if": 1, "highLevel": 1, "set": 2, "clickUp": 1, "merge": 1, "googleSheets": 1}, "services": ["google"], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": false, "has_ai": false}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: 🧨 VIP Radar: Instantly Spot & Summarize High-Value Shopify Orders with AI + Slack Alerts Automatically detect when a new Shopify order exceeds $200, fetch the customer’s purchase history, generate an AI-powered summary, and alert your team in Slack—so no VIP goes unnoticed. 🛠️ Workflow Overview Feature\tDescription Trigger\tShopify “New Order” webhook Conditional Check\tFilters for orders > $200 Data Enrichment\tPulls full order history for the customer from Shopify AI Summary\tUses OpenAI to summarize buying behavior Notification\tSends detailed alert to Slack with name, order total, and customer insights Fallback\tIgnores low-value orders and terminates flow 📘 What This Workflow Does This automation monitors your Shopify store and reacts to any high-value order (over $200). When triggered: It f"}, {"role": "assistant", "content": "\n**Analyse du besoin**: 🧨 VIP Radar: Instantly Spot & Summarize High-Value Shopify Orders with AI + Slack Alerts\n\nAutomatically detect when a new Shopify order exceeds $200, fetch the customer’s purchase history, generate an...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 9 nodes utilisant ai, slack, http.\nStructure: logique conditionnelle, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"meta\":{\"instanceId\":\"5aaf4236c70e34e423fbdb2c7b754d19253a933bb1476d548f75848a01e473cf\"},\"nodes\":[{\"id\":\"ac23a49a-4fc6-468a-ba0f-c520a4feb396\",\"name\":\"No Operation, do nothing\",\"type\":\"n8n-nodes-base.noOp\",\"position\":[40,1540],\"parameters\":{},\"typeVersion\":1},{\"id\":\"f3c6e47e-6784-47d8-a7a7-30f4c11e9ff3\",\"name\":\"New Shopify Order\",\"type\":\"n8n-nodes-base.shopifyTrigger\",\"position\":[-720,1260],\"webhookId\":\"2969c4e3-fcbb-45d7-b783-256b55cf8088\",\"parameters\":{\"topic\":\"orders/create\",\"authentication\":\"accessToken\"},\"typeVersion\":1},{\"id\":\"a694a77c-a1eb-4053-bc69-4f7048a1abbc\",\"name\":\"If\",\"type\":\"n8n-nodes-base.if\",\"position\":[-280,1260],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"c2b8d86f-a356-4ea4-b516-56abfeb2570f\",\"operator\":{\"type\":\"number\",\"operation\":\"gt\"},\"leftValue\":\"={{ $json.total_price }}\",\"rightValue\":200}]}},\"typeVersion\":2.2},{\"id\":\"1a22c0cd-d1b1-45a7-8fc6-78ef21edb762\",\"name\":\"Fetch Customer Order History\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[40,1100],\"parameters\":{\"url\":\"=https://your-store.myshopify.com/admin/api/2023-07/orders.json?customer_id={{ $('New Shopify Order').item.json.id }}\",\"options\":{},\"sendHeaders\":true,\"headerParameters\":{\"parameters\":[{\"name\":\"X-Shopify-Access-Token\",\"value\":\"shpat_abc123xyz...\"}]}},\"typeVersion\":4.2},{\"id\":\"cfbfb38c-53b9-4c25-8eda-2090c4ef0738\",\"name\":\"Type conversion (Array to String)\",\"type\":\"n8n-nodes-base.set\",\"position\":[260,1100],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"3f2f5ff0-4bf6-4f2e-aecf-6de16ec91cf4\",\"name\":\"orders\",\"type\":\"string\",\"value\":\"={{ $json.orders }}\"}]}},\"typeVersion\":3.4},{\"id\":\"79f49ac3-b559-48e8-826b-ee7ae58dbe5f\",\"name\":\"Type conversion (String to Number)\",\"type\":\"n8n-nodes-base.set\",\"position\":[-500,1260],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"9c3375fe-5ad9-46df-b892-f1e6696d1b0e\",\"name\":\"total_price\",\"type\":\"number\",\"value\":\"={{ $json.total_price }}\"}]}},\"typeVersion\":3.4},{\"id\":\"b69c46f9-67dd-4eec-a94e-72cc9a03ebbf\",\"name\":\"Summarize Order History\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[520,1100],\"parameters\":{\"text\":\"=Summarize the customer's order history for Slack. Here is their order data:\\n{{ $json.orders }}\",\"options\":{\"systemMessage\":\"You are a helpful assistant\"},\"promptType\":\"define\"},\"typeVersion\":1.9},{\"id\":\"f4812abe-d29d-4fc6-b9ea-705437c90d82\",\"name\":\"Send Slack Alert\",\"type\":\"n8n-nodes-base.slack\",\"position\":[880,1100],\"webhookId\":\"577b78c7-df10-46f6-9025-8c5e64c332fe\",\"parameters\":{\"text\":\"=🚨 High-Value Order Alert! \\nCustomer: {{ $('New Shopify Order').item.json.billing_address.first_name }} {{ $('New Shopify Order').item.json.billing_address.last_name }}\\nOrder Total: ${{ $('New Shopify Order').item.json.total_price }} \\nCustomer Order history Summary: {{ $json.output }}\",\"select\":\"channel\",\"channelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"C08TTV0CC3E\",\"cachedResultName\":\"all-nathing\"},\"otherOptions\":{\"includeLinkToWorkflow\":false}},\"typeVersion\":2.3},{\"id\":\"aa297625-1574-4105-a480-ace06e258cc3\",\"name\":\"Ignore Low-Value Order\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[460,1300],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4o-mini\"},\"options\":{}},\"typeVersion\":1.2}],\"connections\":{\"If\":{\"main\":[[{\"node\":\"Fetch Customer Order History\",\"type\":\"main\",\"index\":0}],[{\"node\":\"No Operation, do nothing\",\"type\":\"main\",\"index\":0}]]},\"New Shopify Order\":{\"main\":[[{\"node\":\"Type conversion (String to Number)\",\"type\":\"main\",\"index\":0}]]},\"Ignore Low-Value Order\":{\"ai_languageModel\":[[{\"node\":\"Summarize Order History\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Summarize Order History\":{\"main\":[[{\"node\":\"Send Slack Alert\",\"type\":\"main\",\"index\":0}]]},\"Fetch Customer Order History\":{\"main\":[[{\"node\":\"Type conversion (Array to String)\",\"type\":\"main\",\"index\":0}]]},\"Type conversion (Array to String)\":{\"main\":[[{\"node\":\"Summarize Order History\",\"type\":\"main\",\"index\":0}]]},\"Type conversion (String to Number)\":{\"main\":[[{\"node\":\"If\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 9, "node_types": {"noOp": 1, "shopifyTrigger": 1, "if": 1, "httpRequest": 1, "set": 2, "agent": 1, "slack": 1, "lmChatOpenAi": 1}, "services": ["ai", "slack", "http"], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": false, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Shopify VIP Alerts: AI Summary & Slack Notification for Big Orders"}, {"role": "assistant", "content": "\n**Analyse du besoin**: 🧨 VIP Radar: Instantly Spot & Summarize High-Value Shopify Orders with AI + Slack Alerts\n\nAutomatically detect when a new Shopify order exceeds $200, fetch the customer’s purchase history, generate an...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 9 nodes utilisant ai, slack, http.\nStructure: logique conditionnelle, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"meta\":{\"instanceId\":\"5aaf4236c70e34e423fbdb2c7b754d19253a933bb1476d548f75848a01e473cf\"},\"nodes\":[{\"id\":\"ac23a49a-4fc6-468a-ba0f-c520a4feb396\",\"name\":\"No Operation, do nothing\",\"type\":\"n8n-nodes-base.noOp\",\"position\":[40,1540],\"parameters\":{},\"typeVersion\":1},{\"id\":\"f3c6e47e-6784-47d8-a7a7-30f4c11e9ff3\",\"name\":\"New Shopify Order\",\"type\":\"n8n-nodes-base.shopifyTrigger\",\"position\":[-720,1260],\"webhookId\":\"2969c4e3-fcbb-45d7-b783-256b55cf8088\",\"parameters\":{\"topic\":\"orders/create\",\"authentication\":\"accessToken\"},\"typeVersion\":1},{\"id\":\"a694a77c-a1eb-4053-bc69-4f7048a1abbc\",\"name\":\"If\",\"type\":\"n8n-nodes-base.if\",\"position\":[-280,1260],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"c2b8d86f-a356-4ea4-b516-56abfeb2570f\",\"operator\":{\"type\":\"number\",\"operation\":\"gt\"},\"leftValue\":\"={{ $json.total_price }}\",\"rightValue\":200}]}},\"typeVersion\":2.2},{\"id\":\"1a22c0cd-d1b1-45a7-8fc6-78ef21edb762\",\"name\":\"Fetch Customer Order History\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[40,1100],\"parameters\":{\"url\":\"=https://your-store.myshopify.com/admin/api/2023-07/orders.json?customer_id={{ $('New Shopify Order').item.json.id }}\",\"options\":{},\"sendHeaders\":true,\"headerParameters\":{\"parameters\":[{\"name\":\"X-Shopify-Access-Token\",\"value\":\"shpat_abc123xyz...\"}]}},\"typeVersion\":4.2},{\"id\":\"cfbfb38c-53b9-4c25-8eda-2090c4ef0738\",\"name\":\"Type conversion (Array to String)\",\"type\":\"n8n-nodes-base.set\",\"position\":[260,1100],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"3f2f5ff0-4bf6-4f2e-aecf-6de16ec91cf4\",\"name\":\"orders\",\"type\":\"string\",\"value\":\"={{ $json.orders }}\"}]}},\"typeVersion\":3.4},{\"id\":\"79f49ac3-b559-48e8-826b-ee7ae58dbe5f\",\"name\":\"Type conversion (String to Number)\",\"type\":\"n8n-nodes-base.set\",\"position\":[-500,1260],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"9c3375fe-5ad9-46df-b892-f1e6696d1b0e\",\"name\":\"total_price\",\"type\":\"number\",\"value\":\"={{ $json.total_price }}\"}]}},\"typeVersion\":3.4},{\"id\":\"b69c46f9-67dd-4eec-a94e-72cc9a03ebbf\",\"name\":\"Summarize Order History\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[520,1100],\"parameters\":{\"text\":\"=Summarize the customer's order history for Slack. Here is their order data:\\n{{ $json.orders }}\",\"options\":{\"systemMessage\":\"You are a helpful assistant\"},\"promptType\":\"define\"},\"typeVersion\":1.9},{\"id\":\"f4812abe-d29d-4fc6-b9ea-705437c90d82\",\"name\":\"Send Slack Alert\",\"type\":\"n8n-nodes-base.slack\",\"position\":[880,1100],\"webhookId\":\"577b78c7-df10-46f6-9025-8c5e64c332fe\",\"parameters\":{\"text\":\"=🚨 High-Value Order Alert! \\nCustomer: {{ $('New Shopify Order').item.json.billing_address.first_name }} {{ $('New Shopify Order').item.json.billing_address.last_name }}\\nOrder Total: ${{ $('New Shopify Order').item.json.total_price }} \\nCustomer Order history Summary: {{ $json.output }}\",\"select\":\"channel\",\"channelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"C08TTV0CC3E\",\"cachedResultName\":\"all-nathing\"},\"otherOptions\":{\"includeLinkToWorkflow\":false}},\"typeVersion\":2.3},{\"id\":\"aa297625-1574-4105-a480-ace06e258cc3\",\"name\":\"Ignore Low-Value Order\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[460,1300],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4o-mini\"},\"options\":{}},\"typeVersion\":1.2}],\"connections\":{\"If\":{\"main\":[[{\"node\":\"Fetch Customer Order History\",\"type\":\"main\",\"index\":0}],[{\"node\":\"No Operation, do nothing\",\"type\":\"main\",\"index\":0}]]},\"New Shopify Order\":{\"main\":[[{\"node\":\"Type conversion (String to Number)\",\"type\":\"main\",\"index\":0}]]},\"Ignore Low-Value Order\":{\"ai_languageModel\":[[{\"node\":\"Summarize Order History\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Summarize Order History\":{\"main\":[[{\"node\":\"Send Slack Alert\",\"type\":\"main\",\"index\":0}]]},\"Fetch Customer Order History\":{\"main\":[[{\"node\":\"Type conversion (Array to String)\",\"type\":\"main\",\"index\":0}]]},\"Type conversion (Array to String)\":{\"main\":[[{\"node\":\"Summarize Order History\",\"type\":\"main\",\"index\":0}]]},\"Type conversion (String to Number)\":{\"main\":[[{\"node\":\"If\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 9, "node_types": {"noOp": 1, "shopifyTrigger": 1, "if": 1, "httpRequest": 1, "set": 2, "agent": 1, "slack": 1, "lmChatOpenAi": 1}, "services": ["ai", "slack", "http"], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": false, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: This n8n workflow integrates Shopify order management with Telegram, allowing you to query open orders and order details directly through Telegram chat commands. It provides an interactive way to monitor your Shopify store orders using Telegram as an interface. Key Features Telegram Trigger: Listens for messages and callback queries from your Telegram bot. Switch Node: Routes incoming Telegram messages to different flows based on message content: /orders command to fetch all open orders Callback queries starting with /order_ to fetch details of a specific order Shopify Get Orders: Retrieves all open orders from your Shopify store using your Shopify API credentials. Conditional Check (If Node): Determines if there are any open orders; branches accordingly: If orders exist, prepare an intera"}, {"role": "assistant", "content": "\n**Analyse du besoin**: This n8n workflow integrates Shopify order management with Telegram, allowing you to query open orders and order details directly through Telegram chat commands. It provides an interactive way to moni...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 11 nodes utilisant http.\nStructure: logique conditionnelle, code personnalisé, flux standard.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"A0Db66VzkRkoTQtL\",\"meta\":{\"instanceId\":\"1e9c5d216f82eece259bdabdf191aced054cce6456f87af0ff7807ca2b37638a\",\"templateCredsSetupCompleted\":true},\"name\":\"Query and Monitor Shopify Orders via Telegram Bot Commands\",\"tags\":[{\"id\":\"hlEHEpOdSg5lhIqi\",\"name\":\"Template\",\"createdAt\":\"2025-06-05T15:35:52.689Z\",\"updatedAt\":\"2025-06-05T15:35:52.689Z\"}],\"nodes\":[{\"id\":\"0ec29eee-814b-43a6-8ed6-608306de9dd7\",\"name\":\"Telegram Trigger\",\"type\":\"n8n-nodes-base.telegramTrigger\",\"position\":[-760,280],\"webhookId\":\"85257fe6-a492-4523-a3c0-156054b46d51\",\"parameters\":{\"updates\":[\"message\",\"*\"],\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"29ea564c-f456-4779-b5f4-cd4c26e6738f\",\"name\":\"get Orders\",\"type\":\"n8n-nodes-base.shopify\",\"position\":[0,0],\"parameters\":{\"options\":{\"status\":\"open\"},\"operation\":\"getAll\",\"returnAll\":true,\"authentication\":\"accessToken\"},\"notesInFlow\":false,\"typeVersion\":1,\"alwaysOutputData\":true},{\"id\":\"5a6bf5b1-0249-4773-aae2-9ac3fdd3c8a2\",\"name\":\"Orders\",\"type\":\"n8n-nodes-base.code\",\"position\":[580,-120],\"parameters\":{\"jsCode\":\"const chatId = $('Telegram Trigger').first().json.message.chat.id;\\n\\nreturn [{\\n json: {\\n chat_id: chatId,\\n text: \\\"All Open Orders\\\",\\n reply_markup: {\\n inline_keyboard: items.map(order => [{\\n text: `${order.json.name} ($${order.json.total_price})`,\\n callback_data: `/order_${order.json.id}`\\n }])\\n }\\n }\\n}];\\n\"},\"typeVersion\":2},{\"id\":\"cfa6e297-1462-480b-9e48-c3d50a63cadc\",\"name\":\"No Order\",\"type\":\"n8n-nodes-base.code\",\"position\":[580,80],\"parameters\":{\"jsCode\":\"const chatId = $('Telegram Trigger').first().json.message.chat.id;\\n\\nreturn [{\\n json: {\\n chat_id: chatId,\\n text: \\\"No Order\\\",\\n \\n }\\n}];\\n\"},\"typeVersion\":2},{\"id\":\"fcca715b-6f12-4baa-bfaa-7878fcf61b69\",\"name\":\"get Order\",\"type\":\"n8n-nodes-base.shopify\",\"position\":[200,420],\"parameters\":{\"options\":{},\"orderId\":\"={{ $json.orderId }}\",\"operation\":\"get\",\"authentication\":\"accessToken\"},\"notesInFlow\":false,\"typeVersion\":1,\"alwaysOutputData\":false},{\"id\":\"5463162c-7a0b-4cbc-b9f1-1f6e7fa03ee5\",\"name\":\"Clean Up Order\",\"type\":\"n8n-nodes-base.code\",\"position\":[480,420],\"parameters\":{\"jsCode\":\"const items = $json.line_items || [];\\n\\nlet message = '🧾 *'+ $input.first().json.name+'*\\\\n\\\\n';\\n\\nitems.forEach(item => {\\n const variant = item.variant_title ? ` ${item.variant_title}` : '';\\n message += `• ${item.title}${variant} x ${item.quantity} — $${item.price}\\\\n`;\\n});\\n\\nreturn [{\\n json: {\\n text: message,\\n chat_id: $('Get Order ID').first().json.chat_id, // pass this from previous step\\n \\n message_id: $('Get Order ID').first().json.message_id,\\n \\n parse_mode: \\\"Markdown\\\",\\n reply_markup: {\\n inline_keyboard: []\\n }\\n \\n }\\n}];\\n\"},\"typeVersion\":2},{\"id\":\"375a5e49-cc8e-43b2-a8c3-ecdbcaff5fbf\",\"name\":\"Check If There's Any Order\",\"type\":\"n8n-nodes-base.if\",\"position\":[220,0],\"parameters\":{\"options\":{\"ignoreCase\":false},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"7cba3954-60cd-44ac-ad53-509ae2fcb6d2\",\"operator\":{\"type\":\"object\",\"operation\":\"notEmpty\",\"singleValue\":true},\"leftValue\":\"={{ $json }}\",\"rightValue\":\"asdf\"},{\"id\":\"a2964354-a639-4621-a895-00ad314f397f\",\"operator\":{\"name\":\"filter.operator.equals\",\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2,\"alwaysOutputData\":false},{\"id\":\"6139c466-6c0f-4faa-ad28-3fff661343e6\",\"name\":\"Get All Orders/Get An Order Detail\",\"type\":\"n8n-nodes-base.switch\",\"position\":[-500,280],\"parameters\":{\"rules\":{\"values\":[{\"outputKey\":\"Get Order Detail\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":false,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"15856982-a1b8-4ec6-8fe1-4c4dea6c27cc\",\"operator\":{\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.message.text }}\",\"rightValue\":\"/orders\"}]},\"renameOutput\":true},{\"outputKey\":\"Get An Order\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":false,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"b64cbec5-2e9f-4466-9753-4a3dd77fe381\",\"operator\":{\"type\":\"string\",\"operation\":\"startsWith\"},\"leftValue\":\"={{ $json.callback_query.data }}\",\"rightValue\":\"/order_\"}]},\"renameOutput\":true}]},\"options\":{\"ignoreCase\":true}},\"typeVersion\":3.2},{\"id\":\"624cd9da-e921-4849-8ecd-5b4cfd281e08\",\"name\":\"Get Order ID\",\"type\":\"n8n-nodes-base.code\",\"position\":[-120,420],\"parameters\":{\"jsCode\":\"const callbackData = $json.callback_query.data; // e.g., /order_5832437071968ACSbot\\n\\nconst id = callbackData.match(/^\\\\/order_(\\\\d+)/)?.[1];\\n\\nreturn [{\\n json: {\\n orderId: id,\\n chat_id: $json.callback_query.message.chat.id,\\n message_id: $json.callback_query.message.message_id\\n }\\n}];\"},\"typeVersion\":2},{\"id\":\"22148fd6-8503-4486-b1b1-2c1a947cddab\",\"name\":\"Send Orders to Telegram\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[900,-20],\"parameters\":{\"url\":\"https://api.telegram.org/bot/sendMessage\",\"options\":{},\"sendBody\":true,\"bodyParameters\":{\"parameters\":[{\"name\":\"chat_id\",\"value\":\"={{ $json.chat_id }}\"},{\"name\":\"text\",\"value\":\"={{ $json.text }}\"},{\"name\":\"reply_markup\",\"value\":\"={{ JSON.stringify($json.reply_markup) }}\"}]}},\"typeVersion\":4.2},{\"id\":\"330bc89d-4f23-4401-9f18-e0d9d9743b06\",\"name\":\"Send Order Details\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[900,420],\"webhookId\":\"fd0d23df-37db-4bd1-ae1e-dd03b54e6089\",\"parameters\":{\"text\":\"={{ $json.text }}\",\"chatId\":\"={{ $json.chat_id }}\",\"messageId\":\"={{ $json.message_id }}\",\"operation\":\"editMessageText\",\"additionalFields\":{\"parse_mode\":\"Markdown\"}},\"typeVersion\":1.2}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Orders\":{\"main\":[[{\"node\":\"Send Orders to Telegram\",\"type\":\"main\",\"index\":0}]]},\"No Order\":{\"main\":[[{\"node\":\"Send Orders to Telegram\",\"type\":\"main\",\"index\":0}]]},\"get Order\":{\"main\":[[{\"node\":\"Clean Up Order\",\"type\":\"main\",\"index\":0}]]},\"get Orders\":{\"main\":[[{\"node\":\"Check If There's Any Order\",\"type\":\"main\",\"index\":0}]]},\"Get Order ID\":{\"main\":[[{\"node\":\"get Order\",\"type\":\"main\",\"index\":0}]]},\"Clean Up Order\":{\"main\":[[{\"node\":\"Send Order Details\",\"type\":\"main\",\"index\":0}]]},\"Telegram Trigger\":{\"main\":[[{\"node\":\"Get All Orders/Get An Order Detail\",\"type\":\"main\",\"index\":0}]]},\"Check If There's Any Order\":{\"main\":[[{\"node\":\"Orders\",\"type\":\"main\",\"index\":0}],[{\"node\":\"No Order\",\"type\":\"main\",\"index\":0}]]},\"Get All Orders/Get An Order Detail\":{\"main\":[[{\"node\":\"get Orders\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Get Order ID\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 11, "node_types": {"telegramTrigger": 1, "shopify": 2, "code": 4, "if": 1, "switch": 1, "httpRequest": 1, "telegram": 1}, "services": ["http"], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": true, "has_ai": false}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Query and Monitor Shopify Orders via Telegram Bot Commands"}, {"role": "assistant", "content": "\n**Analyse du besoin**: This n8n workflow integrates Shopify order management with Telegram, allowing you to query open orders and order details directly through Telegram chat commands. It provides an interactive way to moni...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 11 nodes utilisant http.\nStructure: logique conditionnelle, code personnalisé, flux standard.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"A0Db66VzkRkoTQtL\",\"meta\":{\"instanceId\":\"1e9c5d216f82eece259bdabdf191aced054cce6456f87af0ff7807ca2b37638a\",\"templateCredsSetupCompleted\":true},\"name\":\"Query and Monitor Shopify Orders via Telegram Bot Commands\",\"tags\":[{\"id\":\"hlEHEpOdSg5lhIqi\",\"name\":\"Template\",\"createdAt\":\"2025-06-05T15:35:52.689Z\",\"updatedAt\":\"2025-06-05T15:35:52.689Z\"}],\"nodes\":[{\"id\":\"0ec29eee-814b-43a6-8ed6-608306de9dd7\",\"name\":\"Telegram Trigger\",\"type\":\"n8n-nodes-base.telegramTrigger\",\"position\":[-760,280],\"webhookId\":\"85257fe6-a492-4523-a3c0-156054b46d51\",\"parameters\":{\"updates\":[\"message\",\"*\"],\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"29ea564c-f456-4779-b5f4-cd4c26e6738f\",\"name\":\"get Orders\",\"type\":\"n8n-nodes-base.shopify\",\"position\":[0,0],\"parameters\":{\"options\":{\"status\":\"open\"},\"operation\":\"getAll\",\"returnAll\":true,\"authentication\":\"accessToken\"},\"notesInFlow\":false,\"typeVersion\":1,\"alwaysOutputData\":true},{\"id\":\"5a6bf5b1-0249-4773-aae2-9ac3fdd3c8a2\",\"name\":\"Orders\",\"type\":\"n8n-nodes-base.code\",\"position\":[580,-120],\"parameters\":{\"jsCode\":\"const chatId = $('Telegram Trigger').first().json.message.chat.id;\\n\\nreturn [{\\n json: {\\n chat_id: chatId,\\n text: \\\"All Open Orders\\\",\\n reply_markup: {\\n inline_keyboard: items.map(order => [{\\n text: `${order.json.name} ($${order.json.total_price})`,\\n callback_data: `/order_${order.json.id}`\\n }])\\n }\\n }\\n}];\\n\"},\"typeVersion\":2},{\"id\":\"cfa6e297-1462-480b-9e48-c3d50a63cadc\",\"name\":\"No Order\",\"type\":\"n8n-nodes-base.code\",\"position\":[580,80],\"parameters\":{\"jsCode\":\"const chatId = $('Telegram Trigger').first().json.message.chat.id;\\n\\nreturn [{\\n json: {\\n chat_id: chatId,\\n text: \\\"No Order\\\",\\n \\n }\\n}];\\n\"},\"typeVersion\":2},{\"id\":\"fcca715b-6f12-4baa-bfaa-7878fcf61b69\",\"name\":\"get Order\",\"type\":\"n8n-nodes-base.shopify\",\"position\":[200,420],\"parameters\":{\"options\":{},\"orderId\":\"={{ $json.orderId }}\",\"operation\":\"get\",\"authentication\":\"accessToken\"},\"notesInFlow\":false,\"typeVersion\":1,\"alwaysOutputData\":false},{\"id\":\"5463162c-7a0b-4cbc-b9f1-1f6e7fa03ee5\",\"name\":\"Clean Up Order\",\"type\":\"n8n-nodes-base.code\",\"position\":[480,420],\"parameters\":{\"jsCode\":\"const items = $json.line_items || [];\\n\\nlet message = '🧾 *'+ $input.first().json.name+'*\\\\n\\\\n';\\n\\nitems.forEach(item => {\\n const variant = item.variant_title ? ` ${item.variant_title}` : '';\\n message += `• ${item.title}${variant} x ${item.quantity} — $${item.price}\\\\n`;\\n});\\n\\nreturn [{\\n json: {\\n text: message,\\n chat_id: $('Get Order ID').first().json.chat_id, // pass this from previous step\\n \\n message_id: $('Get Order ID').first().json.message_id,\\n \\n parse_mode: \\\"Markdown\\\",\\n reply_markup: {\\n inline_keyboard: []\\n }\\n \\n }\\n}];\\n\"},\"typeVersion\":2},{\"id\":\"375a5e49-cc8e-43b2-a8c3-ecdbcaff5fbf\",\"name\":\"Check If There's Any Order\",\"type\":\"n8n-nodes-base.if\",\"position\":[220,0],\"parameters\":{\"options\":{\"ignoreCase\":false},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"7cba3954-60cd-44ac-ad53-509ae2fcb6d2\",\"operator\":{\"type\":\"object\",\"operation\":\"notEmpty\",\"singleValue\":true},\"leftValue\":\"={{ $json }}\",\"rightValue\":\"asdf\"},{\"id\":\"a2964354-a639-4621-a895-00ad314f397f\",\"operator\":{\"name\":\"filter.operator.equals\",\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2,\"alwaysOutputData\":false},{\"id\":\"6139c466-6c0f-4faa-ad28-3fff661343e6\",\"name\":\"Get All Orders/Get An Order Detail\",\"type\":\"n8n-nodes-base.switch\",\"position\":[-500,280],\"parameters\":{\"rules\":{\"values\":[{\"outputKey\":\"Get Order Detail\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":false,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"15856982-a1b8-4ec6-8fe1-4c4dea6c27cc\",\"operator\":{\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.message.text }}\",\"rightValue\":\"/orders\"}]},\"renameOutput\":true},{\"outputKey\":\"Get An Order\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":false,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"b64cbec5-2e9f-4466-9753-4a3dd77fe381\",\"operator\":{\"type\":\"string\",\"operation\":\"startsWith\"},\"leftValue\":\"={{ $json.callback_query.data }}\",\"rightValue\":\"/order_\"}]},\"renameOutput\":true}]},\"options\":{\"ignoreCase\":true}},\"typeVersion\":3.2},{\"id\":\"624cd9da-e921-4849-8ecd-5b4cfd281e08\",\"name\":\"Get Order ID\",\"type\":\"n8n-nodes-base.code\",\"position\":[-120,420],\"parameters\":{\"jsCode\":\"const callbackData = $json.callback_query.data; // e.g., /order_5832437071968ACSbot\\n\\nconst id = callbackData.match(/^\\\\/order_(\\\\d+)/)?.[1];\\n\\nreturn [{\\n json: {\\n orderId: id,\\n chat_id: $json.callback_query.message.chat.id,\\n message_id: $json.callback_query.message.message_id\\n }\\n}];\"},\"typeVersion\":2},{\"id\":\"22148fd6-8503-4486-b1b1-2c1a947cddab\",\"name\":\"Send Orders to Telegram\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[900,-20],\"parameters\":{\"url\":\"https://api.telegram.org/bot/sendMessage\",\"options\":{},\"sendBody\":true,\"bodyParameters\":{\"parameters\":[{\"name\":\"chat_id\",\"value\":\"={{ $json.chat_id }}\"},{\"name\":\"text\",\"value\":\"={{ $json.text }}\"},{\"name\":\"reply_markup\",\"value\":\"={{ JSON.stringify($json.reply_markup) }}\"}]}},\"typeVersion\":4.2},{\"id\":\"330bc89d-4f23-4401-9f18-e0d9d9743b06\",\"name\":\"Send Order Details\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[900,420],\"webhookId\":\"fd0d23df-37db-4bd1-ae1e-dd03b54e6089\",\"parameters\":{\"text\":\"={{ $json.text }}\",\"chatId\":\"={{ $json.chat_id }}\",\"messageId\":\"={{ $json.message_id }}\",\"operation\":\"editMessageText\",\"additionalFields\":{\"parse_mode\":\"Markdown\"}},\"typeVersion\":1.2}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Orders\":{\"main\":[[{\"node\":\"Send Orders to Telegram\",\"type\":\"main\",\"index\":0}]]},\"No Order\":{\"main\":[[{\"node\":\"Send Orders to Telegram\",\"type\":\"main\",\"index\":0}]]},\"get Order\":{\"main\":[[{\"node\":\"Clean Up Order\",\"type\":\"main\",\"index\":0}]]},\"get Orders\":{\"main\":[[{\"node\":\"Check If There's Any Order\",\"type\":\"main\",\"index\":0}]]},\"Get Order ID\":{\"main\":[[{\"node\":\"get Order\",\"type\":\"main\",\"index\":0}]]},\"Clean Up Order\":{\"main\":[[{\"node\":\"Send Order Details\",\"type\":\"main\",\"index\":0}]]},\"Telegram Trigger\":{\"main\":[[{\"node\":\"Get All Orders/Get An Order Detail\",\"type\":\"main\",\"index\":0}]]},\"Check If There's Any Order\":{\"main\":[[{\"node\":\"Orders\",\"type\":\"main\",\"index\":0}],[{\"node\":\"No Order\",\"type\":\"main\",\"index\":0}]]},\"Get All Orders/Get An Order Detail\":{\"main\":[[{\"node\":\"get Orders\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Get Order ID\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 11, "node_types": {"telegramTrigger": 1, "shopify": 2, "code": 4, "if": 1, "switch": 1, "httpRequest": 1, "telegram": 1}, "services": ["http"], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": true, "has_ai": false}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: ✨ SEO Blog Post Automation with Perplexity, GPT, Leonardo AI & WordPress This workflow automates the creation and publishing of weekly SEO-optimized blog posts using AI and publishes them directly to WordPress — with featured images and tracking in Google Sheets. 🧠 Who is this for This automation is ideal for: Startup platforms and tech blogs Content creators and marketers Solopreneurs who want consistent blog output Spanish-speaking audiences focused on startup trends ⚙️ What it does ⏰ Runs every Monday at 6:00 AM via CRON 📡 Uses Perplexity AI to research trending startup topics 📝 Generates a 1000–1500 word article with GPT in structured HTML 🎨 Creates a cinematic blog image using Leonardo AI 🖼️ Uploads the image to WordPress with alt text and SEO-friendly filename 📰 Publishes the post in"}, {"role": "assistant", "content": "\n**Analyse du besoin**: ✨ SEO Blog Post Automation with Perplexity, GPT, Leonardo AI & WordPress\n\nThis workflow automates the creation and publishing of weekly SEO-optimized blog posts using AI and publishes them directly to...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 13 nodes utilisant ai, google, http.\nStructure: logique conditionnelle, code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"OcdRRO25OfTnrILJ\",\"meta\":{\"instanceId\":\"d97a35efa9230ba825e389dcf8247ce5a77a88f4113df9825ba41d6ce9398085\",\"templateId\":\"4352\",\"templateCredsSetupCompleted\":true},\"name\":\"Blog Post : Tendencias Ecosistema\",\"tags\":[],\"nodes\":[{\"id\":\"cc9b1e41-aaeb-43fb-a283-e3faf397cc73\",\"name\":\"Schedule Trigger\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"position\":[-1480,610],\"parameters\":{\"rule\":{\"interval\":[{\"field\":\"cronExpression\",\"expression\":\"0 6 * * 1\"}]}},\"typeVersion\":1.2},{\"id\":\"01d0a3b7-66db-4032-b7d7-7a7b273920a7\",\"name\":\"Research Topic- Perplexity\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-1260,610],\"parameters\":{\"url\":\"https://api.perplexity.ai/chat/completions\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"model\\\": \\\"sonar-pro\\\",\\n \\\"messages\\\": [\\n {\\n \\\"role\\\": \\\"system\\\",\\n \\\"content\\\": \\\"Eres un asistente experto en generar artículos SEO en español neutro sobre startups tecnológicas. El tono debe ser educativo, práctico, reflexivo e inspirador.\\\"\\n },\\n {\\n \\\"role\\\": \\\"user\\\",\\n \\\"content\\\": \\\"Redacta un artículo basado en la tendencia más relevante del ecosistema de startups tecnológicas hispanohablantes del día.\\\\n\\\\nDevuelve la respuesta estrictamente en formato JSON con esta estructura:\\\\n{\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"[título atractivo en una sola línea]\\\\\\\",\\\\n \\\\\\\"content\\\\\\\": \\\\\\\"[cuerpo del artículo en HTML limpio, sin caracteres escapados, sin markdown, sin saltos \\\\\\\\n, y sin comentarios externos. Usar solo etiquetas estándar de HTML como

,

,
    ,
  • , y . No uses etiquetas personalizadas ni scripts.]\\\\\\\"\\\\n}\\\\n\\\\nEl artículo debe:\\\\n- Tener entre 1000 y 1500 palabras.\\\\n- Incluir subtítulos usando

    .\\\\n- Iniciar con un gancho atractivo de máximo 3 frases dentro de

    .\\\\n- Incluir al menos 2 datos estadísticos actuales con fuente (en texto).\\\\n- Ofrecer mínimo 3 consejos útiles, en formato de lista con

      y
    • .\\\\n- Terminar con una reflexión motivadora e invitación a sumarse a la comunidad (sin enlaces).\\\\n- Usar naturalmente palabras clave como: startups tecnológicas, innovación, emprendimiento, inversión, comunidad.\\\\n\\\\nNo agregues ningún texto ni explicación fuera del objeto JSON.\\\"\\n }\\n ]\\n}\\n\",\"sendBody\":true,\"specifyBody\":\"json\",\"authentication\":\"predefinedCredentialType\",\"nodeCredentialType\":\"perplexityApi\"},\"typeVersion\":4.2},{\"id\":\"f70d8187-0f57-4680-8155-420d060536f0\",\"name\":\"Crear Post en Wordpress\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[860,760],\"parameters\":{\"url\":\"https://cristiantala.com/wp-json/wp/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"title\\\": \\\"{{ $('Get Title, Content, and Image FileName').item.json.title }}\\\",\\n \\\"content\\\": \\\"{{ $('Get Title, Content, and Image FileName').item.json.content }}\\\",\\n \\\"status\\\": \\\"publish\\\",\\n \\\"categories\\\": [\\n 916\\n ],\\n \\\"featured_media\\\": {{ $('Upload Image to Wordpress').item.json.id }}\\n}\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"authentication\":\"genericCredentialType\",\"genericAuthType\":\"httpBasicAuth\"},\"retryOnFail\":true,\"typeVersion\":4.2},{\"id\":\"b306aff7-c8b0-4bf7-9eb1-d8eeee45da6e\",\"name\":\"Message a model\",\"type\":\"@n8n/n8n-nodes-langchain.openAi\",\"position\":[-820,610],\"parameters\":{\"modelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4.1-mini\",\"cachedResultName\":\"GPT-4.1-MINI\"},\"options\":{},\"messages\":{\"values\":[{\"content\":\"=Generate a single-line English description of an editorial-style image to visually represent the following article.\\n\\nThe image must follow these rules:\\n- Cinematic, editorial look (not cartoonish or abstract).\\n- No visible text or logos.\\n- Must work for a blog post featured image in Google News and Discover (ideal size: 1200x628 px).\\n- The article title is: \\\"{{ $json.title }}\\\"\\n- Article content: {{ $json.content }}.\\n\\nOutput just the English prompt, without quotes or formatting.\"},{\"role\":\"system\",\"content\":\"You are an expert in crafting AI image generation prompts for editorial and news images. You help generate cinematic, editorial-style prompts for blog images that perform well in Google News and Google Discover. Avoid any text or logos in the result.\"}]}},\"typeVersion\":1.8},{\"id\":\"e3786cd7-baac-4e9e-bd45-63ec3b5cfd5e\",\"name\":\"Upload Image to Wordpress\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[420,760],\"parameters\":{\"url\":\"https://cristiantala.com/wp-json/wp/v2/media\",\"method\":\"POST\",\"options\":{},\"sendBody\":true,\"contentType\":\"binaryData\",\"sendHeaders\":true,\"authentication\":\"genericCredentialType\",\"genericAuthType\":\"httpBasicAuth\",\"headerParameters\":{\"parameters\":[{\"name\":\"Content-Disposition\",\"value\":\"=attachment; filename=\\\"{{ $('Get Title, Content, and Image FileName').item.json.image_filename }}\\\"\"},{\"name\":\"Content-Type\",\"value\":\"image/jpeg\"}]},\"inputDataFieldName\":\"data\"},\"retryOnFail\":true,\"typeVersion\":4.2},{\"id\":\"bd779c40-a90d-4412-935a-7adc30e431fc\",\"name\":\"If\",\"type\":\"n8n-nodes-base.if\",\"position\":[-20,560],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"132de601-8ca1-46b4-9ae3-67baa33f28ad\",\"operator\":{\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.generations_by_pk.status }}\",\"rightValue\":\"COMPLETE\"}]}},\"typeVersion\":2.2},{\"id\":\"24b8ff73-0eff-41ce-b99b-27d4210838ac\",\"name\":\"Wait\",\"type\":\"n8n-nodes-base.wait\",\"position\":[200,560],\"webhookId\":\"d14af83a-15dc-4387-adf9-0f8b785faa0c\",\"parameters\":{},\"typeVersion\":1.1},{\"id\":\"072b61c5-7494-42cd-808f-bb311605f4a3\",\"name\":\"Get Leonardo Image Status\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-240,610],\"parameters\":{\"url\":\"=https://cloud.leonardo.ai/api/rest/v1/generations/{{ $json.sdGenerationJob.generationId }}\",\"options\":{},\"sendHeaders\":true,\"authentication\":\"genericCredentialType\",\"genericAuthType\":\"httpBearerAuth\",\"headerParameters\":{\"parameters\":[{\"name\":\"accept\",\"value\":\"application/json\"}]}},\"retryOnFail\":true,\"typeVersion\":4.2},{\"id\":\"da14ecc4-ca0f-445e-9c87-0148a602bfc2\",\"name\":\"Get Leonardo Image\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[200,760],\"parameters\":{\"url\":\"={{ $json.generations_by_pk.generated_images[0].url }}\",\"options\":{}},\"retryOnFail\":true,\"typeVersion\":4.2},{\"id\":\"02b052f2-0771-42b3-b4e8-526375654118\",\"name\":\"Agregar ALT a la Imagen\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[640,760],\"parameters\":{\"url\":\"=https://cristiantala.com/wp-json/wp/v2/media/{{ $json.id }}\",\"method\":\"PUT\",\"options\":{},\"sendBody\":true,\"authentication\":\"genericCredentialType\",\"bodyParameters\":{\"parameters\":[{\"name\":\"alt_text\",\"value\":\"={{ $('Message a model').item.json.message.content }}\"}]},\"genericAuthType\":\"httpBasicAuth\"},\"retryOnFail\":true,\"typeVersion\":4.2},{\"id\":\"07078bdd-6d8e-485e-9581-e359361feba9\",\"name\":\"Publicaciones Wordpress Startups y Tecnología\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[1080,760],\"parameters\":{\"columns\":{\"value\":{\"URL\":\"={{ $json.guid.raw }}\",\"Tipo\":\"Post WP\",\"Topic\":\"={{ $json.title.rendered }}\",\"Status\":\"Posted\",\"URL Imagen\":\"={{ $('Upload Image to Wordpress').item.json.guid.rendered }}\",\"Contenido AI\":\"={{ $json.content.raw }}\",\"Fecha del Posteo\":\"={{ $json.date }}\"},\"schema\":[{\"id\":\"Topic\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"Topic\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"Tipo\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"Tipo\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"Status\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"Status\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"Contenido AI\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"Contenido AI\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"Fecha del Posteo\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"Fecha del Posteo\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"URL\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"URL\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"URL Imagen\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"URL Imagen\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[\"Topic\"],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{},\"operation\":\"appendOrUpdate\",\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gid=0\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1s3HKV8M3U8NvOp1CxERz8tnC9ibYmnB4Pztgv1ZjkOQ/edit#gid=0\",\"cachedResultName\":\"Hoja 1\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1s3HKV8M3U8NvOp1CxERz8tnC9ibYmnB4Pztgv1ZjkOQ\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1s3HKV8M3U8NvOp1CxERz8tnC9ibYmnB4Pztgv1ZjkOQ/edit?usp=drivesdk\",\"cachedResultName\":\"Publicaciones RRSS\"}},\"typeVersion\":4.5},{\"id\":\"ce87f8ee-3d53-462c-9df5-921fdc42d17c\",\"name\":\"Leonardo: Create Post Image\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-460,610],\"parameters\":{\"url\":\"https://cloud.leonardo.ai/api/rest/v1/generations\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"prompt\\\": \\\"{{ $json.message.content }}\\\",\\n \\\"modelId\\\": \\\"6bef9f1b-29cb-40c7-b9df-32b51c1f67d3\\\",\\n \\\"width\\\": 1280,\\n \\\"height\\\": 720,\\n \\\"sd_version\\\": \\\"v2\\\",\\n \\\"num_images\\\": 1,\\n \\\"promptMagic\\\": true,\\n \\\"promptMagicStrength\\\": 0.5,\\n \\\"public\\\": false,\\n \\\"scheduler\\\": \\\"LEONARDO\\\",\\n \\\"guidance_scale\\\": 7\\n}\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"authentication\":\"genericCredentialType\",\"genericAuthType\":\"httpBearerAuth\",\"headerParameters\":{\"parameters\":[{\"name\":\"accept\",\"value\":\"application/json\"}]}},\"retryOnFail\":true,\"typeVersion\":4.2},{\"id\":\"c8e83410-b334-4c2e-8095-0d424dd8455f\",\"name\":\"Get Title, Content, and Image FileName\",\"type\":\"n8n-nodes-base.code\",\"position\":[-1040,610],\"parameters\":{\"jsCode\":\"const data = JSON.parse($input.first().json.choices[0].message.content);\\n\\n// Función para generar slug SEO-friendly\\nfunction toSlug(text) {\\n return text\\n .toLowerCase()\\n .normalize(\\\"NFD\\\") // elimina acentos\\n .replace(/[\\\\u0300-\\\\u036f]/g, \\\"\\\") // elimina diacríticos\\n .replace(/[^a-z0-9\\\\s-]/g, \\\"\\\") // elimina caracteres especiales\\n .replace(/\\\\s+/g, \\\"-\\\") // reemplaza espacios por guiones\\n .replace(/-+/g, \\\"-\\\") // evita guiones dobles\\n .replace(/^-|-$/g, \\\"\\\"); // quita guiones iniciales y finales\\n}\\n\\nconst imageName = toSlug(data.title) + \\\".jpg\\\";\\n\\nreturn [\\n {\\n json: {\\n title: data.title,\\n content: data.content,\\n image_filename: imageName\\n }\\n }\\n];\\n\"},\"typeVersion\":2}],\"active\":true,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"If\":{\"main\":[[{\"node\":\"Get Leonardo Image\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Wait\",\"type\":\"main\",\"index\":0}]]},\"Wait\":{\"main\":[[{\"node\":\"Get Leonardo Image Status\",\"type\":\"main\",\"index\":0}]]},\"Message a model\":{\"main\":[[{\"node\":\"Leonardo: Create Post Image\",\"type\":\"main\",\"index\":0}]]},\"Schedule Trigger\":{\"main\":[[{\"node\":\"Research Topic- Perplexity\",\"type\":\"main\",\"index\":0}]]},\"Get Leonardo Image\":{\"main\":[[{\"node\":\"Upload Image to Wordpress\",\"type\":\"main\",\"index\":0}]]},\"Agregar ALT a la Imagen\":{\"main\":[[{\"node\":\"Crear Post en Wordpress\",\"type\":\"main\",\"index\":0}]]},\"Crear Post en Wordpress\":{\"main\":[[{\"node\":\"Publicaciones Wordpress Startups y Tecnología\",\"type\":\"main\",\"index\":0}]]},\"Get Leonardo Image Status\":{\"main\":[[{\"node\":\"If\",\"type\":\"main\",\"index\":0}]]},\"Upload Image to Wordpress\":{\"main\":[[{\"node\":\"Agregar ALT a la Imagen\",\"type\":\"main\",\"index\":0}]]},\"Research Topic- Perplexity\":{\"main\":[[{\"node\":\"Get Title, Content, and Image FileName\",\"type\":\"main\",\"index\":0}]]},\"Leonardo: Create Post Image\":{\"main\":[[{\"node\":\"Get Leonardo Image Status\",\"type\":\"main\",\"index\":0}]]},\"Get Title, Content, and Image FileName\":{\"main\":[[{\"node\":\"Message a model\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 13, "node_types": {"scheduleTrigger": 1, "httpRequest": 7, "openAi": 1, "if": 1, "wait": 1, "googleSheets": 1, "code": 1}, "services": ["ai", "google", "http"], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Auto-Generate SEO Blog Posts with Perplexity, GPT, Leonardo & WordPress"}, {"role": "assistant", "content": "\n**Analyse du besoin**: ✨ SEO Blog Post Automation with Perplexity, GPT, Leonardo AI & WordPress\n\nThis workflow automates the creation and publishing of weekly SEO-optimized blog posts using AI and publishes them directly to...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 13 nodes utilisant ai, google, http.\nStructure: logique conditionnelle, code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"OcdRRO25OfTnrILJ\",\"meta\":{\"instanceId\":\"d97a35efa9230ba825e389dcf8247ce5a77a88f4113df9825ba41d6ce9398085\",\"templateId\":\"4352\",\"templateCredsSetupCompleted\":true},\"name\":\"Blog Post : Tendencias Ecosistema\",\"tags\":[],\"nodes\":[{\"id\":\"cc9b1e41-aaeb-43fb-a283-e3faf397cc73\",\"name\":\"Schedule Trigger\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"position\":[-1480,610],\"parameters\":{\"rule\":{\"interval\":[{\"field\":\"cronExpression\",\"expression\":\"0 6 * * 1\"}]}},\"typeVersion\":1.2},{\"id\":\"01d0a3b7-66db-4032-b7d7-7a7b273920a7\",\"name\":\"Research Topic- Perplexity\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-1260,610],\"parameters\":{\"url\":\"https://api.perplexity.ai/chat/completions\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"model\\\": \\\"sonar-pro\\\",\\n \\\"messages\\\": [\\n {\\n \\\"role\\\": \\\"system\\\",\\n \\\"content\\\": \\\"Eres un asistente experto en generar artículos SEO en español neutro sobre startups tecnológicas. El tono debe ser educativo, práctico, reflexivo e inspirador.\\\"\\n },\\n {\\n \\\"role\\\": \\\"user\\\",\\n \\\"content\\\": \\\"Redacta un artículo basado en la tendencia más relevante del ecosistema de startups tecnológicas hispanohablantes del día.\\\\n\\\\nDevuelve la respuesta estrictamente en formato JSON con esta estructura:\\\\n{\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"[título atractivo en una sola línea]\\\\\\\",\\\\n \\\\\\\"content\\\\\\\": \\\\\\\"[cuerpo del artículo en HTML limpio, sin caracteres escapados, sin markdown, sin saltos \\\\\\\\n, y sin comentarios externos. Usar solo etiquetas estándar de HTML como

      ,

      ,
        ,
      • , y . No uses etiquetas personalizadas ni scripts.]\\\\\\\"\\\\n}\\\\n\\\\nEl artículo debe:\\\\n- Tener entre 1000 y 1500 palabras.\\\\n- Incluir subtítulos usando

        .\\\\n- Iniciar con un gancho atractivo de máximo 3 frases dentro de

        .\\\\n- Incluir al menos 2 datos estadísticos actuales con fuente (en texto).\\\\n- Ofrecer mínimo 3 consejos útiles, en formato de lista con

          y
        • .\\\\n- Terminar con una reflexión motivadora e invitación a sumarse a la comunidad (sin enlaces).\\\\n- Usar naturalmente palabras clave como: startups tecnológicas, innovación, emprendimiento, inversión, comunidad.\\\\n\\\\nNo agregues ningún texto ni explicación fuera del objeto JSON.\\\"\\n }\\n ]\\n}\\n\",\"sendBody\":true,\"specifyBody\":\"json\",\"authentication\":\"predefinedCredentialType\",\"nodeCredentialType\":\"perplexityApi\"},\"typeVersion\":4.2},{\"id\":\"f70d8187-0f57-4680-8155-420d060536f0\",\"name\":\"Crear Post en Wordpress\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[860,760],\"parameters\":{\"url\":\"https://cristiantala.com/wp-json/wp/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"title\\\": \\\"{{ $('Get Title, Content, and Image FileName').item.json.title }}\\\",\\n \\\"content\\\": \\\"{{ $('Get Title, Content, and Image FileName').item.json.content }}\\\",\\n \\\"status\\\": \\\"publish\\\",\\n \\\"categories\\\": [\\n 916\\n ],\\n \\\"featured_media\\\": {{ $('Upload Image to Wordpress').item.json.id }}\\n}\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"authentication\":\"genericCredentialType\",\"genericAuthType\":\"httpBasicAuth\"},\"retryOnFail\":true,\"typeVersion\":4.2},{\"id\":\"b306aff7-c8b0-4bf7-9eb1-d8eeee45da6e\",\"name\":\"Message a model\",\"type\":\"@n8n/n8n-nodes-langchain.openAi\",\"position\":[-820,610],\"parameters\":{\"modelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4.1-mini\",\"cachedResultName\":\"GPT-4.1-MINI\"},\"options\":{},\"messages\":{\"values\":[{\"content\":\"=Generate a single-line English description of an editorial-style image to visually represent the following article.\\n\\nThe image must follow these rules:\\n- Cinematic, editorial look (not cartoonish or abstract).\\n- No visible text or logos.\\n- Must work for a blog post featured image in Google News and Discover (ideal size: 1200x628 px).\\n- The article title is: \\\"{{ $json.title }}\\\"\\n- Article content: {{ $json.content }}.\\n\\nOutput just the English prompt, without quotes or formatting.\"},{\"role\":\"system\",\"content\":\"You are an expert in crafting AI image generation prompts for editorial and news images. You help generate cinematic, editorial-style prompts for blog images that perform well in Google News and Google Discover. Avoid any text or logos in the result.\"}]}},\"typeVersion\":1.8},{\"id\":\"e3786cd7-baac-4e9e-bd45-63ec3b5cfd5e\",\"name\":\"Upload Image to Wordpress\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[420,760],\"parameters\":{\"url\":\"https://cristiantala.com/wp-json/wp/v2/media\",\"method\":\"POST\",\"options\":{},\"sendBody\":true,\"contentType\":\"binaryData\",\"sendHeaders\":true,\"authentication\":\"genericCredentialType\",\"genericAuthType\":\"httpBasicAuth\",\"headerParameters\":{\"parameters\":[{\"name\":\"Content-Disposition\",\"value\":\"=attachment; filename=\\\"{{ $('Get Title, Content, and Image FileName').item.json.image_filename }}\\\"\"},{\"name\":\"Content-Type\",\"value\":\"image/jpeg\"}]},\"inputDataFieldName\":\"data\"},\"retryOnFail\":true,\"typeVersion\":4.2},{\"id\":\"bd779c40-a90d-4412-935a-7adc30e431fc\",\"name\":\"If\",\"type\":\"n8n-nodes-base.if\",\"position\":[-20,560],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"132de601-8ca1-46b4-9ae3-67baa33f28ad\",\"operator\":{\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.generations_by_pk.status }}\",\"rightValue\":\"COMPLETE\"}]}},\"typeVersion\":2.2},{\"id\":\"24b8ff73-0eff-41ce-b99b-27d4210838ac\",\"name\":\"Wait\",\"type\":\"n8n-nodes-base.wait\",\"position\":[200,560],\"webhookId\":\"d14af83a-15dc-4387-adf9-0f8b785faa0c\",\"parameters\":{},\"typeVersion\":1.1},{\"id\":\"072b61c5-7494-42cd-808f-bb311605f4a3\",\"name\":\"Get Leonardo Image Status\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-240,610],\"parameters\":{\"url\":\"=https://cloud.leonardo.ai/api/rest/v1/generations/{{ $json.sdGenerationJob.generationId }}\",\"options\":{},\"sendHeaders\":true,\"authentication\":\"genericCredentialType\",\"genericAuthType\":\"httpBearerAuth\",\"headerParameters\":{\"parameters\":[{\"name\":\"accept\",\"value\":\"application/json\"}]}},\"retryOnFail\":true,\"typeVersion\":4.2},{\"id\":\"da14ecc4-ca0f-445e-9c87-0148a602bfc2\",\"name\":\"Get Leonardo Image\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[200,760],\"parameters\":{\"url\":\"={{ $json.generations_by_pk.generated_images[0].url }}\",\"options\":{}},\"retryOnFail\":true,\"typeVersion\":4.2},{\"id\":\"02b052f2-0771-42b3-b4e8-526375654118\",\"name\":\"Agregar ALT a la Imagen\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[640,760],\"parameters\":{\"url\":\"=https://cristiantala.com/wp-json/wp/v2/media/{{ $json.id }}\",\"method\":\"PUT\",\"options\":{},\"sendBody\":true,\"authentication\":\"genericCredentialType\",\"bodyParameters\":{\"parameters\":[{\"name\":\"alt_text\",\"value\":\"={{ $('Message a model').item.json.message.content }}\"}]},\"genericAuthType\":\"httpBasicAuth\"},\"retryOnFail\":true,\"typeVersion\":4.2},{\"id\":\"07078bdd-6d8e-485e-9581-e359361feba9\",\"name\":\"Publicaciones Wordpress Startups y Tecnología\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[1080,760],\"parameters\":{\"columns\":{\"value\":{\"URL\":\"={{ $json.guid.raw }}\",\"Tipo\":\"Post WP\",\"Topic\":\"={{ $json.title.rendered }}\",\"Status\":\"Posted\",\"URL Imagen\":\"={{ $('Upload Image to Wordpress').item.json.guid.rendered }}\",\"Contenido AI\":\"={{ $json.content.raw }}\",\"Fecha del Posteo\":\"={{ $json.date }}\"},\"schema\":[{\"id\":\"Topic\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"Topic\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"Tipo\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"Tipo\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"Status\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"Status\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"Contenido AI\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"Contenido AI\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"Fecha del Posteo\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"Fecha del Posteo\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"URL\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"URL\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"URL Imagen\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"URL Imagen\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[\"Topic\"],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{},\"operation\":\"appendOrUpdate\",\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gid=0\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1s3HKV8M3U8NvOp1CxERz8tnC9ibYmnB4Pztgv1ZjkOQ/edit#gid=0\",\"cachedResultName\":\"Hoja 1\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1s3HKV8M3U8NvOp1CxERz8tnC9ibYmnB4Pztgv1ZjkOQ\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1s3HKV8M3U8NvOp1CxERz8tnC9ibYmnB4Pztgv1ZjkOQ/edit?usp=drivesdk\",\"cachedResultName\":\"Publicaciones RRSS\"}},\"typeVersion\":4.5},{\"id\":\"ce87f8ee-3d53-462c-9df5-921fdc42d17c\",\"name\":\"Leonardo: Create Post Image\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-460,610],\"parameters\":{\"url\":\"https://cloud.leonardo.ai/api/rest/v1/generations\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"prompt\\\": \\\"{{ $json.message.content }}\\\",\\n \\\"modelId\\\": \\\"6bef9f1b-29cb-40c7-b9df-32b51c1f67d3\\\",\\n \\\"width\\\": 1280,\\n \\\"height\\\": 720,\\n \\\"sd_version\\\": \\\"v2\\\",\\n \\\"num_images\\\": 1,\\n \\\"promptMagic\\\": true,\\n \\\"promptMagicStrength\\\": 0.5,\\n \\\"public\\\": false,\\n \\\"scheduler\\\": \\\"LEONARDO\\\",\\n \\\"guidance_scale\\\": 7\\n}\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"authentication\":\"genericCredentialType\",\"genericAuthType\":\"httpBearerAuth\",\"headerParameters\":{\"parameters\":[{\"name\":\"accept\",\"value\":\"application/json\"}]}},\"retryOnFail\":true,\"typeVersion\":4.2},{\"id\":\"c8e83410-b334-4c2e-8095-0d424dd8455f\",\"name\":\"Get Title, Content, and Image FileName\",\"type\":\"n8n-nodes-base.code\",\"position\":[-1040,610],\"parameters\":{\"jsCode\":\"const data = JSON.parse($input.first().json.choices[0].message.content);\\n\\n// Función para generar slug SEO-friendly\\nfunction toSlug(text) {\\n return text\\n .toLowerCase()\\n .normalize(\\\"NFD\\\") // elimina acentos\\n .replace(/[\\\\u0300-\\\\u036f]/g, \\\"\\\") // elimina diacríticos\\n .replace(/[^a-z0-9\\\\s-]/g, \\\"\\\") // elimina caracteres especiales\\n .replace(/\\\\s+/g, \\\"-\\\") // reemplaza espacios por guiones\\n .replace(/-+/g, \\\"-\\\") // evita guiones dobles\\n .replace(/^-|-$/g, \\\"\\\"); // quita guiones iniciales y finales\\n}\\n\\nconst imageName = toSlug(data.title) + \\\".jpg\\\";\\n\\nreturn [\\n {\\n json: {\\n title: data.title,\\n content: data.content,\\n image_filename: imageName\\n }\\n }\\n];\\n\"},\"typeVersion\":2}],\"active\":true,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"If\":{\"main\":[[{\"node\":\"Get Leonardo Image\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Wait\",\"type\":\"main\",\"index\":0}]]},\"Wait\":{\"main\":[[{\"node\":\"Get Leonardo Image Status\",\"type\":\"main\",\"index\":0}]]},\"Message a model\":{\"main\":[[{\"node\":\"Leonardo: Create Post Image\",\"type\":\"main\",\"index\":0}]]},\"Schedule Trigger\":{\"main\":[[{\"node\":\"Research Topic- Perplexity\",\"type\":\"main\",\"index\":0}]]},\"Get Leonardo Image\":{\"main\":[[{\"node\":\"Upload Image to Wordpress\",\"type\":\"main\",\"index\":0}]]},\"Agregar ALT a la Imagen\":{\"main\":[[{\"node\":\"Crear Post en Wordpress\",\"type\":\"main\",\"index\":0}]]},\"Crear Post en Wordpress\":{\"main\":[[{\"node\":\"Publicaciones Wordpress Startups y Tecnología\",\"type\":\"main\",\"index\":0}]]},\"Get Leonardo Image Status\":{\"main\":[[{\"node\":\"If\",\"type\":\"main\",\"index\":0}]]},\"Upload Image to Wordpress\":{\"main\":[[{\"node\":\"Agregar ALT a la Imagen\",\"type\":\"main\",\"index\":0}]]},\"Research Topic- Perplexity\":{\"main\":[[{\"node\":\"Get Title, Content, and Image FileName\",\"type\":\"main\",\"index\":0}]]},\"Leonardo: Create Post Image\":{\"main\":[[{\"node\":\"Get Leonardo Image Status\",\"type\":\"main\",\"index\":0}]]},\"Get Title, Content, and Image FileName\":{\"main\":[[{\"node\":\"Message a model\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 13, "node_types": {"scheduleTrigger": 1, "httpRequest": 7, "openAi": 1, "if": 1, "wait": 1, "googleSheets": 1, "code": 1}, "services": ["ai", "google", "http"], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: This n8n workflow template creates an intelligent data analysis chatbot that can answer questions about data stored in Google Sheets using OpenAI's GPT-5 Mini model. The system automatically analyzes your spreadsheet data and provides insights through natural language conversations. What This Workflow Does Chat Interface: Provides a conversational interface for asking questions about your data Smart Data Analysis: Uses AI to understand column structures and data relationships Google Sheets Integration: Connects directly to your Google Sheets data Memory Buffer: Maintains conversation context for follow-up questions Automated Column Detection: Automatically identifies and describes your data columns 🚀 Try It Out! 1. Set Up OpenAI Connection Get Your API Key Visit the OpenAI API Keys page. G"}, {"role": "assistant", "content": "\n**Analyse du besoin**: This n8n workflow template creates an intelligent data analysis chatbot that can answer questions about data stored in Google Sheets using OpenAI's GPT-5 Mini model. The system automatically analyzes ...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 5 nodes utilisant ai, google.\nStructure: intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"meta\":{\"instanceId\":\"ad0113c344ee237399e44e9f11798b05baeb83a6196d514a9ae9d2ad71c3b5c9\",\"templateCredsSetupCompleted\":true},\"nodes\":[{\"id\":\"5b054044-5814-47aa-99b4-0a9c5a601bad\",\"name\":\"Analyze Data\",\"type\":\"n8n-nodes-base.googleSheetsTool\",\"position\":[784,1328],\"parameters\":{\"options\":{},\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":365710158,\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1UDWt0-Z9fHqwnSNfU3vvhSoYCFG6EG3E-ZewJC_CLq4/edit#gid=365710158\",\"cachedResultName\":\"Data\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1UDWt0-Z9fHqwnSNfU3vvhSoYCFG6EG3E-ZewJC_CLq4\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1UDWt0-Z9fHqwnSNfU3vvhSoYCFG6EG3E-ZewJC_CLq4/edit?usp=drivesdk\",\"cachedResultName\":\"Sample Marketing Data - n8n\"}},\"typeVersion\":4.7},{\"id\":\"a6869994-77e8-4f5d-916c-cc40f0b5ab7e\",\"name\":\"OpenAI Chat Model\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[224,1312],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4.1-nano\",\"cachedResultName\":\"gpt-4.1-nano\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"2ecbc678-f948-4435-bc3a-e66718810b33\",\"name\":\"Talk to Your Data\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[704,688],\"parameters\":{\"options\":{\"systemMessage\":\"Google Sheets Ask-YOUR_OPENAI_KEY_HERE \\n\\n\\nYou are Ask-YOUR_OPENAI_KEY_HERE. Answer questions using Google Sheets ONLY via the tool below. Be precise and conservative. \\n\\nThere is only one dataset. dont ask what dataset it is. \\n\\nUse the data tool to answer the question.\"},\"hasOutputParser\":true},\"typeVersion\":2.2},{\"id\":\"93c92fba-07f8-416f-952b-3b001e8294e0\",\"name\":\"Chat with Your Data\",\"type\":\"@n8n/n8n-nodes-langchain.chatTrigger\",\"position\":[192,848],\"webhookId\":\"edca0f0a-77c3-43e5-8ece-e514a29446f5\",\"parameters\":{\"options\":{}},\"typeVersion\":1.3},{\"id\":\"713d398d-fb27-42b2-bb39-21ef8f8f97df\",\"name\":\"Memory\",\"type\":\"@n8n/n8n-nodes-langchain.memoryBufferWindow\",\"position\":[736,880],\"parameters\":{},\"typeVersion\":1.3}],\"connections\":{\"Memory\":{\"ai_memory\":[[{\"node\":\"Talk to Your Data\",\"type\":\"ai_memory\",\"index\":0}]]},\"Analyze Data\":{\"ai_tool\":[[{\"node\":\"Talk to Your Data\",\"type\":\"ai_tool\",\"index\":0}]]},\"OpenAI Chat Model\":{\"ai_languageModel\":[[{\"node\":\"Talk to Your Data\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Chat with Your Data\":{\"main\":[[{\"node\":\"Talk to Your Data\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 5, "node_types": {"googleSheetsTool": 1, "lmChatOpenAi": 1, "agent": 1, "chatTrigger": 1, "memoryBufferWindow": 1}, "services": ["ai", "google"], "complexity": "simple", "has_conditions": false, "has_loops": false, "has_code": false, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Talk to Your Google Sheets Using ChatGPT-5"}, {"role": "assistant", "content": "\n**Analyse du besoin**: This n8n workflow template creates an intelligent data analysis chatbot that can answer questions about data stored in Google Sheets using OpenAI's GPT-5 Mini model. The system automatically analyzes ...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 5 nodes utilisant ai, google.\nStructure: intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"meta\":{\"instanceId\":\"ad0113c344ee237399e44e9f11798b05baeb83a6196d514a9ae9d2ad71c3b5c9\",\"templateCredsSetupCompleted\":true},\"nodes\":[{\"id\":\"5b054044-5814-47aa-99b4-0a9c5a601bad\",\"name\":\"Analyze Data\",\"type\":\"n8n-nodes-base.googleSheetsTool\",\"position\":[784,1328],\"parameters\":{\"options\":{},\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":365710158,\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1UDWt0-Z9fHqwnSNfU3vvhSoYCFG6EG3E-ZewJC_CLq4/edit#gid=365710158\",\"cachedResultName\":\"Data\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1UDWt0-Z9fHqwnSNfU3vvhSoYCFG6EG3E-ZewJC_CLq4\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1UDWt0-Z9fHqwnSNfU3vvhSoYCFG6EG3E-ZewJC_CLq4/edit?usp=drivesdk\",\"cachedResultName\":\"Sample Marketing Data - n8n\"}},\"typeVersion\":4.7},{\"id\":\"a6869994-77e8-4f5d-916c-cc40f0b5ab7e\",\"name\":\"OpenAI Chat Model\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[224,1312],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4.1-nano\",\"cachedResultName\":\"gpt-4.1-nano\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"2ecbc678-f948-4435-bc3a-e66718810b33\",\"name\":\"Talk to Your Data\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[704,688],\"parameters\":{\"options\":{\"systemMessage\":\"Google Sheets Ask-YOUR_OPENAI_KEY_HERE \\n\\n\\nYou are Ask-YOUR_OPENAI_KEY_HERE. Answer questions using Google Sheets ONLY via the tool below. Be precise and conservative. \\n\\nThere is only one dataset. dont ask what dataset it is. \\n\\nUse the data tool to answer the question.\"},\"hasOutputParser\":true},\"typeVersion\":2.2},{\"id\":\"93c92fba-07f8-416f-952b-3b001e8294e0\",\"name\":\"Chat with Your Data\",\"type\":\"@n8n/n8n-nodes-langchain.chatTrigger\",\"position\":[192,848],\"webhookId\":\"edca0f0a-77c3-43e5-8ece-e514a29446f5\",\"parameters\":{\"options\":{}},\"typeVersion\":1.3},{\"id\":\"713d398d-fb27-42b2-bb39-21ef8f8f97df\",\"name\":\"Memory\",\"type\":\"@n8n/n8n-nodes-langchain.memoryBufferWindow\",\"position\":[736,880],\"parameters\":{},\"typeVersion\":1.3}],\"connections\":{\"Memory\":{\"ai_memory\":[[{\"node\":\"Talk to Your Data\",\"type\":\"ai_memory\",\"index\":0}]]},\"Analyze Data\":{\"ai_tool\":[[{\"node\":\"Talk to Your Data\",\"type\":\"ai_tool\",\"index\":0}]]},\"OpenAI Chat Model\":{\"ai_languageModel\":[[{\"node\":\"Talk to Your Data\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Chat with Your Data\":{\"main\":[[{\"node\":\"Talk to Your Data\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 5, "node_types": {"googleSheetsTool": 1, "lmChatOpenAi": 1, "agent": 1, "chatTrigger": 1, "memoryBufferWindow": 1}, "services": ["ai", "google"], "complexity": "simple", "has_conditions": false, "has_loops": false, "has_code": false, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: This workflow automatically fetches reviews for one or more Google Play Store apps, summarizes the feedback using OpenAI, stores and manages review data with Pinecone, and posts the summary to a Slack channel. It is designed for product teams, community managers, or anyone who wants to keep track of app sentiment and review trends without manually reading each review. Features: Fetches daily reviews for specified Google Play Store app bundle IDs using a Google Service Account. Stores reviews in a Pinecone vector database for efficient retrieval and summarization. Uses OpenAI to generate a summary, including: Positive and negative review highlights Star rating breakdown and average rating Total number of reviews processed Posts the summary to a Slack channel of your choice. Supports both da"}, {"role": "assistant", "content": "\n**Analyse du besoin**: This workflow automatically fetches reviews for one or more Google Play Store apps, summarizes the feedback using OpenAI, stores and manages review data with Pinecone, and posts the summary to a Slack...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 19 nodes utilisant ai, slack, http.\nStructure: traitement par lots, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"GE9244KEY5823lcB\",\"meta\":{\"instanceId\":\"fe52080916406a2a9812a7975b2d9b9e9838f3ce0f0b34614c611fb2ca1528d3\"},\"name\":\"Create summary of Google Play Store reviews\",\"tags\":[],\"nodes\":[{\"id\":\"976a0252-5685-4678-83d8-925d06853179\",\"name\":\"Split Out4\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[288,-384],\"parameters\":{\"include\":\"=\",\"options\":{\"destinationFieldName\":\"\"},\"fieldToSplitOut\":\"reviews\"},\"typeVersion\":1},{\"id\":\"9ad91b18-e9c3-4e43-b301-cc833747fbe2\",\"name\":\"Loop Over Items\",\"type\":\"n8n-nodes-base.splitInBatches\",\"onError\":\"continueRegularOutput\",\"position\":[-112,-384],\"parameters\":{\"options\":{\"reset\":false}},\"typeVersion\":3},{\"id\":\"fd00f503-709f-472d-b0c3-8e8d617f8506\",\"name\":\"Loop Over Items1\",\"type\":\"n8n-nodes-base.splitInBatches\",\"onError\":\"continueRegularOutput\",\"position\":[-192,96],\"parameters\":{\"options\":{\"reset\":false}},\"typeVersion\":3},{\"id\":\"c67fa141-8df9-4010-8d46-b038bc540381\",\"name\":\"AI Agent - Summary creator\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"onError\":\"continueErrorOutput\",\"position\":[32,96],\"parameters\":{\"text\":\"=Create a summary of store reviews submitted. Start your message with \\\"Hi! This is your Google Play Store AI agent for *{{$json.app_name}}*\\\". In your output, include the number of reviews you processed to create the summary. The summary should be split into two groups: a summary about positive reviews and a summary about negative reviews. In your summary include also a breakdown of star ratings, ie. how many reviews there were for each star rating. Also include the average star rating.\",\"options\":{\"systemMessage\":\"=Your job is to respond to prompts using the information you gather from the Google Play Store reviews of an app called {{$json.app_name}}. Your main role is to help your users to gain insights from store review without having to read reviews one by one. Store review usually have star ratings with 1 star being the lowest rating and 5 star being the highest rating. They can also have a text description where the user writes a review about their experience with the app. These can be negative reviews or positive reviews. The lower the star rating the more likely that the review is negative.\"},\"promptType\":\"define\"},\"typeVersion\":2},{\"id\":\"83cf0fc5-66cc-4598-b354-6dd0f4f9ef1c\",\"name\":\"Set the bundle ids\",\"type\":\"n8n-nodes-base.set\",\"position\":[-512,-384],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"ed79836f-8032-4daa-afc1-d0170157c8a0\",\"name\":\"=apps\",\"type\":\"array\",\"value\":\"[\\n \\\"com.bundle.id1\\\",\\n \\\"com.bundle.id2\\\",\\n \\\"com.bundle.id3\\\"\\n]\"}]}},\"typeVersion\":3.4},{\"id\":\"0bcfc993-e58e-49d6-aeba-ad7accb2087b\",\"name\":\"Daily Trigger\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"notes\":\"Daily at 10am \",\"position\":[-720,-384],\"parameters\":{\"rule\":{\"interval\":[{\"triggerAtHour\":10}]}},\"notesInFlow\":true,\"typeVersion\":1.2},{\"id\":\"53df7cef-c399-48a5-bd10-82ec4547999a\",\"name\":\"Split Out\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-288,-384],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"apps\"},\"typeVersion\":1},{\"id\":\"68a7de8f-ad17-4b8b-8a5e-fba73b66794f\",\"name\":\"HTTP Request\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[112,-384],\"parameters\":{\"url\":\"=https://androidpublisher.googleapis.com/androidpublisher/v3/applications/{{$json.apps}}/reviews\",\"options\":{\"pagination\":{\"pagination\":{\"parameters\":{\"parameters\":[{\"name\":\"token\",\"value\":\"={{$response.body.tokenPagination.nextPageToken}}\"}]},\"maxRequests\":10,\"requestInterval\":10,\"limitPagesFetched\":true,\"completeExpression\":\"={{$response.body.tokenPagination.nextPageToken == null}}\",\"paginationCompleteWhen\":\"other\"}}},\"authentication\":\"predefinedCredentialType\",\"nodeCredentialType\":\"googleApi\"},\"typeVersion\":4.2,\"alwaysOutputData\":true},{\"id\":\"beb2b08e-f53d-4b36-82a8-ae282ae477ba\",\"name\":\"Filter\",\"type\":\"n8n-nodes-base.filter\",\"notes\":\"Fetch yesterday's reviews\",\"position\":[496,-384],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"e5cc101a-9e06-4f33-8578-63c4acc66042\",\"operator\":{\"type\":\"dateTime\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.reviews.comments[0].userComment.lastModified.seconds.toDateTime('s').toISODate() }}\",\"rightValue\":\"={{$today.minus({days: 1})}}\\n\"}]}},\"notesInFlow\":true,\"typeVersion\":2.2,\"alwaysOutputData\":true},{\"id\":\"3107ffd9-94ea-43ef-9fad-d0c8c75c32b4\",\"name\":\"Pinecone Vector Store\",\"type\":\"@n8n/n8n-nodes-langchain.vectorStorePinecone\",\"position\":[688,-384],\"parameters\":{\"mode\":\"insert\",\"options\":{\"clearNamespace\":\"={{ new Date().getDay() === 6 }}\",\"pineconeNamespace\":\"=google_play_store_reviews_{{ $('Split Out').item.json.apps }}\"},\"pineconeIndex\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"n8n-store-reviews\",\"cachedResultName\":\"n8n-store-reviews\"}},\"typeVersion\":1.3},{\"id\":\"a7611074-702b-496a-bef4-be4eeffda2b9\",\"name\":\"Embeddings OpenAI\",\"type\":\"@n8n/n8n-nodes-langchain.embeddingsOpenAi\",\"position\":[672,-160],\"parameters\":{\"options\":{}},\"typeVersion\":1.2},{\"id\":\"d6f865d0-fba7-456e-9bed-b531b11250c5\",\"name\":\"Default Data Loader\",\"type\":\"@n8n/n8n-nodes-langchain.documentDefaultDataLoader\",\"position\":[864,-160],\"parameters\":{\"options\":{\"metadata\":{\"metadataValues\":[{\"name\":\"star_rating\",\"value\":\"={{ $json.reviews.comments[0].userComment.starRating }}\"},{\"name\":\"date\",\"value\":\"={{$json.reviews.comments[0].userComment.lastModified.seconds.toDateTime('s')}}\\n\"},{\"name\":\"app_version\",\"value\":\"={{ $json.reviews.comments[0].userComment.appVersionName }}\"},{\"name\":\"language\",\"value\":\"={{ $json.reviews.comments[0].userComment.reviewerLanguage }}\"},{\"name\":\"review_id\",\"value\":\"={{ $json.reviews.reviewId }}\"}]}},\"jsonData\":\"=comment: {{ $json.reviews.comments[0].userComment.text }} | date: {{ $json.reviews.comments[0].userComment.lastModified.seconds.toDateTime('s') }} | star rating: {{ $json.reviews.comments[0].userComment.starRating }} | app version: {{ $json.reviews.comments[0].userComment.appVersionName }} | language: {{ $json.reviews.comments[0].userComment.reviewerLanguage }}\",\"jsonMode\":\"expressionData\"},\"typeVersion\":1.1},{\"id\":\"fd7a2f0c-69f4-446e-978c-1b67d0041f87\",\"name\":\"Set app details\",\"type\":\"n8n-nodes-base.set\",\"position\":[-544,96],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"ed79836f-8032-4daa-afc1-d0170157c8a0\",\"name\":\"=apps\",\"type\":\"array\",\"value\":\"=[\\n { \\n \\\"app\\\": \\\"com.bundle.id1\\\",\\n \\\"app_name\\\": \\\"App1\\\"\\n },\\n {\\n \\\"app\\\": \\\"com.bundle.id2\\\",\\n \\\"app_name\\\": \\\"App2\\\"\\n },\\n {\\n \\\"app\\\": \\\"com.bundle.id3\\\",\\n \\\"app_name\\\": \\\"App3\\\"\\n }\\n]\"}]}},\"typeVersion\":3.4},{\"id\":\"3e88c0ea-e6d5-412c-9aae-a702220d626d\",\"name\":\"Split Out1\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-368,96],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"apps\"},\"typeVersion\":1},{\"id\":\"4eac3a49-5126-47b6-b748-fb97770dbab8\",\"name\":\"OpenAI Chat Model1\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[-32,320],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4.1-mini\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"044cd2a3-c3d4-41a2-8c46-4291b3ba0ac8\",\"name\":\"Embeddings OpenAI1\",\"type\":\"@n8n/n8n-nodes-langchain.embeddingsOpenAi\",\"position\":[96,448],\"parameters\":{\"options\":{}},\"typeVersion\":1.2},{\"id\":\"ec306b60-8dbb-4ea9-a4c3-fa5ce4807f1d\",\"name\":\"Pinecone Vector Store1\",\"type\":\"@n8n/n8n-nodes-langchain.vectorStorePinecone\",\"position\":[96,304],\"parameters\":{\"mode\":\"retrieve-as-tool\",\"topK\":500,\"options\":{\"pineconeNamespace\":\"=google_play_store_reviews_{{ $('Loop Over Items1').item.json.app }}\"},\"pineconeIndex\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"n8n-store-reviews\",\"cachedResultName\":\"n8n-store-reviews\"},\"toolDescription\":\"This is the vector store for the Google Play reviews data you need to answer queries\"},\"typeVersion\":1.3},{\"id\":\"053e5a35-875e-4e16-a788-ec2c7eea8425\",\"name\":\"Send to Slack channel\",\"type\":\"n8n-nodes-base.slack\",\"position\":[400,80],\"webhookId\":\"91dd6021-c694-4470-9013-53d5f2e213f8\",\"parameters\":{\"text\":\"={{ $json.output }}\",\"select\":\"channel\",\"channelId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"C1111\"},\"otherOptions\":{}},\"typeVersion\":2.3},{\"id\":\"071bb344-81f1-45f6-bd41-b3df56e7ef4f\",\"name\":\"Weekly trigger\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"notes\":\"On Fridays at 11am\",\"position\":[-736,96],\"parameters\":{\"rule\":{\"interval\":[{\"field\":\"weeks\",\"triggerAtDay\":[5],\"triggerAtHour\":11}]}},\"notesInFlow\":true,\"typeVersion\":1.2}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Filter\":{\"main\":[[{\"node\":\"Pinecone Vector Store\",\"type\":\"main\",\"index\":0}]]},\"Split Out\":{\"main\":[[{\"node\":\"Loop Over Items\",\"type\":\"main\",\"index\":0}]]},\"Split Out1\":{\"main\":[[{\"node\":\"Loop Over Items1\",\"type\":\"main\",\"index\":0}]]},\"Split Out4\":{\"main\":[[{\"node\":\"Filter\",\"type\":\"main\",\"index\":0}]]},\"HTTP Request\":{\"main\":[[{\"node\":\"Split Out4\",\"type\":\"main\",\"index\":0}]]},\"Daily Trigger\":{\"main\":[[{\"node\":\"Set the bundle ids\",\"type\":\"main\",\"index\":0}]]},\"Weekly trigger\":{\"main\":[[{\"node\":\"Set app details\",\"type\":\"main\",\"index\":0}]]},\"Loop Over Items\":{\"main\":[[],[{\"node\":\"HTTP Request\",\"type\":\"main\",\"index\":0}]]},\"Set app details\":{\"main\":[[{\"node\":\"Split Out1\",\"type\":\"main\",\"index\":0}]]},\"Loop Over Items1\":{\"main\":[[],[{\"node\":\"AI Agent - Summary creator\",\"type\":\"main\",\"index\":0}]]},\"Embeddings OpenAI\":{\"ai_embedding\":[[{\"node\":\"Pinecone Vector Store\",\"type\":\"ai_embedding\",\"index\":0}]]},\"Embeddings OpenAI1\":{\"ai_embedding\":[[{\"node\":\"Pinecone Vector Store1\",\"type\":\"ai_embedding\",\"index\":0}]]},\"OpenAI Chat Model1\":{\"ai_languageModel\":[[{\"node\":\"AI Agent - Summary creator\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Set the bundle ids\":{\"main\":[[{\"node\":\"Split Out\",\"type\":\"main\",\"index\":0}]]},\"Default Data Loader\":{\"ai_document\":[[{\"node\":\"Pinecone Vector Store\",\"type\":\"ai_document\",\"index\":0}]]},\"Pinecone Vector Store\":{\"main\":[[{\"node\":\"Loop Over Items\",\"type\":\"main\",\"index\":0}]]},\"Send to Slack channel\":{\"main\":[[{\"node\":\"Loop Over Items1\",\"type\":\"main\",\"index\":0}]]},\"Pinecone Vector Store1\":{\"ai_tool\":[[{\"node\":\"AI Agent - Summary creator\",\"type\":\"ai_tool\",\"index\":0}]]},\"AI Agent - Summary creator\":{\"main\":[[{\"node\":\"Send to Slack channel\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 19, "node_types": {"splitOut": 3, "splitInBatches": 2, "agent": 1, "set": 2, "scheduleTrigger": 2, "httpRequest": 1, "filter": 1, "vectorStorePinecone": 2, "embeddingsOpenAi": 2, "documentDefaultDataLoader": 1, "lmChatOpenAi": 1, "slack": 1}, "services": ["ai", "slack", "http"], "complexity": "complex", "has_conditions": false, "has_loops": true, "has_code": false, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Summarize Google Play Store Reviews with GPT-4-mini, Pinecone & Slack Alerts"}, {"role": "assistant", "content": "\n**Analyse du besoin**: This workflow automatically fetches reviews for one or more Google Play Store apps, summarizes the feedback using OpenAI, stores and manages review data with Pinecone, and posts the summary to a Slack...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 19 nodes utilisant ai, slack, http.\nStructure: traitement par lots, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"GE9244KEY5823lcB\",\"meta\":{\"instanceId\":\"fe52080916406a2a9812a7975b2d9b9e9838f3ce0f0b34614c611fb2ca1528d3\"},\"name\":\"Create summary of Google Play Store reviews\",\"tags\":[],\"nodes\":[{\"id\":\"976a0252-5685-4678-83d8-925d06853179\",\"name\":\"Split Out4\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[288,-384],\"parameters\":{\"include\":\"=\",\"options\":{\"destinationFieldName\":\"\"},\"fieldToSplitOut\":\"reviews\"},\"typeVersion\":1},{\"id\":\"9ad91b18-e9c3-4e43-b301-cc833747fbe2\",\"name\":\"Loop Over Items\",\"type\":\"n8n-nodes-base.splitInBatches\",\"onError\":\"continueRegularOutput\",\"position\":[-112,-384],\"parameters\":{\"options\":{\"reset\":false}},\"typeVersion\":3},{\"id\":\"fd00f503-709f-472d-b0c3-8e8d617f8506\",\"name\":\"Loop Over Items1\",\"type\":\"n8n-nodes-base.splitInBatches\",\"onError\":\"continueRegularOutput\",\"position\":[-192,96],\"parameters\":{\"options\":{\"reset\":false}},\"typeVersion\":3},{\"id\":\"c67fa141-8df9-4010-8d46-b038bc540381\",\"name\":\"AI Agent - Summary creator\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"onError\":\"continueErrorOutput\",\"position\":[32,96],\"parameters\":{\"text\":\"=Create a summary of store reviews submitted. Start your message with \\\"Hi! This is your Google Play Store AI agent for *{{$json.app_name}}*\\\". In your output, include the number of reviews you processed to create the summary. The summary should be split into two groups: a summary about positive reviews and a summary about negative reviews. In your summary include also a breakdown of star ratings, ie. how many reviews there were for each star rating. Also include the average star rating.\",\"options\":{\"systemMessage\":\"=Your job is to respond to prompts using the information you gather from the Google Play Store reviews of an app called {{$json.app_name}}. Your main role is to help your users to gain insights from store review without having to read reviews one by one. Store review usually have star ratings with 1 star being the lowest rating and 5 star being the highest rating. They can also have a text description where the user writes a review about their experience with the app. These can be negative reviews or positive reviews. The lower the star rating the more likely that the review is negative.\"},\"promptType\":\"define\"},\"typeVersion\":2},{\"id\":\"83cf0fc5-66cc-4598-b354-6dd0f4f9ef1c\",\"name\":\"Set the bundle ids\",\"type\":\"n8n-nodes-base.set\",\"position\":[-512,-384],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"ed79836f-8032-4daa-afc1-d0170157c8a0\",\"name\":\"=apps\",\"type\":\"array\",\"value\":\"[\\n \\\"com.bundle.id1\\\",\\n \\\"com.bundle.id2\\\",\\n \\\"com.bundle.id3\\\"\\n]\"}]}},\"typeVersion\":3.4},{\"id\":\"0bcfc993-e58e-49d6-aeba-ad7accb2087b\",\"name\":\"Daily Trigger\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"notes\":\"Daily at 10am \",\"position\":[-720,-384],\"parameters\":{\"rule\":{\"interval\":[{\"triggerAtHour\":10}]}},\"notesInFlow\":true,\"typeVersion\":1.2},{\"id\":\"53df7cef-c399-48a5-bd10-82ec4547999a\",\"name\":\"Split Out\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-288,-384],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"apps\"},\"typeVersion\":1},{\"id\":\"68a7de8f-ad17-4b8b-8a5e-fba73b66794f\",\"name\":\"HTTP Request\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[112,-384],\"parameters\":{\"url\":\"=https://androidpublisher.googleapis.com/androidpublisher/v3/applications/{{$json.apps}}/reviews\",\"options\":{\"pagination\":{\"pagination\":{\"parameters\":{\"parameters\":[{\"name\":\"token\",\"value\":\"={{$response.body.tokenPagination.nextPageToken}}\"}]},\"maxRequests\":10,\"requestInterval\":10,\"limitPagesFetched\":true,\"completeExpression\":\"={{$response.body.tokenPagination.nextPageToken == null}}\",\"paginationCompleteWhen\":\"other\"}}},\"authentication\":\"predefinedCredentialType\",\"nodeCredentialType\":\"googleApi\"},\"typeVersion\":4.2,\"alwaysOutputData\":true},{\"id\":\"beb2b08e-f53d-4b36-82a8-ae282ae477ba\",\"name\":\"Filter\",\"type\":\"n8n-nodes-base.filter\",\"notes\":\"Fetch yesterday's reviews\",\"position\":[496,-384],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"e5cc101a-9e06-4f33-8578-63c4acc66042\",\"operator\":{\"type\":\"dateTime\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.reviews.comments[0].userComment.lastModified.seconds.toDateTime('s').toISODate() }}\",\"rightValue\":\"={{$today.minus({days: 1})}}\\n\"}]}},\"notesInFlow\":true,\"typeVersion\":2.2,\"alwaysOutputData\":true},{\"id\":\"3107ffd9-94ea-43ef-9fad-d0c8c75c32b4\",\"name\":\"Pinecone Vector Store\",\"type\":\"@n8n/n8n-nodes-langchain.vectorStorePinecone\",\"position\":[688,-384],\"parameters\":{\"mode\":\"insert\",\"options\":{\"clearNamespace\":\"={{ new Date().getDay() === 6 }}\",\"pineconeNamespace\":\"=google_play_store_reviews_{{ $('Split Out').item.json.apps }}\"},\"pineconeIndex\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"n8n-store-reviews\",\"cachedResultName\":\"n8n-store-reviews\"}},\"typeVersion\":1.3},{\"id\":\"a7611074-702b-496a-bef4-be4eeffda2b9\",\"name\":\"Embeddings OpenAI\",\"type\":\"@n8n/n8n-nodes-langchain.embeddingsOpenAi\",\"position\":[672,-160],\"parameters\":{\"options\":{}},\"typeVersion\":1.2},{\"id\":\"d6f865d0-fba7-456e-9bed-b531b11250c5\",\"name\":\"Default Data Loader\",\"type\":\"@n8n/n8n-nodes-langchain.documentDefaultDataLoader\",\"position\":[864,-160],\"parameters\":{\"options\":{\"metadata\":{\"metadataValues\":[{\"name\":\"star_rating\",\"value\":\"={{ $json.reviews.comments[0].userComment.starRating }}\"},{\"name\":\"date\",\"value\":\"={{$json.reviews.comments[0].userComment.lastModified.seconds.toDateTime('s')}}\\n\"},{\"name\":\"app_version\",\"value\":\"={{ $json.reviews.comments[0].userComment.appVersionName }}\"},{\"name\":\"language\",\"value\":\"={{ $json.reviews.comments[0].userComment.reviewerLanguage }}\"},{\"name\":\"review_id\",\"value\":\"={{ $json.reviews.reviewId }}\"}]}},\"jsonData\":\"=comment: {{ $json.reviews.comments[0].userComment.text }} | date: {{ $json.reviews.comments[0].userComment.lastModified.seconds.toDateTime('s') }} | star rating: {{ $json.reviews.comments[0].userComment.starRating }} | app version: {{ $json.reviews.comments[0].userComment.appVersionName }} | language: {{ $json.reviews.comments[0].userComment.reviewerLanguage }}\",\"jsonMode\":\"expressionData\"},\"typeVersion\":1.1},{\"id\":\"fd7a2f0c-69f4-446e-978c-1b67d0041f87\",\"name\":\"Set app details\",\"type\":\"n8n-nodes-base.set\",\"position\":[-544,96],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"ed79836f-8032-4daa-afc1-d0170157c8a0\",\"name\":\"=apps\",\"type\":\"array\",\"value\":\"=[\\n { \\n \\\"app\\\": \\\"com.bundle.id1\\\",\\n \\\"app_name\\\": \\\"App1\\\"\\n },\\n {\\n \\\"app\\\": \\\"com.bundle.id2\\\",\\n \\\"app_name\\\": \\\"App2\\\"\\n },\\n {\\n \\\"app\\\": \\\"com.bundle.id3\\\",\\n \\\"app_name\\\": \\\"App3\\\"\\n }\\n]\"}]}},\"typeVersion\":3.4},{\"id\":\"3e88c0ea-e6d5-412c-9aae-a702220d626d\",\"name\":\"Split Out1\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-368,96],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"apps\"},\"typeVersion\":1},{\"id\":\"4eac3a49-5126-47b6-b748-fb97770dbab8\",\"name\":\"OpenAI Chat Model1\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[-32,320],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4.1-mini\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"044cd2a3-c3d4-41a2-8c46-4291b3ba0ac8\",\"name\":\"Embeddings OpenAI1\",\"type\":\"@n8n/n8n-nodes-langchain.embeddingsOpenAi\",\"position\":[96,448],\"parameters\":{\"options\":{}},\"typeVersion\":1.2},{\"id\":\"ec306b60-8dbb-4ea9-a4c3-fa5ce4807f1d\",\"name\":\"Pinecone Vector Store1\",\"type\":\"@n8n/n8n-nodes-langchain.vectorStorePinecone\",\"position\":[96,304],\"parameters\":{\"mode\":\"retrieve-as-tool\",\"topK\":500,\"options\":{\"pineconeNamespace\":\"=google_play_store_reviews_{{ $('Loop Over Items1').item.json.app }}\"},\"pineconeIndex\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"n8n-store-reviews\",\"cachedResultName\":\"n8n-store-reviews\"},\"toolDescription\":\"This is the vector store for the Google Play reviews data you need to answer queries\"},\"typeVersion\":1.3},{\"id\":\"053e5a35-875e-4e16-a788-ec2c7eea8425\",\"name\":\"Send to Slack channel\",\"type\":\"n8n-nodes-base.slack\",\"position\":[400,80],\"webhookId\":\"91dd6021-c694-4470-9013-53d5f2e213f8\",\"parameters\":{\"text\":\"={{ $json.output }}\",\"select\":\"channel\",\"channelId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"C1111\"},\"otherOptions\":{}},\"typeVersion\":2.3},{\"id\":\"071bb344-81f1-45f6-bd41-b3df56e7ef4f\",\"name\":\"Weekly trigger\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"notes\":\"On Fridays at 11am\",\"position\":[-736,96],\"parameters\":{\"rule\":{\"interval\":[{\"field\":\"weeks\",\"triggerAtDay\":[5],\"triggerAtHour\":11}]}},\"notesInFlow\":true,\"typeVersion\":1.2}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Filter\":{\"main\":[[{\"node\":\"Pinecone Vector Store\",\"type\":\"main\",\"index\":0}]]},\"Split Out\":{\"main\":[[{\"node\":\"Loop Over Items\",\"type\":\"main\",\"index\":0}]]},\"Split Out1\":{\"main\":[[{\"node\":\"Loop Over Items1\",\"type\":\"main\",\"index\":0}]]},\"Split Out4\":{\"main\":[[{\"node\":\"Filter\",\"type\":\"main\",\"index\":0}]]},\"HTTP Request\":{\"main\":[[{\"node\":\"Split Out4\",\"type\":\"main\",\"index\":0}]]},\"Daily Trigger\":{\"main\":[[{\"node\":\"Set the bundle ids\",\"type\":\"main\",\"index\":0}]]},\"Weekly trigger\":{\"main\":[[{\"node\":\"Set app details\",\"type\":\"main\",\"index\":0}]]},\"Loop Over Items\":{\"main\":[[],[{\"node\":\"HTTP Request\",\"type\":\"main\",\"index\":0}]]},\"Set app details\":{\"main\":[[{\"node\":\"Split Out1\",\"type\":\"main\",\"index\":0}]]},\"Loop Over Items1\":{\"main\":[[],[{\"node\":\"AI Agent - Summary creator\",\"type\":\"main\",\"index\":0}]]},\"Embeddings OpenAI\":{\"ai_embedding\":[[{\"node\":\"Pinecone Vector Store\",\"type\":\"ai_embedding\",\"index\":0}]]},\"Embeddings OpenAI1\":{\"ai_embedding\":[[{\"node\":\"Pinecone Vector Store1\",\"type\":\"ai_embedding\",\"index\":0}]]},\"OpenAI Chat Model1\":{\"ai_languageModel\":[[{\"node\":\"AI Agent - Summary creator\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Set the bundle ids\":{\"main\":[[{\"node\":\"Split Out\",\"type\":\"main\",\"index\":0}]]},\"Default Data Loader\":{\"ai_document\":[[{\"node\":\"Pinecone Vector Store\",\"type\":\"ai_document\",\"index\":0}]]},\"Pinecone Vector Store\":{\"main\":[[{\"node\":\"Loop Over Items\",\"type\":\"main\",\"index\":0}]]},\"Send to Slack channel\":{\"main\":[[{\"node\":\"Loop Over Items1\",\"type\":\"main\",\"index\":0}]]},\"Pinecone Vector Store1\":{\"ai_tool\":[[{\"node\":\"AI Agent - Summary creator\",\"type\":\"ai_tool\",\"index\":0}]]},\"AI Agent - Summary creator\":{\"main\":[[{\"node\":\"Send to Slack channel\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 19, "node_types": {"splitOut": 3, "splitInBatches": 2, "agent": 1, "set": 2, "scheduleTrigger": 2, "httpRequest": 1, "filter": 1, "vectorStorePinecone": 2, "embeddingsOpenAi": 2, "documentDefaultDataLoader": 1, "lmChatOpenAi": 1, "slack": 1}, "services": ["ai", "slack", "http"], "complexity": "complex", "has_conditions": false, "has_loops": true, "has_code": false, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: This template attempts to replicate OpenAI's DeepResearch feature which, at time of writing, is only available to their pro subscribers. An agent that uses reasoning to synthesize large amount of online information and complete multi-step research tasks for you. Source Though the inner workings of DeepResearch have not been made public, it is presumed the feature relies on the ability to deep search the web, scrape web content and invoking reasoning models to generate reports. All of which n8n is really good at! Using this workflow, n8n users can enjoy a variation of the Deep Research experience for themselves and their teams at a fraction of the cost. Better yet, learn and customise this Deep Research template for their businesses and/or organisations. Check out the generated reports here"}, {"role": "assistant", "content": "\n**Analyse du besoin**: This template attempts to replicate OpenAI's DeepResearch feature which, at time of writing, is only available to their pro subscribers.\n\nAn agent that uses reasoning to synthesize large amount of onl...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 64 nodes utilisant ai, google, http.\nStructure: logique conditionnelle, traitement par lots, code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"meta\":{\"instanceId\":\"408f9fb9940c3cb18ffdef0e0150fe342d6e655c3a9fac21f0f644e8bedabcd9\",\"templateCredsSetupCompleted\":true},\"nodes\":[{\"id\":\"a342005e-a88e-419b-b929-56ecbba4a936\",\"name\":\"Structured Output Parser\",\"type\":\"@n8n/n8n-nodes-langchain.outputParserStructured\",\"position\":[1300,1180],\"parameters\":{\"schemaType\":\"manual\",\"inputSchema\":\"{\\n \\\"type\\\": \\\"object\\\",\\n \\\"properties\\\": {\\n \\\"learnings\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"description\\\": \\\"List of learnings, max of 3.\\\",\\n \\\"items\\\": { \\\"type\\\": \\\"string\\\" }\\n },\\n \\\"followUpQuestions\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"List of follow-up questions to research the topic further, max of 3.\\\"\\n }\\n }\\n }\\n}\"},\"typeVersion\":1.2},{\"id\":\"126b8151-6d20-43b8-8028-8163112c4c5b\",\"name\":\"Set Variables\",\"type\":\"n8n-nodes-base.set\",\"position\":[-1360,-460],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"df28b12e-7c20-4ff5-b5b8-dc773aa14d4b\",\"name\":\"request_id\",\"type\":\"string\",\"value\":\"={{ $execution.id }}\"},{\"id\":\"9362c1e7-717d-444a-8ea2-6b5f958c9f3f\",\"name\":\"prompt\",\"type\":\"string\",\"value\":\"={{ $json['What would you like to research?'] }}\"},{\"id\":\"09094be4-7844-4a9e-af82-cc8e39322398\",\"name\":\"depth\",\"type\":\"number\",\"value\":\"={{\\n!isNaN($json['input-depth'][0].toNumber())\\n ? $json['input-depth'][0].toNumber()\\n : 1\\n}}\"},{\"id\":\"3fc30a30-7806-4013-835d-97e27ddd7ae1\",\"name\":\"breadth\",\"type\":\"number\",\"value\":\"={{\\n!isNaN($json['input-breadth'][0].toNumber())\\n ? $json['input-breadth'][0].toNumber()\\n : 1\\n}}\"}]}},\"typeVersion\":3.4},{\"id\":\"1d0fb87b-263d-46c2-b016-a29ba1d407ab\",\"name\":\"OpenAI Chat Model\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[1120,1180],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"o3-mini\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"39b300d9-11ba-44f6-8f43-2fe256fe4856\",\"name\":\"OpenAI Chat Model1\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[-860,1760],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"o3-mini\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"018da029-a796-45c5-947c-791e087fe934\",\"name\":\"OpenAI Chat Model2\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[-1060,-300],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"o3-mini\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"525da936-a9eb-4523-b27a-ff6ae7b0e5ef\",\"name\":\"Structured Output Parser1\",\"type\":\"@n8n/n8n-nodes-langchain.outputParserStructured\",\"position\":[-840,-300],\"parameters\":{\"schemaType\":\"manual\",\"inputSchema\":\"{\\n \\\"type\\\": \\\"object\\\",\\n \\\"properties\\\": {\\n \\\"questions\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"description\\\": \\\"Follow up questions to clarify the research direction, max of 3.\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n }\\n}\"},\"typeVersion\":1.2},{\"id\":\"e6664883-cff4-4e09-881e-6b6f684f9cac\",\"name\":\"On form submission\",\"type\":\"n8n-nodes-base.formTrigger\",\"position\":[-1760,-460],\"webhookId\":\"026629c8-7644-493c-b830-d9c72eea307d\",\"parameters\":{\"options\":{\"path\":\"deep_research\",\"ignoreBots\":true,\"buttonLabel\":\"Next\"},\"formTitle\":\" DeepResearcher\",\"formFields\":{\"values\":[{\"fieldType\":\"html\"}]},\"formDescription\":\"=DeepResearcher is a multi-step, recursive approach using the internet to solve complex research tasks, accomplishing in tens of minutes what a human would take many hours.\\n\\nTo use, provide a short summary of what the research and how \\\"deep\\\" you'd like the workflow to investigate. Note, the higher the numbers the more time and cost will occur for the research.\\n\\nThe workflow is designed to complete independently and when finished, a report will be saved in a designated Notion Database.\"},\"typeVersion\":2.2},{\"id\":\"6b8ebc08-c0b1-4af8-99cc-79d09eea7316\",\"name\":\"Generate SERP Queries\",\"type\":\"@n8n/n8n-nodes-langchain.chainLlm\",\"position\":[-1040,820],\"parameters\":{\"text\":\"=Given the following prompt from the user, generate a list of SERP queries to research the topic.\\nReduce the number of words in each query to its keywords only.\\nReturn a maximum of {{ $('JobType Router').first().json.data.breadth }} queries, but feel free to return less if the original prompt is clear. Make sure each query is unique and not similar to each other: {{ $('JobType Router').first().json.data.query.trim() }}\\n\\n{{\\n$('JobType Router').first().json.data.learnings.length\\n ? `Here are some learnings from previous research, use them to generate more specific queries:\\\\n${$('JobType Router').first().json.data.learnings.map(text => `* ${text}`).join('\\\\n')}`\\n : ''\\n}}\",\"messages\":{\"messageValues\":[{\"type\":\"HumanMessagePromptTemplate\",\"message\":\"=You are an expert researcher. Today is {{ $now.toLocaleString() }}. Follow these instructions when responding:\\n - You may be asked to research subjects that is after your knowledge cutoff, assume the user is right when presented with news.\\n - The user is a highly experienced analyst, no need to simplify it, be as detailed as possible and make sure your response is correct.\\n - Be highly organized.\\n - Suggest solutions that I didn't think about.\\n - Be proactive and anticipate my needs.\\n - Treat me as an expert in all subject matter.\\n - Mistakes erode my trust, so be accurate and thorough.\\n - Provide detailed explanations, I'm comfortable with lots of detail.\\n - Value good arguments over authorities, the source is irrelevant.\\n - Consider new technologies and contrarian ideas, not just the conventional wisdom.\\n - You may use high levels of speculation or prediction, just flag it for me.\"}]},\"promptType\":\"define\",\"hasOutputParser\":true},\"typeVersion\":1.5},{\"id\":\"34e1fa5d-bc0c-4b9e-84a7-35db2b08c772\",\"name\":\"Structured Output Parser2\",\"type\":\"@n8n/n8n-nodes-langchain.outputParserStructured\",\"position\":[-860,980],\"parameters\":{\"schemaType\":\"manual\",\"inputSchema\":\"{\\n \\\"type\\\": \\\"object\\\",\\n \\\"properties\\\": {\\n \\\"queries\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"properties\\\": {\\n \\\"query\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"The SERP query\\\"\\n },\\n \\\"researchGoal\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"First talk about the goal of the research that this query is meant to accomplish, then go deeper into how to advance the research once the results are found, mention additional research directions. Be as specific as possible, especially for additional research directions.\\\"\\n }\\n }\\n }\\n }\\n }\\n}\"},\"typeVersion\":1.2},{\"id\":\"be6dd6a2-aacf-4682-8f13-8ae24c4249a3\",\"name\":\"OpenAI Chat Model3\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[-1040,980],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"o3-mini\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"d5ce6e21-cd07-44fa-b6d0-90bf7531ee01\",\"name\":\"Set Initial Query\",\"type\":\"n8n-nodes-base.set\",\"position\":[-580,180],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"acb41e93-70c6-41a3-be0f-e5a74ec3ec88\",\"name\":\"query\",\"type\":\"string\",\"value\":\"={{ $('JobType Router').first().json.data.query }}\"},{\"id\":\"7fc54063-b610-42bc-a250-b1e8847c4d1e\",\"name\":\"learnings\",\"type\":\"array\",\"value\":\"={{ $('JobType Router').first().json.data.learnings }}\"},{\"id\":\"e8f1c158-56fb-41c8-8d86-96add16289bb\",\"name\":\"breadth\",\"type\":\"number\",\"value\":\"={{ $('JobType Router').first().json.data.breadth }}\"}]}},\"typeVersion\":3.4},{\"id\":\"9de6e4a1-a2b5-4a6f-948e-a0585edcae48\",\"name\":\"SERP to Items\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-700,820],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"output.queries\"},\"typeVersion\":1},{\"id\":\"2c9c4cdf-942b-494c-83fb-ed5ec37385ee\",\"name\":\"Item Ref\",\"type\":\"n8n-nodes-base.noOp\",\"position\":[-220,1020],\"parameters\":{},\"typeVersion\":1},{\"id\":\"703c57af-de19-4f00-b580-711a272fa5ca\",\"name\":\"Research Goal + Learnings\",\"type\":\"n8n-nodes-base.set\",\"position\":[1460,1160],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"9acec2cc-64c8-4e62-bed4-c3d9ffab1379\",\"name\":\"researchGoal\",\"type\":\"string\",\"value\":\"={{ $('Item Ref').first().json.researchGoal }}\"},{\"id\":\"1b2d2dad-429b-4fc9-96c5-498f572a85c3\",\"name\":\"learnings\",\"type\":\"array\",\"value\":\"={{ $json.output.learnings }}\"},{\"id\":\"7025f533-02ab-4031-9413-43390fb61f05\",\"name\":\"followUpQuestions\",\"type\":\"string\",\"value\":\"={{ $json.output.followUpQuestions }}\"},{\"id\":\"c9e34ea4-5606-46d6-8d66-cb42d772a8b4\",\"name\":\"urls\",\"type\":\"array\",\"value\":\"={{\\n$('Get Markdown + URL')\\n .all()\\n .map(item => item.json.url)\\n}}\"}]}},\"typeVersion\":3.4},{\"id\":\"16ed2835-3af4-45e3-b5a7-e4342d571aa0\",\"name\":\"Accumulate Results\",\"type\":\"n8n-nodes-base.set\",\"position\":[-200,180],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"db509e90-9a86-431f-8149-4094d22666cc\",\"name\":\"should_stop\",\"type\":\"boolean\",\"value\":\"={{\\n$runIndex >= ($('JobType Router').first().json.data.depth)\\n}}\"},{\"id\":\"90986e2b-8aca-4a22-a9db-ed8809d6284d\",\"name\":\"all_learnings\",\"type\":\"array\",\"value\":\"={{\\nArray($runIndex+1)\\n .fill(0)\\n .flatMap((_,idx) => {\\n try {\\n return $('Generate Learnings')\\n .all(0,idx)\\n .flatMap(item => item.json.data.flatMap(d => d.learnings))\\n } catch (e) {\\n return []\\n }\\n })\\n}}\"},{\"id\":\"3eade958-e8ab-4975-aac4-f4a4a983c163\",\"name\":\"all_urls\",\"type\":\"array\",\"value\":\"={{\\nArray($runIndex+1)\\n .fill(0)\\n .flatMap((_,idx) => {\\n try {\\n return $('Generate Learnings')\\n .all(0,idx)\\n .flatMap(item => item.json.data.flatMap(d => d.urls))\\n } catch (e) {\\n return []\\n }\\n })\\n}}\"}]}},\"executeOnce\":true,\"typeVersion\":3.4},{\"id\":\"0011773e-85c6-4fe1-8554-c23ce50706d0\",\"name\":\"DeepResearch Results\",\"type\":\"n8n-nodes-base.set\",\"position\":[160,360],\"parameters\":{\"mode\":\"raw\",\"options\":{},\"jsonOutput\":\"={{ $('Generate Learnings').item.json }}\"},\"typeVersion\":3.4},{\"id\":\"c0b646d0-1246-4864-8f79-8b7a66e4e083\",\"name\":\"Results to Items\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[320,360],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"data\"},\"typeVersion\":1},{\"id\":\"3c52ec3e-c952-4b5f-ab12-f1b5d02aba74\",\"name\":\"Set Next Queries\",\"type\":\"n8n-nodes-base.set\",\"position\":[480,360],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"d88bfe95-9e73-4d25-b45c-9f164b940b0e\",\"name\":\"query\",\"type\":\"string\",\"value\":\"=Previous research goal: {{ $json.researchGoal }}\\nFollow-up research directions: {{ $json.followUpQuestions.map(q => `\\\\n${q}`).join('') }}\"},{\"id\":\"4aa20690-d998-458a-b1e4-0d72e6a68e6b\",\"name\":\"learnings\",\"type\":\"array\",\"value\":\"={{ $('Accumulate Results').item.json.all_learnings }}\"},{\"id\":\"89acafae-b04a-4d5d-b08b-656e715654e4\",\"name\":\"breadth\",\"type\":\"number\",\"value\":\"={{ $('JobType Router').first().json.data.breadth }}\"}]}},\"typeVersion\":3.4},{\"id\":\"bc59dddc-2b03-481f-91c6-ea8aa378eef0\",\"name\":\"For Each Query...\",\"type\":\"n8n-nodes-base.splitInBatches\",\"position\":[-420,860],\"parameters\":{\"options\":{}},\"typeVersion\":3},{\"id\":\"903c31c4-5fdc-4cb6-8baa-402555997266\",\"name\":\"Feedback to Items\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-720,-460],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"output.questions\"},\"typeVersion\":1},{\"id\":\"59ff671d-5d4f-42ff-b94f-ed30a8531e55\",\"name\":\"Ask Clarity Questions\",\"type\":\"n8n-nodes-base.form\",\"position\":[-360,-380],\"webhookId\":\"d3375ba6-0008-4fcb-96bc-110374de2603\",\"parameters\":{\"options\":{\"formTitle\":\"DeepResearcher\",\"buttonLabel\":\"Answer\",\"formDescription\":\"=\\n

          \\nAnswer the following clarification questions to assist the DeepResearcher better under the research topic.\\n

          \\n
          \\n

          \\nTotal {{ $('Feedback to Items').all().length }} questions.\\n

          \"},\"formFields\":{\"values\":[{\"fieldType\":\"textarea\",\"fieldLabel\":\"={{ $json[\\\"output.questions\\\"] }}\",\"placeholder\":\"=\",\"requiredField\":true}]}},\"typeVersion\":1},{\"id\":\"1c2cf79b-f1a1-4ecc-bb45-3d4460c947bd\",\"name\":\"For Each Question...\",\"type\":\"n8n-nodes-base.splitInBatches\",\"position\":[-540,-460],\"parameters\":{\"options\":{}},\"typeVersion\":3},{\"id\":\"0c9ffa99-2687-4df5-8581-0c5b0b2657a9\",\"name\":\"DeepResearch Subworkflow\",\"type\":\"n8n-nodes-base.executeWorkflowTrigger\",\"position\":[-1880,820],\"parameters\":{\"workflowInputs\":{\"values\":[{\"name\":\"requestId\",\"type\":\"any\"},{\"name\":\"jobType\"},{\"name\":\"data\",\"type\":\"object\"}]}},\"typeVersion\":1.1},{\"id\":\"e87c0f19-6002-4aa2-931a-ca7546146a84\",\"name\":\"Clarifying Questions\",\"type\":\"@n8n/n8n-nodes-langchain.chainLlm\",\"position\":[-1040,-460],\"parameters\":{\"text\":\"=Given the following query from the user, ask some follow up questions to clarify the research direction. Return a maximum of 3 questions, but feel free to return less if the original query is clear: {{ $json.prompt }}`\",\"messages\":{\"messageValues\":[{\"type\":\"HumanMessagePromptTemplate\",\"message\":\"=You are an expert researcher. Today is {{ $now.toLocaleString() }}. Follow these instructions when responding:\\n - You may be asked to research subjects that is after your knowledge cutoff, assume the user is right when presented with news.\\n - The user is a highly experienced analyst, no need to simplify it, be as detailed as possible and make sure your response is correct.\\n - Be highly organized.\\n - Suggest solutions that I didn't think about.\\n - Be proactive and anticipate my needs.\\n - Treat me as an expert in all subject matter.\\n - Mistakes erode my trust, so be accurate and thorough.\\n - Provide detailed explanations, I'm comfortable with lots of detail.\\n - Value good arguments over authorities, the source is irrelevant.\\n - Consider new technologies and contrarian ideas, not just the conventional wisdom.\\n - You may use high levels of speculation or prediction, just flag it for me.\"}]},\"promptType\":\"define\",\"hasOutputParser\":true},\"typeVersion\":1.5},{\"id\":\"0a8c3a01-d4d4-4075-9521-035b7df9aa5a\",\"name\":\"End Form\",\"type\":\"n8n-nodes-base.form\",\"position\":[960,-420],\"webhookId\":\"88f2534b-2b82-4b40-a4bc-97d96384e8fd\",\"parameters\":{\"options\":{},\"operation\":\"completion\",\"completionTitle\":\"=Thank you for using DeepResearcher.\",\"completionMessage\":\"=You may now close this window.\"},\"typeVersion\":1},{\"id\":\"44a3603f-a5a1-4031-8c5f-c748b1007b47\",\"name\":\"Initiate DeepResearch\",\"type\":\"n8n-nodes-base.executeWorkflow\",\"position\":[600,-420],\"parameters\":{\"mode\":\"each\",\"options\":{\"waitForSubWorkflow\":false},\"workflowId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"={{ $workflow.id }}\"},\"workflowInputs\":{\"value\":{\"data\":\"={{\\n{\\n \\\"query\\\": $('Get Initial Query').first().json.query,\\n \\\"learnings\\\": [],\\n \\\"depth\\\": $('Set Variables').first().json.depth,\\n \\\"breadth\\\": $('Set Variables').first().json.breadth,\\n}\\n}}\",\"jobType\":\"deepresearch_initiate\",\"requestId\":\"={{ $('Set Variables').first().json.request_id }}\"},\"schema\":[{\"id\":\"requestId\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"requestId\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"jobType\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"jobType\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"data\",\"type\":\"object\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"data\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[],\"attemptToConvertTypes\":false,\"convertFieldsToString\":true}},\"typeVersion\":1.2},{\"id\":\"b243eb76-9ed9-4327-968f-c21844bc9df4\",\"name\":\"Execution Data\",\"type\":\"n8n-nodes-base.executionData\",\"position\":[-1700,820],\"parameters\":{\"dataToSave\":{\"values\":[{\"key\":\"requestId\",\"value\":\"={{ $json.requestId }}\"},{\"key\":\"=jobType\",\"value\":\"={{ $json.jobType }}\"}]}},\"typeVersion\":1},{\"id\":\"57ca4b22-9349-4b34-8f6b-c502905b5172\",\"name\":\"JobType Router\",\"type\":\"n8n-nodes-base.switch\",\"position\":[-1520,820],\"parameters\":{\"rules\":{\"values\":[{\"outputKey\":\"initiate\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"operator\":{\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.jobType }}\",\"rightValue\":\"deepresearch_initiate\"}]},\"renameOutput\":true},{\"outputKey\":\"learnings\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"ecbfa54d-fc97-48c5-8d3d-f0538b8d727b\",\"operator\":{\"name\":\"filter.operator.equals\",\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.jobType }}\",\"rightValue\":\"deepresearch_learnings\"}]},\"renameOutput\":true},{\"outputKey\":\"report\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"392f9a98-ec22-4e57-9c8e-0e1ed6b7dafa\",\"operator\":{\"name\":\"filter.operator.equals\",\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.jobType }}\",\"rightValue\":\"deepresearch_report\"}]},\"renameOutput\":true}]},\"options\":{}},\"typeVersion\":3.2},{\"id\":\"1f880fbd-71ba-4e5b-8d99-9654ae0c949f\",\"name\":\"OpenAI Chat Model4\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[-20,-280],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"o3-mini\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"ea65589b-106f-4ff1-a6f2-763393c2cb07\",\"name\":\"Get Initial Query\",\"type\":\"n8n-nodes-base.set\",\"position\":[-360,-540],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"14b77741-c3c3-4bd2-be6e-37bd09fcea2b\",\"name\":\"query\",\"type\":\"string\",\"value\":\"=Initial query: {{ $('Set Variables').first().json.prompt }}\\nFollow-up Questions and Answers:\\n{{\\n$input.all()\\n .map(item => {\\n const q = Object.keys(item.json)[0];\\n const a = item.json[q];\\n return `question: ${q}\\\\nanswer: ${a}`;\\n })\\n .join('\\\\n')\\n}}\"}]}},\"executeOnce\":true,\"typeVersion\":3.4},{\"id\":\"09a363f2-6300-430d-8c7e-3e1611ab8e68\",\"name\":\"Structured Output Parser4\",\"type\":\"@n8n/n8n-nodes-langchain.outputParserStructured\",\"position\":[160,-280],\"parameters\":{\"schemaType\":\"manual\",\"inputSchema\":\"{\\n \\\"type\\\": \\\"object\\\",\\n \\\"properties\\\": {\\n \\\"title\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\":\\\" A short title summarising the research topic\\\"\\n },\\n \\\"description\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"A short description to summarise the research topic\\\"\\n }\\n }\\n}\"},\"typeVersion\":1.2},{\"id\":\"9910804e-8376-4e2e-a011-7d32ca951edf\",\"name\":\"Create Row\",\"type\":\"n8n-nodes-base.notion\",\"position\":[300,-420],\"parameters\":{\"title\":\"={{ $json.output.title }}\",\"options\":{},\"resource\":\"databasePage\",\"databaseId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"19486dd6-0c0c-80da-9cb7-eb1468ea9afd\",\"cachedResultUrl\":\"https://www.notion.so/19486dd60c0c80da9cb7eb1468ea9afd\",\"cachedResultName\":\"n8n DeepResearch\"},\"propertiesUi\":{\"propertyValues\":[{\"key\":\"Description|rich_text\",\"textContent\":\"={{ $json.output.description }}\"},{\"key\":\"Status|status\",\"statusValue\":\"Not started\"},{\"key\":\"Request ID|rich_text\",\"textContent\":\"={{ $('Set Variables').first().json.request_id }}\"},{\"key\":\"Name|title\",\"title\":\"={{ $json.output.title }}\"}]}},\"typeVersion\":2.2},{\"id\":\"9f06d9ae-220d-4f5b-bcbf-761b88ba255c\",\"name\":\"Report Page Generator\",\"type\":\"@n8n/n8n-nodes-langchain.chainLlm\",\"position\":[-20,-420],\"parameters\":{\"text\":\"=Create a suitable title for the research report which will be created from the user's query.\\n{{ $json.query }}\",\"promptType\":\"define\",\"hasOutputParser\":true},\"typeVersion\":1.5},{\"id\":\"9fd00d55-1c76-425b-8386-7bc5b2bb47ac\",\"name\":\"Is Depth Reached?\",\"type\":\"n8n-nodes-base.if\",\"position\":[-40,180],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"75d18d88-6ba6-43df-bef7-3e8ad99ad8bd\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json.should_stop }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2},{\"id\":\"f658537b-4f4c-4427-a66f-56cfd950bffc\",\"name\":\"Get Research Results\",\"type\":\"n8n-nodes-base.set\",\"position\":[160,180],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"90b3da00-dcd5-4289-bd45-953146a3b0ba\",\"name\":\"all_learnings\",\"type\":\"array\",\"value\":\"={{ $json.all_learnings }}\"},{\"id\":\"623dbb3d-83a1-44a9-8ad3-48d92bc42811\",\"name\":\"all_urls\",\"type\":\"array\",\"value\":\"={{ $json.all_urls }}\"}]}},\"typeVersion\":3.4},{\"id\":\"6059f3ba-e4a0-4528-894c-6080eedb91c3\",\"name\":\"Get Existing Row\",\"type\":\"n8n-nodes-base.notion\",\"position\":[-1040,180],\"parameters\":{\"limit\":1,\"filters\":{\"conditions\":[{\"key\":\"Request ID|rich_text\",\"condition\":\"equals\",\"richTextValue\":\"={{ $json.requestId.toString() }}\"}]},\"options\":{},\"resource\":\"databasePage\",\"matchType\":\"allFilters\",\"operation\":\"getAll\",\"databaseId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"19486dd6-0c0c-80da-9cb7-eb1468ea9afd\",\"cachedResultUrl\":\"https://www.notion.so/19486dd60c0c80da9cb7eb1468ea9afd\",\"cachedResultName\":\"n8n DeepResearch\"},\"filterType\":\"manual\"},\"typeVersion\":2.2},{\"id\":\"100625bb-bf9a-4993-b387-1c61e486ba6d\",\"name\":\"Set In-Progress\",\"type\":\"n8n-nodes-base.notion\",\"position\":[-840,180],\"parameters\":{\"pageId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"={{ $json.id }}\"},\"options\":{},\"resource\":\"databasePage\",\"operation\":\"update\",\"propertiesUi\":{\"propertyValues\":[{\"key\":\"Status|status\",\"statusValue\":\"In progress\"}]}},\"typeVersion\":2.2},{\"id\":\"864332ea-dd25-4347-a49d-68ed6495c1a9\",\"name\":\"Set Done\",\"type\":\"n8n-nodes-base.notion\",\"position\":[1680,1600],\"parameters\":{\"pageId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"={{ $('Get Existing Row1').first().json.id }}\"},\"options\":{},\"resource\":\"databasePage\",\"operation\":\"update\",\"propertiesUi\":{\"propertyValues\":[{\"key\":\"Status|status\",\"statusValue\":\"Done\"},{\"key\":\"Last Updated|date\",\"date\":\"={{ $now.toISO() }}\"}]}},\"executeOnce\":true,\"typeVersion\":2.2},{\"id\":\"6771568a-e6bd-4c89-a535-089fd1c18fc3\",\"name\":\"Tags to Items\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-60,1600],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"tag\"},\"typeVersion\":1},{\"id\":\"47fce580-7b5b-4bc6-ba52-a8e7af6595b5\",\"name\":\"Convert to HTML\",\"type\":\"n8n-nodes-base.markdown\",\"position\":[-380,1600],\"parameters\":{\"mode\":\"markdownToHtml\",\"options\":{\"tables\":true},\"markdown\":\"={{ $json.text }}\"},\"typeVersion\":1},{\"id\":\"e2fb5a31-9ca5-487b-a7f8-f020759ec53a\",\"name\":\"HTML to Array\",\"type\":\"n8n-nodes-base.set\",\"position\":[-220,1600],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"851b8a3f-c2d3-41ad-bf60-4e0e667f6c58\",\"name\":\"tag\",\"type\":\"array\",\"value\":\"={{ $json.data.match(/||<[^>]+>[^<]*<\\\\/[^>]+>/g) }}\"}]}},\"typeVersion\":3.4},{\"id\":\"5275f9dd-5420-4c59-a330-5f2775b47e51\",\"name\":\"Notion Block Generator\",\"type\":\"@n8n/n8n-nodes-langchain.chainLlm\",\"position\":[100,1600],\"parameters\":{\"text\":\"={{ $json.tag.trim() }}\",\"messages\":{\"messageValues\":[{\"message\":\"=Convert the following html into its equivalent Notion Block as per Notion's API schema.\\n* Ensure the content is always included and remains the same.\\n* Return only a json response.\\n* Generate child-level blocks. Should not define \\\"parent\\\" or \\\"children\\\" property.\\n* Strongly prefer headings, paragraphs, tables and lists type blocks.\\n* available headings are heading_1, heading_2 and heading_3 - h4,h5,h6 should use heading_3 type instead. ensure headings use the rich text definition.\\n* ensure lists blocks include all list items.\\n\\n## Examples\\n\\n1. headings\\n```\\n

          References

          \\n```\\nwould convert to \\n```\\n{\\\"object\\\": \\\"block\\\", \\\"type\\\": \\\"heading_3\\\", \\\"heading_3\\\": { \\\"rich_text\\\": [{\\\"type\\\": \\\"text\\\",\\\"text\\\": {\\\"content\\\": \\\"References\\\"}}]}}\\n```\\n\\n2. lists\\n```\\n
          • hello
          • world
          \\n```\\nwould convert to\\n```\\n[\\n{\\n \\\"object\\\": \\\"block\\\",\\n \\\"type\\\": \\\"bulleted_list_item\\\",\\n \\\"bulleted_list_item\\\": {\\\"rich_text\\\": [{\\\"type\\\": \\\"text\\\",\\\"text\\\": {\\\"content\\\": \\\"hello\\\"}}]}\\n},\\n{\\n \\\"object\\\": \\\"block\\\",\\n \\\"type\\\": \\\"bulleted_list_item\\\",\\n \\\"bulleted_list_item\\\": {\\\"rich_text\\\": [{\\\"type\\\": \\\"text\\\",\\\"text\\\": {\\\"content\\\": \\\"world\\\"}}]}\\n}\\n]\\n```\\n\\n3. tables\\n```\\n\\n \\n \\n \\n \\n \\n \\n \\n \\n
          TechnologyPotential Impact
          5G ConnectivityEnables faster data speeds and advanced apps
          \\n```\\nwould convert to\\n```\\n{\\n \\\"object\\\": \\\"block\\\",\\n \\\"type\\\": \\\"table\\\",\\n \\\"table\\\": {\\n \\\"table_width\\\": 2,\\n \\\"has_column_header\\\": true,\\n \\\"has_row_header\\\": false,\\n \\\"children\\\": [\\n {\\n \\\"object\\\": \\\"block\\\",\\n \\\"type\\\": \\\"table_row\\\",\\n \\\"table_row\\\": {\\n \\\"cells\\\": [\\n [\\n {\\n \\\"type\\\": \\\"text\\\",\\n \\\"text\\\": {\\n \\\"content\\\": \\\"Technology\\\",\\n \\\"link\\\": null\\n }\\n },\\n {\\n \\\"type\\\": \\\"text\\\",\\n \\\"text\\\": {\\n \\\"content\\\": \\\"Potential Impact\\\",\\n \\\"link\\\": null\\n }\\n }\\n ],\\n [\\n {\\n \\\"type\\\": \\\"text\\\",\\n \\\"text\\\": {\\n \\\"content\\\": \\\"5G Connectivity\\\",\\n \\\"link\\\": null\\n }\\n },\\n {\\n \\\"type\\\": \\\"text\\\",\\n \\\"text\\\": {\\n \\\"content\\\": \\\"Enables faster data speeds and advanced apps\\\",\\n \\\"link\\\": null\\n }\\n }\\n ]\\n ]\\n }\\n }\\n ]\\n }\\n}\\n```\\n4. anchor links\\nSince Notion doesn't support anchor links, just convert them to rich text blocks instead.\\n```\\nModule 0: Pre-Course Setup and Learning Principles\\n```\\nconverts to\\n```\\n{\\n \\\"object\\\": \\\"block\\\",\\n \\\"type\\\": \\\"paragraph\\\",\\n \\\"paragraph\\\": {\\n \\\"rich_text\\\": [\\n {\\n \\\"type\\\": \\\"text\\\",\\n \\\"text\\\": {\\n \\\"content\\\": \\\"Module 0: Pre-Course Setup and Learning Principles\\\"\\n }\\n }\\n ]\\n }\\n}\\n```\\n5. Invalid html parts\\nWhen the html is not syntax valid eg. orphaned closing tags, then just skip the conversion and use an empty rich text block.\\n```\\n
        • \\\\n\\n```\\ncan be substituted with\\n```\\n{\\n \\\"object\\\": \\\"block\\\",\\n \\\"type\\\": \\\"paragraph\\\",\\n \\\"paragraph\\\": {\\n \\\"rich_text\\\": [\\n {\\n \\\"type\\\": \\\"text\\\",\\n \\\"text\\\": {\\n \\\"content\\\": \\\" \\\"\\n }\\n }\\n ]\\n }\\n}\\n```\"}]},\"promptType\":\"define\"},\"typeVersion\":1.5},{\"id\":\"30e73ecf-5994-4229-b7f6-01e043e0e65b\",\"name\":\"Google Gemini Chat Model\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatGoogleGemini\",\"position\":[80,1760],\"parameters\":{\"options\":{},\"modelName\":\"models/gemini-2.0-flash\"},\"typeVersion\":1},{\"id\":\"85ce9f7e-0369-41bd-8c31-c4217f400472\",\"name\":\"Parse JSON blocks\",\"type\":\"n8n-nodes-base.set\",\"onError\":\"continueRegularOutput\",\"position\":[420,1600],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"73fcb8a0-2672-4bd5-86de-8075e1e02baf\",\"name\":\"=block\",\"type\":\"array\",\"value\":\"={{\\n(function(){\\n const block = $json.text\\n .replace('```json', '')\\n .replace('```', '')\\n .trim()\\n .parseJson();\\n if (Array.isArray(block)) return block;\\n if (block.type.startsWith('heading_')) {\\n const prev = Number(block.type.split('_')[1]);\\n const next = Math.max(1, prev - 1);\\n if (next !== prev) {\\n block.type = `heading_${next}`;\\n block[`heading_${next}`] = Object.assign({}, block[`heading_${prev}`]);\\n block[`heading_${prev}`] = undefined;\\n }\\n }\\n return [block];\\n})()\\n}}\"}]}},\"executeOnce\":false,\"typeVersion\":3.4},{\"id\":\"349f4323-d65f-4845-accc-6f51340a84c4\",\"name\":\"Upload to Notion Page\",\"type\":\"n8n-nodes-base.httpRequest\",\"onError\":\"continueRegularOutput\",\"maxTries\":2,\"position\":[1680,1760],\"parameters\":{\"url\":\"=https://api.notion.com/v1/blocks/{{ $('Get Existing Row1').first().json.id }}/children\",\"method\":\"PATCH\",\"options\":{\"timeout\":\"={{ 1000 * 60 }}\"},\"jsonBody\":\"={{\\n{\\n \\\"children\\\": $json.block\\n}\\n}}\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"authentication\":\"predefinedCredentialType\",\"headerParameters\":{\"parameters\":[{\"name\":\"Notion-Version\",\"value\":\"2022-06-28\"}]},\"nodeCredentialType\":\"notionApi\"},\"retryOnFail\":true,\"typeVersion\":4.2,\"waitBetweenTries\":3000},{\"id\":\"e2c29aa2-ff79-4bdd-b3c7-cf5e5866db8a\",\"name\":\"Get Existing Row1\",\"type\":\"n8n-nodes-base.notion\",\"position\":[-1020,1600],\"parameters\":{\"limit\":1,\"filters\":{\"conditions\":[{\"key\":\"Request ID|rich_text\",\"condition\":\"equals\",\"richTextValue\":\"={{ $json.requestId.toString() }}\"}]},\"options\":{},\"resource\":\"databasePage\",\"matchType\":\"allFilters\",\"operation\":\"getAll\",\"databaseId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"19486dd6-0c0c-80da-9cb7-eb1468ea9afd\",\"cachedResultUrl\":\"https://www.notion.so/19486dd60c0c80da9cb7eb1468ea9afd\",\"cachedResultName\":\"n8n DeepResearch\"},\"filterType\":\"manual\"},\"typeVersion\":2.2},{\"id\":\"533ede84-1138-426c-93df-c2b862e2d063\",\"name\":\"DeepResearch Report\",\"type\":\"@n8n/n8n-nodes-langchain.chainLlm\",\"position\":[-860,1600],\"parameters\":{\"text\":\"=You are are an expert and insightful researcher.\\n* Given the following prompt from the user, write a final report on the topic using the learnings from research.\\n* Make it as as detailed as possible, aim for 3 or more pages, include ALL the learnings from research.\\n* Format the report in markdown. Use headings, lists and tables only and where appropriate.\\n\\n{{ $('JobType Router').first().json.data.query }}\\n\\nHere are all the learnings from previous research:\\n\\n\\n{{\\n$('JobType Router').first().json.data\\n .all_learnings\\n .map(item => `${item}`) \\n .join('\\\\n')\\n}}\\n\",\"promptType\":\"define\"},\"typeVersion\":1.5},{\"id\":\"efe47725-7fd5-45e7-97c4-d6c133745e5f\",\"name\":\"DeepResearch Learnings\",\"type\":\"@n8n/n8n-nodes-langchain.chainLlm\",\"position\":[1120,1020],\"parameters\":{\"text\":\"=Given the following contents from a SERP search for the query {{ $('Item Ref').first().json.query }}, generate a list of learnings from the contents. Return a maximum of 3 learnings, but feel free to return less if the contents are clear. Make sure each learning is unique and not similar to each other. The learnings should be concise and to the point, as detailed and infromation dense as possible. Make sure to include any entities like people, places, companies, products, things, etc in the learnings, as well as any exact metrics, numbers, or dates. The learnings will be used to research the topic further.\\n\\n\\n{{\\n$input\\n .all()\\n .map(item =>`\\\\n${item.json.markdown.substr(0, 25_000)}\\\\n`)\\n .join('\\\\n')\\n}}\\n\",\"messages\":{\"messageValues\":[{\"type\":\"HumanMessagePromptTemplate\",\"message\":\"=You are an expert researcher. Today is {{ $now.toLocaleString() }}. Follow these instructions when responding:\\n - You may be asked to research subjects that is after your knowledge cutoff, assume the user is right when presented with news.\\n - The user is a highly experienced analyst, no need to simplify it, be as detailed as possible and make sure your response is correct.\\n - Be highly organized.\\n - Suggest solutions that I didn't think about.\\n - Be proactive and anticipate my needs.\\n - Treat me as an expert in all subject matter.\\n - Mistakes erode my trust, so be accurate and thorough.\\n - Provide detailed explanations, I'm comfortable with lots of detail.\\n - Value good arguments over authorities, the source is irrelevant.\\n - Consider new technologies and contrarian ideas, not just the conventional wisdom.\\n - You may use high levels of speculation or prediction, just flag it for me.\"}]},\"promptType\":\"define\",\"hasOutputParser\":true},\"executeOnce\":true,\"typeVersion\":1.5},{\"id\":\"d3b42d13-e8ca-4085-ace9-1d9fb53f5e71\",\"name\":\"Generate Report\",\"type\":\"n8n-nodes-base.executeWorkflow\",\"position\":[480,180],\"parameters\":{\"options\":{\"waitForSubWorkflow\":false},\"workflowId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"={{ $workflow.id }}\"},\"workflowInputs\":{\"value\":{\"data\":\"={{\\n{\\n ...Object.assign({}, $json),\\n query: $('JobType Router').first().json.data.query\\n}\\n}}\",\"jobType\":\"deepresearch_report\",\"requestId\":\"={{ $('JobType Router').first().json.requestId }}\"},\"schema\":[{\"id\":\"requestId\",\"display\":true,\"required\":false,\"displayName\":\"requestId\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"jobType\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"jobType\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"data\",\"type\":\"object\",\"display\":true,\"required\":false,\"displayName\":\"data\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[],\"attemptToConvertTypes\":false,\"convertFieldsToString\":true}},\"typeVersion\":1.2},{\"id\":\"2b0314ff-cd82-4b3b-a4a9-5fd8067391eb\",\"name\":\"Generate Learnings\",\"type\":\"n8n-nodes-base.executeWorkflow\",\"position\":[-380,180],\"parameters\":{\"mode\":\"each\",\"options\":{\"waitForSubWorkflow\":true},\"workflowId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"={{ $workflow.id }}\"},\"workflowInputs\":{\"value\":{\"data\":\"={{ $json }}\",\"jobType\":\"deepresearch_learnings\",\"requestId\":\"={{ $('JobType Router').first().json.requestId }}\"},\"schema\":[{\"id\":\"requestId\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"requestId\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"jobType\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"jobType\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"data\",\"type\":\"object\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"data\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[],\"attemptToConvertTypes\":false,\"convertFieldsToString\":true}},\"typeVersion\":1.2},{\"id\":\"f4457d0b-d708-4bca-9973-46d96ed55826\",\"name\":\"Confirmation\",\"type\":\"n8n-nodes-base.form\",\"position\":[780,-420],\"webhookId\":\"2eb17c47-c887-4e95-8641-1b3796452ab9\",\"parameters\":{\"options\":{\"formTitle\":\"DeepResearcher\",\"buttonLabel\":\"Done\",\"formDescription\":\"=\\n

          \\nYour Report Is On Its Way!\\n
          \\nDeepResearcher will now work independently to conduct the research and the compiled report will be uploaded to the following Notion page below when finished.\\n

          \\nPlease click the \\\"Done\\\" button to complete the form.\\n

          \\n
          \"},\"formFields\":{\"values\":[{\"html\":\"=\\n
          \\n
          \\n \\n
          \\n
          \\n
          {{ $json.name }}
          \\n
          \\n {{ $json.property_description }}\\n
          \\n
          \\n
          \\n
          \",\"fieldType\":\"html\"}]}},\"typeVersion\":1},{\"id\":\"af8fe17a-4314-4e92-ad8e-8be0be62984b\",\"name\":\"Research Request\",\"type\":\"n8n-nodes-base.form\",\"position\":[-1560,-460],\"webhookId\":\"46142c14-3692-40f6-80e5-f3d976e95191\",\"parameters\":{\"options\":{\"formTitle\":\"DeepResearcher\",\"formDescription\":\"=\"},\"formFields\":{\"values\":[{\"fieldType\":\"textarea\",\"fieldLabel\":\"What would you like to research?\",\"requiredField\":true},{\"html\":\"\",\"fieldType\":\"html\",\"elementName\":\"input-depth\"},{\"html\":\"\\n\",\"fieldType\":\"html\",\"elementName\":\"input-breadth\"},{\"fieldType\":\"dropdown\",\"fieldLabel\":\"={{ \\\"\\\" }}\",\"multiselect\":true,\"fieldOptions\":{\"values\":[{\"option\":\"=I understand higher depth and breath values I've selected may incur longer wait times and higher costs. I acknowledging this and wish to proceed with the research request.\"}]},\"requiredField\":true}]}},\"typeVersion\":1},{\"id\":\"c67a5e5c-f82b-4e8a-9c99-065d16dfa576\",\"name\":\"Valid Blocks\",\"type\":\"n8n-nodes-base.filter\",\"position\":[740,1600],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"f68cefe0-e109-4d41-9aa3-043f3bc6c449\",\"operator\":{\"type\":\"string\",\"operation\":\"notExists\",\"singleValue\":true},\"leftValue\":\"={{ $json.error }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2},{\"id\":\"70c898a1-a757-452d-83ef-de1998fe13ae\",\"name\":\"Append Blocks\",\"type\":\"n8n-nodes-base.merge\",\"position\":[1000,1760],\"parameters\":{},\"typeVersion\":3},{\"id\":\"591a3fcd-1748-43f7-9766-bc2059c195a0\",\"name\":\"URL Sources to Lists\",\"type\":\"n8n-nodes-base.code\",\"position\":[740,1760],\"parameters\":{\"jsCode\":\"const urls = Object.values($('JobType Router').first().json.data.all_urls\\n .reduce((acc, url) => ({ ...acc, [url]: url }),{}));\\nconst chunksize = 50;\\nconst splits = Math.max(1, Math.floor(urls.length/chunksize));\\n\\nconst blocks = Array(splits).fill(0)\\n .map((_, idx) => {\\n const block = urls\\n .slice(\\n idx * chunksize, \\n (idx * chunksize) + chunksize - 1\\n )\\n .map(url => {\\n return {\\n object: \\\"block\\\",\\n type: \\\"bulleted_list_item\\\",\\n bulleted_list_item: {\\n rich_text: [\\n { type: \\\"text\\\", text: { content: url } }\\n ]\\n }\\n }\\n });\\n return { json: { block } }\\n });\\n\\nreturn [\\n { json: {\\n block:[{\\n \\\"object\\\": \\\"block\\\",\\n \\\"type\\\": \\\"heading_2\\\",\\n \\\"heading_2\\\": {\\n \\\"rich_text\\\": [\\n {\\n \\\"type\\\": \\\"text\\\",\\n \\\"text\\\": {\\n \\\"content\\\": \\\"Sources\\\"\\n }\\n }\\n ]\\n }\\n }]\\n } },\\n ...blocks\\n];\"},\"typeVersion\":2},{\"id\":\"e59dbeea-ccf3-4619-9fe1-24874a91bdab\",\"name\":\"Empty Response\",\"type\":\"n8n-nodes-base.set\",\"position\":[640,1160],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"1de40158-338b-4db3-9e22-6fd63b21f825\",\"name\":\"ResearchGoal\",\"type\":\"string\",\"value\":\"={{ $('Item Ref').first().json.researchGoal }}\"},{\"id\":\"9f59a2d4-5e5a-4d0b-8adf-2832ce746f0f\",\"name\":\"learnings\",\"type\":\"array\",\"value\":\"={{ [] }}\"},{\"id\":\"972ab5f5-0537-4755-afcb-d1db4f09ad60\",\"name\":\"followUpQuestions\",\"type\":\"array\",\"value\":\"={{ [] }}\"},{\"id\":\"90cef471-76b0-465d-91a4-a0e256335cd3\",\"name\":\"urls\",\"type\":\"array\",\"value\":\"={{ [] }}\"}]}},\"typeVersion\":3.4},{\"id\":\"34035b2e-eee9-483e-8125-3b6f1f41cd1d\",\"name\":\"Has Content?\",\"type\":\"n8n-nodes-base.if\",\"position\":[480,1020],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"1ef1039a-4792-47f9-860b-d2ffcffd7129\",\"operator\":{\"type\":\"object\",\"operation\":\"notEmpty\",\"singleValue\":true},\"leftValue\":\"={{ $json }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2},{\"id\":\"fd3fec73-4b1a-4882-8c5a-d4825d9038ad\",\"name\":\"Combine & Send back to Loop\",\"type\":\"n8n-nodes-base.aggregate\",\"position\":[-220,860],\"parameters\":{\"options\":{},\"aggregate\":\"aggregateAllItemData\"},\"typeVersion\":1},{\"id\":\"7c183897-e2ce-46da-90bd-0a39122b85f2\",\"name\":\"For Each Block...\",\"type\":\"n8n-nodes-base.splitInBatches\",\"position\":[1440,1600],\"parameters\":{\"options\":{}},\"typeVersion\":3},{\"id\":\"48b83b0f-94e7-44e2-8bd4-0addddd62264\",\"name\":\"Valid Results\",\"type\":\"n8n-nodes-base.filter\",\"position\":[300,1020],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"f44691e4-f753-47b0-b66a-068a723b6beb\",\"operator\":{\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.crawl.requestStatus }}\",\"rightValue\":\"handled\"},{\"id\":\"8e05df2b-0d4a-47da-9aab-da7e8907cbca\",\"operator\":{\"type\":\"string\",\"operation\":\"notEmpty\",\"singleValue\":true},\"leftValue\":\"={{ $json.markdown }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2,\"alwaysOutputData\":true},{\"id\":\"6124becb-2584-472d-8354-b714d9f1e858\",\"name\":\"RAG Web Browser\",\"type\":\"n8n-nodes-base.httpRequest\",\"onError\":\"continueRegularOutput\",\"position\":[-40,1020],\"parameters\":{\"url\":\"https://api.apify.com/v2/acts/apify~rag-web-browser/run-sync-get-dataset-items\",\"method\":\"POST\",\"options\":{},\"sendBody\":true,\"sendQuery\":true,\"authentication\":\"genericCredentialType\",\"bodyParameters\":{\"parameters\":[{\"name\":\"query\",\"value\":\"={{\\n`${$json.query} -filetype:pdf (-site:tiktok.com OR -site:instagram.com OR -site:youtube.com OR -site:linkedin.com OR -site:reddit.com)`\\n}}\"}]},\"genericAuthType\":\"httpHeaderAuth\",\"queryParameters\":{\"parameters\":[{\"name\":\"memory\",\"value\":\"4096\"},{\"name\":\"timeout\",\"value\":\"180\"}]}},\"typeVersion\":4.2},{\"id\":\"749a5d4d-85ae-4ee3-a79b-6659af666a3a\",\"name\":\"Get Markdown + URL\",\"type\":\"n8n-nodes-base.set\",\"position\":[940,1020],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"c41592db-f9f0-4228-b6d8-0514c9a21fca\",\"name\":\"markdown\",\"type\":\"string\",\"value\":\"={{ $json.markdown }}\"},{\"id\":\"5579a411-94dc-4b10-a276-24adf775be1d\",\"name\":\"url\",\"type\":\"string\",\"value\":\"={{ $json.searchResult.url }}\"}]}},\"typeVersion\":3.4},{\"id\":\"4a5ad2e4-b274-4a2f-bc0f-15d067ad469c\",\"name\":\"Is Apify Auth Error?\",\"type\":\"n8n-nodes-base.if\",\"position\":[140,1020],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"8722e13a-d788-4145-8bea-5bc0ce0a83f8\",\"operator\":{\"type\":\"number\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.error.status }}\",\"rightValue\":401}]}},\"typeVersion\":2.2},{\"id\":\"54118cbc-6466-448d-8832-91ad62a931e2\",\"name\":\"Stop and Error\",\"type\":\"n8n-nodes-base.stopAndError\",\"position\":[300,860],\"parameters\":{\"errorMessage\":\"=Apify Auth Error! Check your API token is valid and make sure you put \\\"Bearer \\\" if using HeaderAuth.\"},\"typeVersion\":1}],\"connections\":{\"Item Ref\":{\"main\":[[{\"node\":\"RAG Web Browser\",\"type\":\"main\",\"index\":0}]]},\"Create Row\":{\"main\":[[{\"node\":\"Initiate DeepResearch\",\"type\":\"main\",\"index\":0}]]},\"Confirmation\":{\"main\":[[{\"node\":\"End Form\",\"type\":\"main\",\"index\":0}]]},\"Has Content?\":{\"main\":[[{\"node\":\"Get Markdown + URL\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Empty Response\",\"type\":\"main\",\"index\":0}]]},\"Valid Blocks\":{\"main\":[[{\"node\":\"Append Blocks\",\"type\":\"main\",\"index\":0}]]},\"Append Blocks\":{\"main\":[[{\"node\":\"For Each Block...\",\"type\":\"main\",\"index\":0}]]},\"HTML to Array\":{\"main\":[[{\"node\":\"Tags to Items\",\"type\":\"main\",\"index\":0}]]},\"SERP to Items\":{\"main\":[[{\"node\":\"For Each Query...\",\"type\":\"main\",\"index\":0}]]},\"Set Variables\":{\"main\":[[{\"node\":\"Clarifying Questions\",\"type\":\"main\",\"index\":0}]]},\"Tags to Items\":{\"main\":[[{\"node\":\"Notion Block Generator\",\"type\":\"main\",\"index\":0}]]},\"Valid Results\":{\"main\":[[{\"node\":\"Has Content?\",\"type\":\"main\",\"index\":0}]]},\"Empty Response\":{\"main\":[[{\"node\":\"For Each Query...\",\"type\":\"main\",\"index\":0}]]},\"Execution Data\":{\"main\":[[{\"node\":\"JobType Router\",\"type\":\"main\",\"index\":0}]]},\"JobType Router\":{\"main\":[[{\"node\":\"Get Existing Row\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Generate SERP Queries\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Get Existing Row1\",\"type\":\"main\",\"index\":0}]]},\"Convert to HTML\":{\"main\":[[{\"node\":\"HTML to Array\",\"type\":\"main\",\"index\":0}]]},\"RAG Web Browser\":{\"main\":[[{\"node\":\"Is Apify Auth Error?\",\"type\":\"main\",\"index\":0}]]},\"Set In-Progress\":{\"main\":[[{\"node\":\"Set Initial Query\",\"type\":\"main\",\"index\":0}]]},\"Get Existing Row\":{\"main\":[[{\"node\":\"Set In-Progress\",\"type\":\"main\",\"index\":0}]]},\"Research Request\":{\"main\":[[{\"node\":\"Set Variables\",\"type\":\"main\",\"index\":0}]]},\"Results to Items\":{\"main\":[[{\"node\":\"Set Next Queries\",\"type\":\"main\",\"index\":0}]]},\"Set Next Queries\":{\"main\":[[{\"node\":\"Generate Learnings\",\"type\":\"main\",\"index\":0}]]},\"Feedback to Items\":{\"main\":[[{\"node\":\"For Each Question...\",\"type\":\"main\",\"index\":0}]]},\"For Each Block...\":{\"main\":[[{\"node\":\"Set Done\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Upload to Notion Page\",\"type\":\"main\",\"index\":0}]]},\"For Each Query...\":{\"main\":[[{\"node\":\"Combine & Send back to Loop\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Item Ref\",\"type\":\"main\",\"index\":0}]]},\"Get Existing Row1\":{\"main\":[[{\"node\":\"DeepResearch Report\",\"type\":\"main\",\"index\":0}]]},\"Get Initial Query\":{\"main\":[[{\"node\":\"Report Page Generator\",\"type\":\"main\",\"index\":0}]]},\"Is Depth Reached?\":{\"main\":[[{\"node\":\"Get Research Results\",\"type\":\"main\",\"index\":0}],[{\"node\":\"DeepResearch Results\",\"type\":\"main\",\"index\":0}]]},\"OpenAI Chat Model\":{\"ai_languageModel\":[[{\"node\":\"DeepResearch Learnings\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Parse JSON blocks\":{\"main\":[[{\"node\":\"Valid Blocks\",\"type\":\"main\",\"index\":0},{\"node\":\"URL Sources to Lists\",\"type\":\"main\",\"index\":0}]]},\"Set Initial Query\":{\"main\":[[{\"node\":\"Generate Learnings\",\"type\":\"main\",\"index\":0}]]},\"Accumulate Results\":{\"main\":[[{\"node\":\"Is Depth Reached?\",\"type\":\"main\",\"index\":0}]]},\"Generate Learnings\":{\"main\":[[{\"node\":\"Accumulate Results\",\"type\":\"main\",\"index\":0}]]},\"Get Markdown + URL\":{\"main\":[[{\"node\":\"DeepResearch Learnings\",\"type\":\"main\",\"index\":0}]]},\"On form submission\":{\"main\":[[{\"node\":\"Research Request\",\"type\":\"main\",\"index\":0}]]},\"OpenAI Chat Model1\":{\"ai_languageModel\":[[{\"node\":\"DeepResearch Report\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"OpenAI Chat Model2\":{\"ai_languageModel\":[[{\"node\":\"Clarifying Questions\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"OpenAI Chat Model3\":{\"ai_languageModel\":[[{\"node\":\"Generate SERP Queries\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"OpenAI Chat Model4\":{\"ai_languageModel\":[[{\"node\":\"Report Page Generator\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"DeepResearch Report\":{\"main\":[[{\"node\":\"Convert to HTML\",\"type\":\"main\",\"index\":0}]]},\"Clarifying Questions\":{\"main\":[[{\"node\":\"Feedback to Items\",\"type\":\"main\",\"index\":0}]]},\"DeepResearch Results\":{\"main\":[[{\"node\":\"Results to Items\",\"type\":\"main\",\"index\":0}]]},\"For Each Question...\":{\"main\":[[{\"node\":\"Get Initial Query\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Ask Clarity Questions\",\"type\":\"main\",\"index\":0}]]},\"Get Research Results\":{\"main\":[[{\"node\":\"Generate Report\",\"type\":\"main\",\"index\":0}]]},\"Is Apify Auth Error?\":{\"main\":[[{\"node\":\"Stop and Error\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Valid Results\",\"type\":\"main\",\"index\":0}]]},\"URL Sources to Lists\":{\"main\":[[{\"node\":\"Append Blocks\",\"type\":\"main\",\"index\":1}]]},\"Ask Clarity Questions\":{\"main\":[[{\"node\":\"For Each Question...\",\"type\":\"main\",\"index\":0}]]},\"Generate SERP Queries\":{\"main\":[[{\"node\":\"SERP to Items\",\"type\":\"main\",\"index\":0}]]},\"Initiate DeepResearch\":{\"main\":[[{\"node\":\"Confirmation\",\"type\":\"main\",\"index\":0}]]},\"Report Page Generator\":{\"main\":[[{\"node\":\"Create Row\",\"type\":\"main\",\"index\":0}]]},\"Upload to Notion Page\":{\"main\":[[{\"node\":\"For Each Block...\",\"type\":\"main\",\"index\":0}],[]]},\"DeepResearch Learnings\":{\"main\":[[{\"node\":\"Research Goal + Learnings\",\"type\":\"main\",\"index\":0}]]},\"Notion Block Generator\":{\"main\":[[{\"node\":\"Parse JSON blocks\",\"type\":\"main\",\"index\":0}]]},\"DeepResearch Subworkflow\":{\"main\":[[{\"node\":\"Execution Data\",\"type\":\"main\",\"index\":0}]]},\"Google Gemini Chat Model\":{\"ai_languageModel\":[[{\"node\":\"Notion Block Generator\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Structured Output Parser\":{\"ai_outputParser\":[[{\"node\":\"DeepResearch Learnings\",\"type\":\"ai_outputParser\",\"index\":0}]]},\"Research Goal + Learnings\":{\"main\":[[{\"node\":\"For Each Query...\",\"type\":\"main\",\"index\":0}]]},\"Structured Output Parser1\":{\"ai_outputParser\":[[{\"node\":\"Clarifying Questions\",\"type\":\"ai_outputParser\",\"index\":0}]]},\"Structured Output Parser2\":{\"ai_outputParser\":[[{\"node\":\"Generate SERP Queries\",\"type\":\"ai_outputParser\",\"index\":0}]]},\"Structured Output Parser4\":{\"ai_outputParser\":[[{\"node\":\"Report Page Generator\",\"type\":\"ai_outputParser\",\"index\":0}]]}}}"}], "metadata": {"node_count": 64, "node_types": {"outputParserStructured": 4, "set": 12, "lmChatOpenAi": 5, "formTrigger": 1, "chainLlm": 6, "splitOut": 4, "noOp": 1, "splitInBatches": 3, "form": 4, "executeWorkflowTrigger": 1, "executeWorkflow": 3, "executionData": 1, "switch": 1, "notion": 5, "if": 3, "markdown": 1, "lmChatGoogleGemini": 1, "httpRequest": 2, "filter": 2, "merge": 1, "code": 1, "aggregate": 1, "stopAndError": 1}, "services": ["ai", "google", "http"], "complexity": "complex", "has_conditions": true, "has_loops": true, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Host Your Own AI Deep Research Agent with n8n, Apify and OpenAI o3"}, {"role": "assistant", "content": "\n**Analyse du besoin**: This template attempts to replicate OpenAI's DeepResearch feature which, at time of writing, is only available to their pro subscribers.\n\nAn agent that uses reasoning to synthesize large amount of onl...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 64 nodes utilisant ai, google, http.\nStructure: logique conditionnelle, traitement par lots, code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"meta\":{\"instanceId\":\"408f9fb9940c3cb18ffdef0e0150fe342d6e655c3a9fac21f0f644e8bedabcd9\",\"templateCredsSetupCompleted\":true},\"nodes\":[{\"id\":\"a342005e-a88e-419b-b929-56ecbba4a936\",\"name\":\"Structured Output Parser\",\"type\":\"@n8n/n8n-nodes-langchain.outputParserStructured\",\"position\":[1300,1180],\"parameters\":{\"schemaType\":\"manual\",\"inputSchema\":\"{\\n \\\"type\\\": \\\"object\\\",\\n \\\"properties\\\": {\\n \\\"learnings\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"description\\\": \\\"List of learnings, max of 3.\\\",\\n \\\"items\\\": { \\\"type\\\": \\\"string\\\" }\\n },\\n \\\"followUpQuestions\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"List of follow-up questions to research the topic further, max of 3.\\\"\\n }\\n }\\n }\\n}\"},\"typeVersion\":1.2},{\"id\":\"126b8151-6d20-43b8-8028-8163112c4c5b\",\"name\":\"Set Variables\",\"type\":\"n8n-nodes-base.set\",\"position\":[-1360,-460],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"df28b12e-7c20-4ff5-b5b8-dc773aa14d4b\",\"name\":\"request_id\",\"type\":\"string\",\"value\":\"={{ $execution.id }}\"},{\"id\":\"9362c1e7-717d-444a-8ea2-6b5f958c9f3f\",\"name\":\"prompt\",\"type\":\"string\",\"value\":\"={{ $json['What would you like to research?'] }}\"},{\"id\":\"09094be4-7844-4a9e-af82-cc8e39322398\",\"name\":\"depth\",\"type\":\"number\",\"value\":\"={{\\n!isNaN($json['input-depth'][0].toNumber())\\n ? $json['input-depth'][0].toNumber()\\n : 1\\n}}\"},{\"id\":\"3fc30a30-7806-4013-835d-97e27ddd7ae1\",\"name\":\"breadth\",\"type\":\"number\",\"value\":\"={{\\n!isNaN($json['input-breadth'][0].toNumber())\\n ? $json['input-breadth'][0].toNumber()\\n : 1\\n}}\"}]}},\"typeVersion\":3.4},{\"id\":\"1d0fb87b-263d-46c2-b016-a29ba1d407ab\",\"name\":\"OpenAI Chat Model\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[1120,1180],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"o3-mini\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"39b300d9-11ba-44f6-8f43-2fe256fe4856\",\"name\":\"OpenAI Chat Model1\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[-860,1760],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"o3-mini\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"018da029-a796-45c5-947c-791e087fe934\",\"name\":\"OpenAI Chat Model2\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[-1060,-300],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"o3-mini\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"525da936-a9eb-4523-b27a-ff6ae7b0e5ef\",\"name\":\"Structured Output Parser1\",\"type\":\"@n8n/n8n-nodes-langchain.outputParserStructured\",\"position\":[-840,-300],\"parameters\":{\"schemaType\":\"manual\",\"inputSchema\":\"{\\n \\\"type\\\": \\\"object\\\",\\n \\\"properties\\\": {\\n \\\"questions\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"description\\\": \\\"Follow up questions to clarify the research direction, max of 3.\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n }\\n}\"},\"typeVersion\":1.2},{\"id\":\"e6664883-cff4-4e09-881e-6b6f684f9cac\",\"name\":\"On form submission\",\"type\":\"n8n-nodes-base.formTrigger\",\"position\":[-1760,-460],\"webhookId\":\"026629c8-7644-493c-b830-d9c72eea307d\",\"parameters\":{\"options\":{\"path\":\"deep_research\",\"ignoreBots\":true,\"buttonLabel\":\"Next\"},\"formTitle\":\" DeepResearcher\",\"formFields\":{\"values\":[{\"fieldType\":\"html\"}]},\"formDescription\":\"=DeepResearcher is a multi-step, recursive approach using the internet to solve complex research tasks, accomplishing in tens of minutes what a human would take many hours.\\n\\nTo use, provide a short summary of what the research and how \\\"deep\\\" you'd like the workflow to investigate. Note, the higher the numbers the more time and cost will occur for the research.\\n\\nThe workflow is designed to complete independently and when finished, a report will be saved in a designated Notion Database.\"},\"typeVersion\":2.2},{\"id\":\"6b8ebc08-c0b1-4af8-99cc-79d09eea7316\",\"name\":\"Generate SERP Queries\",\"type\":\"@n8n/n8n-nodes-langchain.chainLlm\",\"position\":[-1040,820],\"parameters\":{\"text\":\"=Given the following prompt from the user, generate a list of SERP queries to research the topic.\\nReduce the number of words in each query to its keywords only.\\nReturn a maximum of {{ $('JobType Router').first().json.data.breadth }} queries, but feel free to return less if the original prompt is clear. Make sure each query is unique and not similar to each other: {{ $('JobType Router').first().json.data.query.trim() }}\\n\\n{{\\n$('JobType Router').first().json.data.learnings.length\\n ? `Here are some learnings from previous research, use them to generate more specific queries:\\\\n${$('JobType Router').first().json.data.learnings.map(text => `* ${text}`).join('\\\\n')}`\\n : ''\\n}}\",\"messages\":{\"messageValues\":[{\"type\":\"HumanMessagePromptTemplate\",\"message\":\"=You are an expert researcher. Today is {{ $now.toLocaleString() }}. Follow these instructions when responding:\\n - You may be asked to research subjects that is after your knowledge cutoff, assume the user is right when presented with news.\\n - The user is a highly experienced analyst, no need to simplify it, be as detailed as possible and make sure your response is correct.\\n - Be highly organized.\\n - Suggest solutions that I didn't think about.\\n - Be proactive and anticipate my needs.\\n - Treat me as an expert in all subject matter.\\n - Mistakes erode my trust, so be accurate and thorough.\\n - Provide detailed explanations, I'm comfortable with lots of detail.\\n - Value good arguments over authorities, the source is irrelevant.\\n - Consider new technologies and contrarian ideas, not just the conventional wisdom.\\n - You may use high levels of speculation or prediction, just flag it for me.\"}]},\"promptType\":\"define\",\"hasOutputParser\":true},\"typeVersion\":1.5},{\"id\":\"34e1fa5d-bc0c-4b9e-84a7-35db2b08c772\",\"name\":\"Structured Output Parser2\",\"type\":\"@n8n/n8n-nodes-langchain.outputParserStructured\",\"position\":[-860,980],\"parameters\":{\"schemaType\":\"manual\",\"inputSchema\":\"{\\n \\\"type\\\": \\\"object\\\",\\n \\\"properties\\\": {\\n \\\"queries\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"object\\\",\\n \\\"properties\\\": {\\n \\\"query\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"The SERP query\\\"\\n },\\n \\\"researchGoal\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"First talk about the goal of the research that this query is meant to accomplish, then go deeper into how to advance the research once the results are found, mention additional research directions. Be as specific as possible, especially for additional research directions.\\\"\\n }\\n }\\n }\\n }\\n }\\n}\"},\"typeVersion\":1.2},{\"id\":\"be6dd6a2-aacf-4682-8f13-8ae24c4249a3\",\"name\":\"OpenAI Chat Model3\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[-1040,980],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"o3-mini\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"d5ce6e21-cd07-44fa-b6d0-90bf7531ee01\",\"name\":\"Set Initial Query\",\"type\":\"n8n-nodes-base.set\",\"position\":[-580,180],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"acb41e93-70c6-41a3-be0f-e5a74ec3ec88\",\"name\":\"query\",\"type\":\"string\",\"value\":\"={{ $('JobType Router').first().json.data.query }}\"},{\"id\":\"7fc54063-b610-42bc-a250-b1e8847c4d1e\",\"name\":\"learnings\",\"type\":\"array\",\"value\":\"={{ $('JobType Router').first().json.data.learnings }}\"},{\"id\":\"e8f1c158-56fb-41c8-8d86-96add16289bb\",\"name\":\"breadth\",\"type\":\"number\",\"value\":\"={{ $('JobType Router').first().json.data.breadth }}\"}]}},\"typeVersion\":3.4},{\"id\":\"9de6e4a1-a2b5-4a6f-948e-a0585edcae48\",\"name\":\"SERP to Items\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-700,820],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"output.queries\"},\"typeVersion\":1},{\"id\":\"2c9c4cdf-942b-494c-83fb-ed5ec37385ee\",\"name\":\"Item Ref\",\"type\":\"n8n-nodes-base.noOp\",\"position\":[-220,1020],\"parameters\":{},\"typeVersion\":1},{\"id\":\"703c57af-de19-4f00-b580-711a272fa5ca\",\"name\":\"Research Goal + Learnings\",\"type\":\"n8n-nodes-base.set\",\"position\":[1460,1160],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"9acec2cc-64c8-4e62-bed4-c3d9ffab1379\",\"name\":\"researchGoal\",\"type\":\"string\",\"value\":\"={{ $('Item Ref').first().json.researchGoal }}\"},{\"id\":\"1b2d2dad-429b-4fc9-96c5-498f572a85c3\",\"name\":\"learnings\",\"type\":\"array\",\"value\":\"={{ $json.output.learnings }}\"},{\"id\":\"7025f533-02ab-4031-9413-43390fb61f05\",\"name\":\"followUpQuestions\",\"type\":\"string\",\"value\":\"={{ $json.output.followUpQuestions }}\"},{\"id\":\"c9e34ea4-5606-46d6-8d66-cb42d772a8b4\",\"name\":\"urls\",\"type\":\"array\",\"value\":\"={{\\n$('Get Markdown + URL')\\n .all()\\n .map(item => item.json.url)\\n}}\"}]}},\"typeVersion\":3.4},{\"id\":\"16ed2835-3af4-45e3-b5a7-e4342d571aa0\",\"name\":\"Accumulate Results\",\"type\":\"n8n-nodes-base.set\",\"position\":[-200,180],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"db509e90-9a86-431f-8149-4094d22666cc\",\"name\":\"should_stop\",\"type\":\"boolean\",\"value\":\"={{\\n$runIndex >= ($('JobType Router').first().json.data.depth)\\n}}\"},{\"id\":\"90986e2b-8aca-4a22-a9db-ed8809d6284d\",\"name\":\"all_learnings\",\"type\":\"array\",\"value\":\"={{\\nArray($runIndex+1)\\n .fill(0)\\n .flatMap((_,idx) => {\\n try {\\n return $('Generate Learnings')\\n .all(0,idx)\\n .flatMap(item => item.json.data.flatMap(d => d.learnings))\\n } catch (e) {\\n return []\\n }\\n })\\n}}\"},{\"id\":\"3eade958-e8ab-4975-aac4-f4a4a983c163\",\"name\":\"all_urls\",\"type\":\"array\",\"value\":\"={{\\nArray($runIndex+1)\\n .fill(0)\\n .flatMap((_,idx) => {\\n try {\\n return $('Generate Learnings')\\n .all(0,idx)\\n .flatMap(item => item.json.data.flatMap(d => d.urls))\\n } catch (e) {\\n return []\\n }\\n })\\n}}\"}]}},\"executeOnce\":true,\"typeVersion\":3.4},{\"id\":\"0011773e-85c6-4fe1-8554-c23ce50706d0\",\"name\":\"DeepResearch Results\",\"type\":\"n8n-nodes-base.set\",\"position\":[160,360],\"parameters\":{\"mode\":\"raw\",\"options\":{},\"jsonOutput\":\"={{ $('Generate Learnings').item.json }}\"},\"typeVersion\":3.4},{\"id\":\"c0b646d0-1246-4864-8f79-8b7a66e4e083\",\"name\":\"Results to Items\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[320,360],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"data\"},\"typeVersion\":1},{\"id\":\"3c52ec3e-c952-4b5f-ab12-f1b5d02aba74\",\"name\":\"Set Next Queries\",\"type\":\"n8n-nodes-base.set\",\"position\":[480,360],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"d88bfe95-9e73-4d25-b45c-9f164b940b0e\",\"name\":\"query\",\"type\":\"string\",\"value\":\"=Previous research goal: {{ $json.researchGoal }}\\nFollow-up research directions: {{ $json.followUpQuestions.map(q => `\\\\n${q}`).join('') }}\"},{\"id\":\"4aa20690-d998-458a-b1e4-0d72e6a68e6b\",\"name\":\"learnings\",\"type\":\"array\",\"value\":\"={{ $('Accumulate Results').item.json.all_learnings }}\"},{\"id\":\"89acafae-b04a-4d5d-b08b-656e715654e4\",\"name\":\"breadth\",\"type\":\"number\",\"value\":\"={{ $('JobType Router').first().json.data.breadth }}\"}]}},\"typeVersion\":3.4},{\"id\":\"bc59dddc-2b03-481f-91c6-ea8aa378eef0\",\"name\":\"For Each Query...\",\"type\":\"n8n-nodes-base.splitInBatches\",\"position\":[-420,860],\"parameters\":{\"options\":{}},\"typeVersion\":3},{\"id\":\"903c31c4-5fdc-4cb6-8baa-402555997266\",\"name\":\"Feedback to Items\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-720,-460],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"output.questions\"},\"typeVersion\":1},{\"id\":\"59ff671d-5d4f-42ff-b94f-ed30a8531e55\",\"name\":\"Ask Clarity Questions\",\"type\":\"n8n-nodes-base.form\",\"position\":[-360,-380],\"webhookId\":\"d3375ba6-0008-4fcb-96bc-110374de2603\",\"parameters\":{\"options\":{\"formTitle\":\"DeepResearcher\",\"buttonLabel\":\"Answer\",\"formDescription\":\"=\\n

          \\nAnswer the following clarification questions to assist the DeepResearcher better under the research topic.\\n

          \\n
          \\n

          \\nTotal {{ $('Feedback to Items').all().length }} questions.\\n

          \"},\"formFields\":{\"values\":[{\"fieldType\":\"textarea\",\"fieldLabel\":\"={{ $json[\\\"output.questions\\\"] }}\",\"placeholder\":\"=\",\"requiredField\":true}]}},\"typeVersion\":1},{\"id\":\"1c2cf79b-f1a1-4ecc-bb45-3d4460c947bd\",\"name\":\"For Each Question...\",\"type\":\"n8n-nodes-base.splitInBatches\",\"position\":[-540,-460],\"parameters\":{\"options\":{}},\"typeVersion\":3},{\"id\":\"0c9ffa99-2687-4df5-8581-0c5b0b2657a9\",\"name\":\"DeepResearch Subworkflow\",\"type\":\"n8n-nodes-base.executeWorkflowTrigger\",\"position\":[-1880,820],\"parameters\":{\"workflowInputs\":{\"values\":[{\"name\":\"requestId\",\"type\":\"any\"},{\"name\":\"jobType\"},{\"name\":\"data\",\"type\":\"object\"}]}},\"typeVersion\":1.1},{\"id\":\"e87c0f19-6002-4aa2-931a-ca7546146a84\",\"name\":\"Clarifying Questions\",\"type\":\"@n8n/n8n-nodes-langchain.chainLlm\",\"position\":[-1040,-460],\"parameters\":{\"text\":\"=Given the following query from the user, ask some follow up questions to clarify the research direction. Return a maximum of 3 questions, but feel free to return less if the original query is clear: {{ $json.prompt }}`\",\"messages\":{\"messageValues\":[{\"type\":\"HumanMessagePromptTemplate\",\"message\":\"=You are an expert researcher. Today is {{ $now.toLocaleString() }}. Follow these instructions when responding:\\n - You may be asked to research subjects that is after your knowledge cutoff, assume the user is right when presented with news.\\n - The user is a highly experienced analyst, no need to simplify it, be as detailed as possible and make sure your response is correct.\\n - Be highly organized.\\n - Suggest solutions that I didn't think about.\\n - Be proactive and anticipate my needs.\\n - Treat me as an expert in all subject matter.\\n - Mistakes erode my trust, so be accurate and thorough.\\n - Provide detailed explanations, I'm comfortable with lots of detail.\\n - Value good arguments over authorities, the source is irrelevant.\\n - Consider new technologies and contrarian ideas, not just the conventional wisdom.\\n - You may use high levels of speculation or prediction, just flag it for me.\"}]},\"promptType\":\"define\",\"hasOutputParser\":true},\"typeVersion\":1.5},{\"id\":\"0a8c3a01-d4d4-4075-9521-035b7df9aa5a\",\"name\":\"End Form\",\"type\":\"n8n-nodes-base.form\",\"position\":[960,-420],\"webhookId\":\"88f2534b-2b82-4b40-a4bc-97d96384e8fd\",\"parameters\":{\"options\":{},\"operation\":\"completion\",\"completionTitle\":\"=Thank you for using DeepResearcher.\",\"completionMessage\":\"=You may now close this window.\"},\"typeVersion\":1},{\"id\":\"44a3603f-a5a1-4031-8c5f-c748b1007b47\",\"name\":\"Initiate DeepResearch\",\"type\":\"n8n-nodes-base.executeWorkflow\",\"position\":[600,-420],\"parameters\":{\"mode\":\"each\",\"options\":{\"waitForSubWorkflow\":false},\"workflowId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"={{ $workflow.id }}\"},\"workflowInputs\":{\"value\":{\"data\":\"={{\\n{\\n \\\"query\\\": $('Get Initial Query').first().json.query,\\n \\\"learnings\\\": [],\\n \\\"depth\\\": $('Set Variables').first().json.depth,\\n \\\"breadth\\\": $('Set Variables').first().json.breadth,\\n}\\n}}\",\"jobType\":\"deepresearch_initiate\",\"requestId\":\"={{ $('Set Variables').first().json.request_id }}\"},\"schema\":[{\"id\":\"requestId\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"requestId\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"jobType\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"jobType\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"data\",\"type\":\"object\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"data\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[],\"attemptToConvertTypes\":false,\"convertFieldsToString\":true}},\"typeVersion\":1.2},{\"id\":\"b243eb76-9ed9-4327-968f-c21844bc9df4\",\"name\":\"Execution Data\",\"type\":\"n8n-nodes-base.executionData\",\"position\":[-1700,820],\"parameters\":{\"dataToSave\":{\"values\":[{\"key\":\"requestId\",\"value\":\"={{ $json.requestId }}\"},{\"key\":\"=jobType\",\"value\":\"={{ $json.jobType }}\"}]}},\"typeVersion\":1},{\"id\":\"57ca4b22-9349-4b34-8f6b-c502905b5172\",\"name\":\"JobType Router\",\"type\":\"n8n-nodes-base.switch\",\"position\":[-1520,820],\"parameters\":{\"rules\":{\"values\":[{\"outputKey\":\"initiate\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"operator\":{\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.jobType }}\",\"rightValue\":\"deepresearch_initiate\"}]},\"renameOutput\":true},{\"outputKey\":\"learnings\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"ecbfa54d-fc97-48c5-8d3d-f0538b8d727b\",\"operator\":{\"name\":\"filter.operator.equals\",\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.jobType }}\",\"rightValue\":\"deepresearch_learnings\"}]},\"renameOutput\":true},{\"outputKey\":\"report\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"392f9a98-ec22-4e57-9c8e-0e1ed6b7dafa\",\"operator\":{\"name\":\"filter.operator.equals\",\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.jobType }}\",\"rightValue\":\"deepresearch_report\"}]},\"renameOutput\":true}]},\"options\":{}},\"typeVersion\":3.2},{\"id\":\"1f880fbd-71ba-4e5b-8d99-9654ae0c949f\",\"name\":\"OpenAI Chat Model4\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[-20,-280],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"o3-mini\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"ea65589b-106f-4ff1-a6f2-763393c2cb07\",\"name\":\"Get Initial Query\",\"type\":\"n8n-nodes-base.set\",\"position\":[-360,-540],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"14b77741-c3c3-4bd2-be6e-37bd09fcea2b\",\"name\":\"query\",\"type\":\"string\",\"value\":\"=Initial query: {{ $('Set Variables').first().json.prompt }}\\nFollow-up Questions and Answers:\\n{{\\n$input.all()\\n .map(item => {\\n const q = Object.keys(item.json)[0];\\n const a = item.json[q];\\n return `question: ${q}\\\\nanswer: ${a}`;\\n })\\n .join('\\\\n')\\n}}\"}]}},\"executeOnce\":true,\"typeVersion\":3.4},{\"id\":\"09a363f2-6300-430d-8c7e-3e1611ab8e68\",\"name\":\"Structured Output Parser4\",\"type\":\"@n8n/n8n-nodes-langchain.outputParserStructured\",\"position\":[160,-280],\"parameters\":{\"schemaType\":\"manual\",\"inputSchema\":\"{\\n \\\"type\\\": \\\"object\\\",\\n \\\"properties\\\": {\\n \\\"title\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\":\\\" A short title summarising the research topic\\\"\\n },\\n \\\"description\\\": {\\n \\\"type\\\": \\\"string\\\",\\n \\\"description\\\": \\\"A short description to summarise the research topic\\\"\\n }\\n }\\n}\"},\"typeVersion\":1.2},{\"id\":\"9910804e-8376-4e2e-a011-7d32ca951edf\",\"name\":\"Create Row\",\"type\":\"n8n-nodes-base.notion\",\"position\":[300,-420],\"parameters\":{\"title\":\"={{ $json.output.title }}\",\"options\":{},\"resource\":\"databasePage\",\"databaseId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"19486dd6-0c0c-80da-9cb7-eb1468ea9afd\",\"cachedResultUrl\":\"https://www.notion.so/19486dd60c0c80da9cb7eb1468ea9afd\",\"cachedResultName\":\"n8n DeepResearch\"},\"propertiesUi\":{\"propertyValues\":[{\"key\":\"Description|rich_text\",\"textContent\":\"={{ $json.output.description }}\"},{\"key\":\"Status|status\",\"statusValue\":\"Not started\"},{\"key\":\"Request ID|rich_text\",\"textContent\":\"={{ $('Set Variables').first().json.request_id }}\"},{\"key\":\"Name|title\",\"title\":\"={{ $json.output.title }}\"}]}},\"typeVersion\":2.2},{\"id\":\"9f06d9ae-220d-4f5b-bcbf-761b88ba255c\",\"name\":\"Report Page Generator\",\"type\":\"@n8n/n8n-nodes-langchain.chainLlm\",\"position\":[-20,-420],\"parameters\":{\"text\":\"=Create a suitable title for the research report which will be created from the user's query.\\n{{ $json.query }}\",\"promptType\":\"define\",\"hasOutputParser\":true},\"typeVersion\":1.5},{\"id\":\"9fd00d55-1c76-425b-8386-7bc5b2bb47ac\",\"name\":\"Is Depth Reached?\",\"type\":\"n8n-nodes-base.if\",\"position\":[-40,180],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"75d18d88-6ba6-43df-bef7-3e8ad99ad8bd\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json.should_stop }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2},{\"id\":\"f658537b-4f4c-4427-a66f-56cfd950bffc\",\"name\":\"Get Research Results\",\"type\":\"n8n-nodes-base.set\",\"position\":[160,180],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"90b3da00-dcd5-4289-bd45-953146a3b0ba\",\"name\":\"all_learnings\",\"type\":\"array\",\"value\":\"={{ $json.all_learnings }}\"},{\"id\":\"623dbb3d-83a1-44a9-8ad3-48d92bc42811\",\"name\":\"all_urls\",\"type\":\"array\",\"value\":\"={{ $json.all_urls }}\"}]}},\"typeVersion\":3.4},{\"id\":\"6059f3ba-e4a0-4528-894c-6080eedb91c3\",\"name\":\"Get Existing Row\",\"type\":\"n8n-nodes-base.notion\",\"position\":[-1040,180],\"parameters\":{\"limit\":1,\"filters\":{\"conditions\":[{\"key\":\"Request ID|rich_text\",\"condition\":\"equals\",\"richTextValue\":\"={{ $json.requestId.toString() }}\"}]},\"options\":{},\"resource\":\"databasePage\",\"matchType\":\"allFilters\",\"operation\":\"getAll\",\"databaseId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"19486dd6-0c0c-80da-9cb7-eb1468ea9afd\",\"cachedResultUrl\":\"https://www.notion.so/19486dd60c0c80da9cb7eb1468ea9afd\",\"cachedResultName\":\"n8n DeepResearch\"},\"filterType\":\"manual\"},\"typeVersion\":2.2},{\"id\":\"100625bb-bf9a-4993-b387-1c61e486ba6d\",\"name\":\"Set In-Progress\",\"type\":\"n8n-nodes-base.notion\",\"position\":[-840,180],\"parameters\":{\"pageId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"={{ $json.id }}\"},\"options\":{},\"resource\":\"databasePage\",\"operation\":\"update\",\"propertiesUi\":{\"propertyValues\":[{\"key\":\"Status|status\",\"statusValue\":\"In progress\"}]}},\"typeVersion\":2.2},{\"id\":\"864332ea-dd25-4347-a49d-68ed6495c1a9\",\"name\":\"Set Done\",\"type\":\"n8n-nodes-base.notion\",\"position\":[1680,1600],\"parameters\":{\"pageId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"={{ $('Get Existing Row1').first().json.id }}\"},\"options\":{},\"resource\":\"databasePage\",\"operation\":\"update\",\"propertiesUi\":{\"propertyValues\":[{\"key\":\"Status|status\",\"statusValue\":\"Done\"},{\"key\":\"Last Updated|date\",\"date\":\"={{ $now.toISO() }}\"}]}},\"executeOnce\":true,\"typeVersion\":2.2},{\"id\":\"6771568a-e6bd-4c89-a535-089fd1c18fc3\",\"name\":\"Tags to Items\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-60,1600],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"tag\"},\"typeVersion\":1},{\"id\":\"47fce580-7b5b-4bc6-ba52-a8e7af6595b5\",\"name\":\"Convert to HTML\",\"type\":\"n8n-nodes-base.markdown\",\"position\":[-380,1600],\"parameters\":{\"mode\":\"markdownToHtml\",\"options\":{\"tables\":true},\"markdown\":\"={{ $json.text }}\"},\"typeVersion\":1},{\"id\":\"e2fb5a31-9ca5-487b-a7f8-f020759ec53a\",\"name\":\"HTML to Array\",\"type\":\"n8n-nodes-base.set\",\"position\":[-220,1600],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"851b8a3f-c2d3-41ad-bf60-4e0e667f6c58\",\"name\":\"tag\",\"type\":\"array\",\"value\":\"={{ $json.data.match(/||<[^>]+>[^<]*<\\\\/[^>]+>/g) }}\"}]}},\"typeVersion\":3.4},{\"id\":\"5275f9dd-5420-4c59-a330-5f2775b47e51\",\"name\":\"Notion Block Generator\",\"type\":\"@n8n/n8n-nodes-langchain.chainLlm\",\"position\":[100,1600],\"parameters\":{\"text\":\"={{ $json.tag.trim() }}\",\"messages\":{\"messageValues\":[{\"message\":\"=Convert the following html into its equivalent Notion Block as per Notion's API schema.\\n* Ensure the content is always included and remains the same.\\n* Return only a json response.\\n* Generate child-level blocks. Should not define \\\"parent\\\" or \\\"children\\\" property.\\n* Strongly prefer headings, paragraphs, tables and lists type blocks.\\n* available headings are heading_1, heading_2 and heading_3 - h4,h5,h6 should use heading_3 type instead. ensure headings use the rich text definition.\\n* ensure lists blocks include all list items.\\n\\n## Examples\\n\\n1. headings\\n```\\n

          References

          \\n```\\nwould convert to \\n```\\n{\\\"object\\\": \\\"block\\\", \\\"type\\\": \\\"heading_3\\\", \\\"heading_3\\\": { \\\"rich_text\\\": [{\\\"type\\\": \\\"text\\\",\\\"text\\\": {\\\"content\\\": \\\"References\\\"}}]}}\\n```\\n\\n2. lists\\n```\\n
          • hello
          • world
          \\n```\\nwould convert to\\n```\\n[\\n{\\n \\\"object\\\": \\\"block\\\",\\n \\\"type\\\": \\\"bulleted_list_item\\\",\\n \\\"bulleted_list_item\\\": {\\\"rich_text\\\": [{\\\"type\\\": \\\"text\\\",\\\"text\\\": {\\\"content\\\": \\\"hello\\\"}}]}\\n},\\n{\\n \\\"object\\\": \\\"block\\\",\\n \\\"type\\\": \\\"bulleted_list_item\\\",\\n \\\"bulleted_list_item\\\": {\\\"rich_text\\\": [{\\\"type\\\": \\\"text\\\",\\\"text\\\": {\\\"content\\\": \\\"world\\\"}}]}\\n}\\n]\\n```\\n\\n3. tables\\n```\\n\\n \\n \\n \\n \\n \\n \\n \\n \\n
          TechnologyPotential Impact
          5G ConnectivityEnables faster data speeds and advanced apps
          \\n```\\nwould convert to\\n```\\n{\\n \\\"object\\\": \\\"block\\\",\\n \\\"type\\\": \\\"table\\\",\\n \\\"table\\\": {\\n \\\"table_width\\\": 2,\\n \\\"has_column_header\\\": true,\\n \\\"has_row_header\\\": false,\\n \\\"children\\\": [\\n {\\n \\\"object\\\": \\\"block\\\",\\n \\\"type\\\": \\\"table_row\\\",\\n \\\"table_row\\\": {\\n \\\"cells\\\": [\\n [\\n {\\n \\\"type\\\": \\\"text\\\",\\n \\\"text\\\": {\\n \\\"content\\\": \\\"Technology\\\",\\n \\\"link\\\": null\\n }\\n },\\n {\\n \\\"type\\\": \\\"text\\\",\\n \\\"text\\\": {\\n \\\"content\\\": \\\"Potential Impact\\\",\\n \\\"link\\\": null\\n }\\n }\\n ],\\n [\\n {\\n \\\"type\\\": \\\"text\\\",\\n \\\"text\\\": {\\n \\\"content\\\": \\\"5G Connectivity\\\",\\n \\\"link\\\": null\\n }\\n },\\n {\\n \\\"type\\\": \\\"text\\\",\\n \\\"text\\\": {\\n \\\"content\\\": \\\"Enables faster data speeds and advanced apps\\\",\\n \\\"link\\\": null\\n }\\n }\\n ]\\n ]\\n }\\n }\\n ]\\n }\\n}\\n```\\n4. anchor links\\nSince Notion doesn't support anchor links, just convert them to rich text blocks instead.\\n```\\nModule 0: Pre-Course Setup and Learning Principles\\n```\\nconverts to\\n```\\n{\\n \\\"object\\\": \\\"block\\\",\\n \\\"type\\\": \\\"paragraph\\\",\\n \\\"paragraph\\\": {\\n \\\"rich_text\\\": [\\n {\\n \\\"type\\\": \\\"text\\\",\\n \\\"text\\\": {\\n \\\"content\\\": \\\"Module 0: Pre-Course Setup and Learning Principles\\\"\\n }\\n }\\n ]\\n }\\n}\\n```\\n5. Invalid html parts\\nWhen the html is not syntax valid eg. orphaned closing tags, then just skip the conversion and use an empty rich text block.\\n```\\n\\\\n\\n```\\ncan be substituted with\\n```\\n{\\n \\\"object\\\": \\\"block\\\",\\n \\\"type\\\": \\\"paragraph\\\",\\n \\\"paragraph\\\": {\\n \\\"rich_text\\\": [\\n {\\n \\\"type\\\": \\\"text\\\",\\n \\\"text\\\": {\\n \\\"content\\\": \\\" \\\"\\n }\\n }\\n ]\\n }\\n}\\n```\"}]},\"promptType\":\"define\"},\"typeVersion\":1.5},{\"id\":\"30e73ecf-5994-4229-b7f6-01e043e0e65b\",\"name\":\"Google Gemini Chat Model\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatGoogleGemini\",\"position\":[80,1760],\"parameters\":{\"options\":{},\"modelName\":\"models/gemini-2.0-flash\"},\"typeVersion\":1},{\"id\":\"85ce9f7e-0369-41bd-8c31-c4217f400472\",\"name\":\"Parse JSON blocks\",\"type\":\"n8n-nodes-base.set\",\"onError\":\"continueRegularOutput\",\"position\":[420,1600],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"73fcb8a0-2672-4bd5-86de-8075e1e02baf\",\"name\":\"=block\",\"type\":\"array\",\"value\":\"={{\\n(function(){\\n const block = $json.text\\n .replace('```json', '')\\n .replace('```', '')\\n .trim()\\n .parseJson();\\n if (Array.isArray(block)) return block;\\n if (block.type.startsWith('heading_')) {\\n const prev = Number(block.type.split('_')[1]);\\n const next = Math.max(1, prev - 1);\\n if (next !== prev) {\\n block.type = `heading_${next}`;\\n block[`heading_${next}`] = Object.assign({}, block[`heading_${prev}`]);\\n block[`heading_${prev}`] = undefined;\\n }\\n }\\n return [block];\\n})()\\n}}\"}]}},\"executeOnce\":false,\"typeVersion\":3.4},{\"id\":\"349f4323-d65f-4845-accc-6f51340a84c4\",\"name\":\"Upload to Notion Page\",\"type\":\"n8n-nodes-base.httpRequest\",\"onError\":\"continueRegularOutput\",\"maxTries\":2,\"position\":[1680,1760],\"parameters\":{\"url\":\"=https://api.notion.com/v1/blocks/{{ $('Get Existing Row1').first().json.id }}/children\",\"method\":\"PATCH\",\"options\":{\"timeout\":\"={{ 1000 * 60 }}\"},\"jsonBody\":\"={{\\n{\\n \\\"children\\\": $json.block\\n}\\n}}\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"authentication\":\"predefinedCredentialType\",\"headerParameters\":{\"parameters\":[{\"name\":\"Notion-Version\",\"value\":\"2022-06-28\"}]},\"nodeCredentialType\":\"notionApi\"},\"retryOnFail\":true,\"typeVersion\":4.2,\"waitBetweenTries\":3000},{\"id\":\"e2c29aa2-ff79-4bdd-b3c7-cf5e5866db8a\",\"name\":\"Get Existing Row1\",\"type\":\"n8n-nodes-base.notion\",\"position\":[-1020,1600],\"parameters\":{\"limit\":1,\"filters\":{\"conditions\":[{\"key\":\"Request ID|rich_text\",\"condition\":\"equals\",\"richTextValue\":\"={{ $json.requestId.toString() }}\"}]},\"options\":{},\"resource\":\"databasePage\",\"matchType\":\"allFilters\",\"operation\":\"getAll\",\"databaseId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"19486dd6-0c0c-80da-9cb7-eb1468ea9afd\",\"cachedResultUrl\":\"https://www.notion.so/19486dd60c0c80da9cb7eb1468ea9afd\",\"cachedResultName\":\"n8n DeepResearch\"},\"filterType\":\"manual\"},\"typeVersion\":2.2},{\"id\":\"533ede84-1138-426c-93df-c2b862e2d063\",\"name\":\"DeepResearch Report\",\"type\":\"@n8n/n8n-nodes-langchain.chainLlm\",\"position\":[-860,1600],\"parameters\":{\"text\":\"=You are are an expert and insightful researcher.\\n* Given the following prompt from the user, write a final report on the topic using the learnings from research.\\n* Make it as as detailed as possible, aim for 3 or more pages, include ALL the learnings from research.\\n* Format the report in markdown. Use headings, lists and tables only and where appropriate.\\n\\n{{ $('JobType Router').first().json.data.query }}\\n\\nHere are all the learnings from previous research:\\n\\n\\n{{\\n$('JobType Router').first().json.data\\n .all_learnings\\n .map(item => `${item}`) \\n .join('\\\\n')\\n}}\\n\",\"promptType\":\"define\"},\"typeVersion\":1.5},{\"id\":\"efe47725-7fd5-45e7-97c4-d6c133745e5f\",\"name\":\"DeepResearch Learnings\",\"type\":\"@n8n/n8n-nodes-langchain.chainLlm\",\"position\":[1120,1020],\"parameters\":{\"text\":\"=Given the following contents from a SERP search for the query {{ $('Item Ref').first().json.query }}, generate a list of learnings from the contents. Return a maximum of 3 learnings, but feel free to return less if the contents are clear. Make sure each learning is unique and not similar to each other. The learnings should be concise and to the point, as detailed and infromation dense as possible. Make sure to include any entities like people, places, companies, products, things, etc in the learnings, as well as any exact metrics, numbers, or dates. The learnings will be used to research the topic further.\\n\\n\\n{{\\n$input\\n .all()\\n .map(item =>`\\\\n${item.json.markdown.substr(0, 25_000)}\\\\n`)\\n .join('\\\\n')\\n}}\\n\",\"messages\":{\"messageValues\":[{\"type\":\"HumanMessagePromptTemplate\",\"message\":\"=You are an expert researcher. Today is {{ $now.toLocaleString() }}. Follow these instructions when responding:\\n - You may be asked to research subjects that is after your knowledge cutoff, assume the user is right when presented with news.\\n - The user is a highly experienced analyst, no need to simplify it, be as detailed as possible and make sure your response is correct.\\n - Be highly organized.\\n - Suggest solutions that I didn't think about.\\n - Be proactive and anticipate my needs.\\n - Treat me as an expert in all subject matter.\\n - Mistakes erode my trust, so be accurate and thorough.\\n - Provide detailed explanations, I'm comfortable with lots of detail.\\n - Value good arguments over authorities, the source is irrelevant.\\n - Consider new technologies and contrarian ideas, not just the conventional wisdom.\\n - You may use high levels of speculation or prediction, just flag it for me.\"}]},\"promptType\":\"define\",\"hasOutputParser\":true},\"executeOnce\":true,\"typeVersion\":1.5},{\"id\":\"d3b42d13-e8ca-4085-ace9-1d9fb53f5e71\",\"name\":\"Generate Report\",\"type\":\"n8n-nodes-base.executeWorkflow\",\"position\":[480,180],\"parameters\":{\"options\":{\"waitForSubWorkflow\":false},\"workflowId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"={{ $workflow.id }}\"},\"workflowInputs\":{\"value\":{\"data\":\"={{\\n{\\n ...Object.assign({}, $json),\\n query: $('JobType Router').first().json.data.query\\n}\\n}}\",\"jobType\":\"deepresearch_report\",\"requestId\":\"={{ $('JobType Router').first().json.requestId }}\"},\"schema\":[{\"id\":\"requestId\",\"display\":true,\"required\":false,\"displayName\":\"requestId\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"jobType\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"jobType\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"data\",\"type\":\"object\",\"display\":true,\"required\":false,\"displayName\":\"data\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[],\"attemptToConvertTypes\":false,\"convertFieldsToString\":true}},\"typeVersion\":1.2},{\"id\":\"2b0314ff-cd82-4b3b-a4a9-5fd8067391eb\",\"name\":\"Generate Learnings\",\"type\":\"n8n-nodes-base.executeWorkflow\",\"position\":[-380,180],\"parameters\":{\"mode\":\"each\",\"options\":{\"waitForSubWorkflow\":true},\"workflowId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"={{ $workflow.id }}\"},\"workflowInputs\":{\"value\":{\"data\":\"={{ $json }}\",\"jobType\":\"deepresearch_learnings\",\"requestId\":\"={{ $('JobType Router').first().json.requestId }}\"},\"schema\":[{\"id\":\"requestId\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"requestId\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"jobType\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"jobType\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"data\",\"type\":\"object\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"data\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[],\"attemptToConvertTypes\":false,\"convertFieldsToString\":true}},\"typeVersion\":1.2},{\"id\":\"f4457d0b-d708-4bca-9973-46d96ed55826\",\"name\":\"Confirmation\",\"type\":\"n8n-nodes-base.form\",\"position\":[780,-420],\"webhookId\":\"2eb17c47-c887-4e95-8641-1b3796452ab9\",\"parameters\":{\"options\":{\"formTitle\":\"DeepResearcher\",\"buttonLabel\":\"Done\",\"formDescription\":\"=\\n

          \\nYour Report Is On Its Way!\\n
          \\nDeepResearcher will now work independently to conduct the research and the compiled report will be uploaded to the following Notion page below when finished.\\n

          \\nPlease click the \\\"Done\\\" button to complete the form.\\n

          \\n
          \"},\"formFields\":{\"values\":[{\"html\":\"=\\n
          \\n
          \\n \\n
          \\n
          \\n
          {{ $json.name }}
          \\n
          \\n {{ $json.property_description }}\\n
          \\n
          \\n
          \\n
          \",\"fieldType\":\"html\"}]}},\"typeVersion\":1},{\"id\":\"af8fe17a-4314-4e92-ad8e-8be0be62984b\",\"name\":\"Research Request\",\"type\":\"n8n-nodes-base.form\",\"position\":[-1560,-460],\"webhookId\":\"46142c14-3692-40f6-80e5-f3d976e95191\",\"parameters\":{\"options\":{\"formTitle\":\"DeepResearcher\",\"formDescription\":\"=\"},\"formFields\":{\"values\":[{\"fieldType\":\"textarea\",\"fieldLabel\":\"What would you like to research?\",\"requiredField\":true},{\"html\":\"\",\"fieldType\":\"html\",\"elementName\":\"input-depth\"},{\"html\":\"\\n\",\"fieldType\":\"html\",\"elementName\":\"input-breadth\"},{\"fieldType\":\"dropdown\",\"fieldLabel\":\"={{ \\\"\\\" }}\",\"multiselect\":true,\"fieldOptions\":{\"values\":[{\"option\":\"=I understand higher depth and breath values I've selected may incur longer wait times and higher costs. I acknowledging this and wish to proceed with the research request.\"}]},\"requiredField\":true}]}},\"typeVersion\":1},{\"id\":\"c67a5e5c-f82b-4e8a-9c99-065d16dfa576\",\"name\":\"Valid Blocks\",\"type\":\"n8n-nodes-base.filter\",\"position\":[740,1600],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"f68cefe0-e109-4d41-9aa3-043f3bc6c449\",\"operator\":{\"type\":\"string\",\"operation\":\"notExists\",\"singleValue\":true},\"leftValue\":\"={{ $json.error }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2},{\"id\":\"70c898a1-a757-452d-83ef-de1998fe13ae\",\"name\":\"Append Blocks\",\"type\":\"n8n-nodes-base.merge\",\"position\":[1000,1760],\"parameters\":{},\"typeVersion\":3},{\"id\":\"591a3fcd-1748-43f7-9766-bc2059c195a0\",\"name\":\"URL Sources to Lists\",\"type\":\"n8n-nodes-base.code\",\"position\":[740,1760],\"parameters\":{\"jsCode\":\"const urls = Object.values($('JobType Router').first().json.data.all_urls\\n .reduce((acc, url) => ({ ...acc, [url]: url }),{}));\\nconst chunksize = 50;\\nconst splits = Math.max(1, Math.floor(urls.length/chunksize));\\n\\nconst blocks = Array(splits).fill(0)\\n .map((_, idx) => {\\n const block = urls\\n .slice(\\n idx * chunksize, \\n (idx * chunksize) + chunksize - 1\\n )\\n .map(url => {\\n return {\\n object: \\\"block\\\",\\n type: \\\"bulleted_list_item\\\",\\n bulleted_list_item: {\\n rich_text: [\\n { type: \\\"text\\\", text: { content: url } }\\n ]\\n }\\n }\\n });\\n return { json: { block } }\\n });\\n\\nreturn [\\n { json: {\\n block:[{\\n \\\"object\\\": \\\"block\\\",\\n \\\"type\\\": \\\"heading_2\\\",\\n \\\"heading_2\\\": {\\n \\\"rich_text\\\": [\\n {\\n \\\"type\\\": \\\"text\\\",\\n \\\"text\\\": {\\n \\\"content\\\": \\\"Sources\\\"\\n }\\n }\\n ]\\n }\\n }]\\n } },\\n ...blocks\\n];\"},\"typeVersion\":2},{\"id\":\"e59dbeea-ccf3-4619-9fe1-24874a91bdab\",\"name\":\"Empty Response\",\"type\":\"n8n-nodes-base.set\",\"position\":[640,1160],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"1de40158-338b-4db3-9e22-6fd63b21f825\",\"name\":\"ResearchGoal\",\"type\":\"string\",\"value\":\"={{ $('Item Ref').first().json.researchGoal }}\"},{\"id\":\"9f59a2d4-5e5a-4d0b-8adf-2832ce746f0f\",\"name\":\"learnings\",\"type\":\"array\",\"value\":\"={{ [] }}\"},{\"id\":\"972ab5f5-0537-4755-afcb-d1db4f09ad60\",\"name\":\"followUpQuestions\",\"type\":\"array\",\"value\":\"={{ [] }}\"},{\"id\":\"90cef471-76b0-465d-91a4-a0e256335cd3\",\"name\":\"urls\",\"type\":\"array\",\"value\":\"={{ [] }}\"}]}},\"typeVersion\":3.4},{\"id\":\"34035b2e-eee9-483e-8125-3b6f1f41cd1d\",\"name\":\"Has Content?\",\"type\":\"n8n-nodes-base.if\",\"position\":[480,1020],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"1ef1039a-4792-47f9-860b-d2ffcffd7129\",\"operator\":{\"type\":\"object\",\"operation\":\"notEmpty\",\"singleValue\":true},\"leftValue\":\"={{ $json }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2},{\"id\":\"fd3fec73-4b1a-4882-8c5a-d4825d9038ad\",\"name\":\"Combine & Send back to Loop\",\"type\":\"n8n-nodes-base.aggregate\",\"position\":[-220,860],\"parameters\":{\"options\":{},\"aggregate\":\"aggregateAllItemData\"},\"typeVersion\":1},{\"id\":\"7c183897-e2ce-46da-90bd-0a39122b85f2\",\"name\":\"For Each Block...\",\"type\":\"n8n-nodes-base.splitInBatches\",\"position\":[1440,1600],\"parameters\":{\"options\":{}},\"typeVersion\":3},{\"id\":\"48b83b0f-94e7-44e2-8bd4-0addddd62264\",\"name\":\"Valid Results\",\"type\":\"n8n-nodes-base.filter\",\"position\":[300,1020],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"f44691e4-f753-47b0-b66a-068a723b6beb\",\"operator\":{\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.crawl.requestStatus }}\",\"rightValue\":\"handled\"},{\"id\":\"8e05df2b-0d4a-47da-9aab-da7e8907cbca\",\"operator\":{\"type\":\"string\",\"operation\":\"notEmpty\",\"singleValue\":true},\"leftValue\":\"={{ $json.markdown }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2,\"alwaysOutputData\":true},{\"id\":\"6124becb-2584-472d-8354-b714d9f1e858\",\"name\":\"RAG Web Browser\",\"type\":\"n8n-nodes-base.httpRequest\",\"onError\":\"continueRegularOutput\",\"position\":[-40,1020],\"parameters\":{\"url\":\"https://api.apify.com/v2/acts/apify~rag-web-browser/run-sync-get-dataset-items\",\"method\":\"POST\",\"options\":{},\"sendBody\":true,\"sendQuery\":true,\"authentication\":\"genericCredentialType\",\"bodyParameters\":{\"parameters\":[{\"name\":\"query\",\"value\":\"={{\\n`${$json.query} -filetype:pdf (-site:tiktok.com OR -site:instagram.com OR -site:youtube.com OR -site:linkedin.com OR -site:reddit.com)`\\n}}\"}]},\"genericAuthType\":\"httpHeaderAuth\",\"queryParameters\":{\"parameters\":[{\"name\":\"memory\",\"value\":\"4096\"},{\"name\":\"timeout\",\"value\":\"180\"}]}},\"typeVersion\":4.2},{\"id\":\"749a5d4d-85ae-4ee3-a79b-6659af666a3a\",\"name\":\"Get Markdown + URL\",\"type\":\"n8n-nodes-base.set\",\"position\":[940,1020],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"c41592db-f9f0-4228-b6d8-0514c9a21fca\",\"name\":\"markdown\",\"type\":\"string\",\"value\":\"={{ $json.markdown }}\"},{\"id\":\"5579a411-94dc-4b10-a276-24adf775be1d\",\"name\":\"url\",\"type\":\"string\",\"value\":\"={{ $json.searchResult.url }}\"}]}},\"typeVersion\":3.4},{\"id\":\"4a5ad2e4-b274-4a2f-bc0f-15d067ad469c\",\"name\":\"Is Apify Auth Error?\",\"type\":\"n8n-nodes-base.if\",\"position\":[140,1020],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"8722e13a-d788-4145-8bea-5bc0ce0a83f8\",\"operator\":{\"type\":\"number\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.error.status }}\",\"rightValue\":401}]}},\"typeVersion\":2.2},{\"id\":\"54118cbc-6466-448d-8832-91ad62a931e2\",\"name\":\"Stop and Error\",\"type\":\"n8n-nodes-base.stopAndError\",\"position\":[300,860],\"parameters\":{\"errorMessage\":\"=Apify Auth Error! Check your API token is valid and make sure you put \\\"Bearer \\\" if using HeaderAuth.\"},\"typeVersion\":1}],\"connections\":{\"Item Ref\":{\"main\":[[{\"node\":\"RAG Web Browser\",\"type\":\"main\",\"index\":0}]]},\"Create Row\":{\"main\":[[{\"node\":\"Initiate DeepResearch\",\"type\":\"main\",\"index\":0}]]},\"Confirmation\":{\"main\":[[{\"node\":\"End Form\",\"type\":\"main\",\"index\":0}]]},\"Has Content?\":{\"main\":[[{\"node\":\"Get Markdown + URL\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Empty Response\",\"type\":\"main\",\"index\":0}]]},\"Valid Blocks\":{\"main\":[[{\"node\":\"Append Blocks\",\"type\":\"main\",\"index\":0}]]},\"Append Blocks\":{\"main\":[[{\"node\":\"For Each Block...\",\"type\":\"main\",\"index\":0}]]},\"HTML to Array\":{\"main\":[[{\"node\":\"Tags to Items\",\"type\":\"main\",\"index\":0}]]},\"SERP to Items\":{\"main\":[[{\"node\":\"For Each Query...\",\"type\":\"main\",\"index\":0}]]},\"Set Variables\":{\"main\":[[{\"node\":\"Clarifying Questions\",\"type\":\"main\",\"index\":0}]]},\"Tags to Items\":{\"main\":[[{\"node\":\"Notion Block Generator\",\"type\":\"main\",\"index\":0}]]},\"Valid Results\":{\"main\":[[{\"node\":\"Has Content?\",\"type\":\"main\",\"index\":0}]]},\"Empty Response\":{\"main\":[[{\"node\":\"For Each Query...\",\"type\":\"main\",\"index\":0}]]},\"Execution Data\":{\"main\":[[{\"node\":\"JobType Router\",\"type\":\"main\",\"index\":0}]]},\"JobType Router\":{\"main\":[[{\"node\":\"Get Existing Row\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Generate SERP Queries\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Get Existing Row1\",\"type\":\"main\",\"index\":0}]]},\"Convert to HTML\":{\"main\":[[{\"node\":\"HTML to Array\",\"type\":\"main\",\"index\":0}]]},\"RAG Web Browser\":{\"main\":[[{\"node\":\"Is Apify Auth Error?\",\"type\":\"main\",\"index\":0}]]},\"Set In-Progress\":{\"main\":[[{\"node\":\"Set Initial Query\",\"type\":\"main\",\"index\":0}]]},\"Get Existing Row\":{\"main\":[[{\"node\":\"Set In-Progress\",\"type\":\"main\",\"index\":0}]]},\"Research Request\":{\"main\":[[{\"node\":\"Set Variables\",\"type\":\"main\",\"index\":0}]]},\"Results to Items\":{\"main\":[[{\"node\":\"Set Next Queries\",\"type\":\"main\",\"index\":0}]]},\"Set Next Queries\":{\"main\":[[{\"node\":\"Generate Learnings\",\"type\":\"main\",\"index\":0}]]},\"Feedback to Items\":{\"main\":[[{\"node\":\"For Each Question...\",\"type\":\"main\",\"index\":0}]]},\"For Each Block...\":{\"main\":[[{\"node\":\"Set Done\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Upload to Notion Page\",\"type\":\"main\",\"index\":0}]]},\"For Each Query...\":{\"main\":[[{\"node\":\"Combine & Send back to Loop\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Item Ref\",\"type\":\"main\",\"index\":0}]]},\"Get Existing Row1\":{\"main\":[[{\"node\":\"DeepResearch Report\",\"type\":\"main\",\"index\":0}]]},\"Get Initial Query\":{\"main\":[[{\"node\":\"Report Page Generator\",\"type\":\"main\",\"index\":0}]]},\"Is Depth Reached?\":{\"main\":[[{\"node\":\"Get Research Results\",\"type\":\"main\",\"index\":0}],[{\"node\":\"DeepResearch Results\",\"type\":\"main\",\"index\":0}]]},\"OpenAI Chat Model\":{\"ai_languageModel\":[[{\"node\":\"DeepResearch Learnings\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Parse JSON blocks\":{\"main\":[[{\"node\":\"Valid Blocks\",\"type\":\"main\",\"index\":0},{\"node\":\"URL Sources to Lists\",\"type\":\"main\",\"index\":0}]]},\"Set Initial Query\":{\"main\":[[{\"node\":\"Generate Learnings\",\"type\":\"main\",\"index\":0}]]},\"Accumulate Results\":{\"main\":[[{\"node\":\"Is Depth Reached?\",\"type\":\"main\",\"index\":0}]]},\"Generate Learnings\":{\"main\":[[{\"node\":\"Accumulate Results\",\"type\":\"main\",\"index\":0}]]},\"Get Markdown + URL\":{\"main\":[[{\"node\":\"DeepResearch Learnings\",\"type\":\"main\",\"index\":0}]]},\"On form submission\":{\"main\":[[{\"node\":\"Research Request\",\"type\":\"main\",\"index\":0}]]},\"OpenAI Chat Model1\":{\"ai_languageModel\":[[{\"node\":\"DeepResearch Report\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"OpenAI Chat Model2\":{\"ai_languageModel\":[[{\"node\":\"Clarifying Questions\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"OpenAI Chat Model3\":{\"ai_languageModel\":[[{\"node\":\"Generate SERP Queries\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"OpenAI Chat Model4\":{\"ai_languageModel\":[[{\"node\":\"Report Page Generator\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"DeepResearch Report\":{\"main\":[[{\"node\":\"Convert to HTML\",\"type\":\"main\",\"index\":0}]]},\"Clarifying Questions\":{\"main\":[[{\"node\":\"Feedback to Items\",\"type\":\"main\",\"index\":0}]]},\"DeepResearch Results\":{\"main\":[[{\"node\":\"Results to Items\",\"type\":\"main\",\"index\":0}]]},\"For Each Question...\":{\"main\":[[{\"node\":\"Get Initial Query\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Ask Clarity Questions\",\"type\":\"main\",\"index\":0}]]},\"Get Research Results\":{\"main\":[[{\"node\":\"Generate Report\",\"type\":\"main\",\"index\":0}]]},\"Is Apify Auth Error?\":{\"main\":[[{\"node\":\"Stop and Error\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Valid Results\",\"type\":\"main\",\"index\":0}]]},\"URL Sources to Lists\":{\"main\":[[{\"node\":\"Append Blocks\",\"type\":\"main\",\"index\":1}]]},\"Ask Clarity Questions\":{\"main\":[[{\"node\":\"For Each Question...\",\"type\":\"main\",\"index\":0}]]},\"Generate SERP Queries\":{\"main\":[[{\"node\":\"SERP to Items\",\"type\":\"main\",\"index\":0}]]},\"Initiate DeepResearch\":{\"main\":[[{\"node\":\"Confirmation\",\"type\":\"main\",\"index\":0}]]},\"Report Page Generator\":{\"main\":[[{\"node\":\"Create Row\",\"type\":\"main\",\"index\":0}]]},\"Upload to Notion Page\":{\"main\":[[{\"node\":\"For Each Block...\",\"type\":\"main\",\"index\":0}],[]]},\"DeepResearch Learnings\":{\"main\":[[{\"node\":\"Research Goal + Learnings\",\"type\":\"main\",\"index\":0}]]},\"Notion Block Generator\":{\"main\":[[{\"node\":\"Parse JSON blocks\",\"type\":\"main\",\"index\":0}]]},\"DeepResearch Subworkflow\":{\"main\":[[{\"node\":\"Execution Data\",\"type\":\"main\",\"index\":0}]]},\"Google Gemini Chat Model\":{\"ai_languageModel\":[[{\"node\":\"Notion Block Generator\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Structured Output Parser\":{\"ai_outputParser\":[[{\"node\":\"DeepResearch Learnings\",\"type\":\"ai_outputParser\",\"index\":0}]]},\"Research Goal + Learnings\":{\"main\":[[{\"node\":\"For Each Query...\",\"type\":\"main\",\"index\":0}]]},\"Structured Output Parser1\":{\"ai_outputParser\":[[{\"node\":\"Clarifying Questions\",\"type\":\"ai_outputParser\",\"index\":0}]]},\"Structured Output Parser2\":{\"ai_outputParser\":[[{\"node\":\"Generate SERP Queries\",\"type\":\"ai_outputParser\",\"index\":0}]]},\"Structured Output Parser4\":{\"ai_outputParser\":[[{\"node\":\"Report Page Generator\",\"type\":\"ai_outputParser\",\"index\":0}]]}}}"}], "metadata": {"node_count": 64, "node_types": {"outputParserStructured": 4, "set": 12, "lmChatOpenAi": 5, "formTrigger": 1, "chainLlm": 6, "splitOut": 4, "noOp": 1, "splitInBatches": 3, "form": 4, "executeWorkflowTrigger": 1, "executeWorkflow": 3, "executionData": 1, "switch": 1, "notion": 5, "if": 3, "markdown": 1, "lmChatGoogleGemini": 1, "httpRequest": 2, "filter": 2, "merge": 1, "code": 1, "aggregate": 1, "stopAndError": 1}, "services": ["ai", "google", "http"], "complexity": "complex", "has_conditions": true, "has_loops": true, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: You still can use the app in a workflow even if we don’t have a node for that or the existing operation for that. With the HTTP Request node, it is possible to call any API point and use the incoming data in your workflow Main use cases: Connect with apps and services that n8n doesn’t have integration with Web scraping How it works This workflow can be divided into three branches, each serving a distinct purpose: 1.Splitting into Items (HTTP Request - Get Mock Albums): The workflow initiates with a manual trigger (On clicking 'execute'). It performs an HTTP request to retrieve mock albums data from \"https://jsonplaceholder.typicode.com/albums.\" The obtained data is split into items using the Item Lists node, facilitating easier management. 2.Data Scraping (HTTP Request - Get Wikipedia Page"}, {"role": "assistant", "content": "\n**Analyse du besoin**: You still can use the app in a workflow even if we don’t have a node for that or the existing operation for that. With the HTTP Request node, it is possible to call any API point and use the incoming ...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 10 nodes utilisant http.\nStructure: logique conditionnelle, flux standard.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"meta\":{\"instanceId\":\"8c8c5237b8e37b006a7adce87f4369350c58e41f3ca9de16196d3197f69eabcd\"},\"nodes\":[{\"id\":\"25ac6cda-31fb-474a-b6b6-083ec03b9273\",\"name\":\"On clicking 'execute'\",\"type\":\"n8n-nodes-base.manualTrigger\",\"position\":[925,285],\"parameters\":{},\"typeVersion\":1},{\"id\":\"af19bb6d-5f0a-41ca-93b2-dbd27c3fd07e\",\"name\":\"Set\",\"type\":\"n8n-nodes-base.set\",\"position\":[1345,725],\"parameters\":{\"values\":{\"number\":[{\"name\":\"page\"},{\"name\":\"perpage\",\"value\":15}],\"string\":[{\"name\":\"githubUser\",\"value\":\"that-one-tom\"}]},\"options\":{}},\"typeVersion\":1},{\"id\":\"d8402820-fa72-4957-8cf6-432f928ae799\",\"name\":\"Item Lists - Create Items from Body\",\"type\":\"n8n-nodes-base.itemLists\",\"notes\":\"Create Items from Body\",\"position\":[1525,-15],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"body\"},\"notesInFlow\":false,\"typeVersion\":1},{\"id\":\"598939cd-e4c0-4a90-bd1f-f2b13ccbe072\",\"name\":\"HTML Extract - Extract Article Title\",\"type\":\"n8n-nodes-base.htmlExtract\",\"position\":[1505,285],\"parameters\":{\"options\":{},\"sourceData\":\"binary\",\"extractionValues\":{\"values\":[{\"key\":\"ArticleTitle\",\"cssSelector\":\"#firstHeading\"}]}},\"typeVersion\":1},{\"id\":\"1c9b609c-5e41-4444-ade7-e1069943c904\",\"name\":\"Item Lists - Fetch Body\",\"type\":\"n8n-nodes-base.itemLists\",\"position\":[1705,725],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"body\"},\"typeVersion\":1,\"alwaysOutputData\":true},{\"id\":\"15dfab42-440c-4d06-9ba2-b7b17371d009\",\"name\":\"If - Are we finished?\",\"type\":\"n8n-nodes-base.if\",\"position\":[1885,725],\"parameters\":{\"conditions\":{\"string\":[{\"value1\":\"={{$node[\\\"HTTP Request - Get my Stars\\\"].json[\\\"body\\\"]}}\",\"operation\":\"isEmpty\"}]}},\"executeOnce\":true,\"typeVersion\":1},{\"id\":\"ba6e6904-6749-4ea2-84c1-8409b795bcf5\",\"name\":\"Set - Increment Page\",\"type\":\"n8n-nodes-base.set\",\"position\":[2105,745],\"parameters\":{\"values\":{\"string\":[{\"name\":\"page\",\"value\":\"={{$node[\\\"Set\\\"].json[\\\"page\\\"]++}}\"}]},\"options\":{}},\"executeOnce\":true,\"typeVersion\":1},{\"id\":\"9f0df828-27d7-4994-8934-c8fe88af8566\",\"name\":\"HTTP Request - Get Mock Albums\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1345,-15],\"parameters\":{\"url\":\"https://jsonplaceholder.typicode.com/albums\",\"options\":{\"response\":{\"response\":{\"fullResponse\":true}}}},\"typeVersion\":3},{\"id\":\"cbc64010-f6f4-4c35-b4e2-9e1d4a748308\",\"name\":\"HTTP Request - Get Wikipedia Page\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1325,285],\"parameters\":{\"url\":\"https://en.wikipedia.org/wiki/Special:Random\",\"options\":{\"redirect\":{\"redirect\":{\"followRedirects\":true}},\"response\":{\"response\":{\"responseFormat\":\"file\"}}}},\"typeVersion\":3},{\"id\":\"a1a19268-0be8-4379-99a4-4285c68691b5\",\"name\":\"HTTP Request - Get my Stars\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1525,725],\"parameters\":{\"url\":\"=https://api.github.com/users/{{$node[\\\"Set\\\"].json[\\\"githubUser\\\"]}}/starred\",\"options\":{\"response\":{\"response\":{\"fullResponse\":true}}},\"sendQuery\":true,\"queryParameters\":{\"parameters\":[{\"name\":\"per_page\",\"value\":\"={{$node[\\\"Set\\\"].json[\\\"perpage\\\"]}}\"},{\"name\":\"page\",\"value\":\"={{$node[\\\"Set\\\"].json[\\\"page\\\"]}}\"}]}},\"typeVersion\":3}],\"connections\":{\"Set\":{\"main\":[[{\"node\":\"HTTP Request - Get my Stars\",\"type\":\"main\",\"index\":0}]]},\"Set - Increment Page\":{\"main\":[[{\"node\":\"HTTP Request - Get my Stars\",\"type\":\"main\",\"index\":0}]]},\"If - Are we finished?\":{\"main\":[null,[{\"node\":\"Set - Increment Page\",\"type\":\"main\",\"index\":0}]]},\"On clicking 'execute'\":{\"main\":[[{\"node\":\"Set\",\"type\":\"main\",\"index\":0},{\"node\":\"HTTP Request - Get Mock Albums\",\"type\":\"main\",\"index\":0},{\"node\":\"HTTP Request - Get Wikipedia Page\",\"type\":\"main\",\"index\":0}]]},\"Item Lists - Fetch Body\":{\"main\":[[{\"node\":\"If - Are we finished?\",\"type\":\"main\",\"index\":0}]]},\"HTTP Request - Get my Stars\":{\"main\":[[{\"node\":\"Item Lists - Fetch Body\",\"type\":\"main\",\"index\":0}]]},\"HTTP Request - Get Mock Albums\":{\"main\":[[{\"node\":\"Item Lists - Create Items from Body\",\"type\":\"main\",\"index\":0}]]},\"HTTP Request - Get Wikipedia Page\":{\"main\":[[{\"node\":\"HTML Extract - Extract Article Title\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 10, "node_types": {"manualTrigger": 1, "set": 2, "itemLists": 2, "htmlExtract": 1, "if": 1, "httpRequest": 3}, "services": ["http"], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": false, "has_ai": false}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Pulling data from services that n8n doesn’t have a pre-built integration for"}, {"role": "assistant", "content": "\n**Analyse du besoin**: You still can use the app in a workflow even if we don’t have a node for that or the existing operation for that. With the HTTP Request node, it is possible to call any API point and use the incoming ...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 10 nodes utilisant http.\nStructure: logique conditionnelle, flux standard.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"meta\":{\"instanceId\":\"8c8c5237b8e37b006a7adce87f4369350c58e41f3ca9de16196d3197f69eabcd\"},\"nodes\":[{\"id\":\"25ac6cda-31fb-474a-b6b6-083ec03b9273\",\"name\":\"On clicking 'execute'\",\"type\":\"n8n-nodes-base.manualTrigger\",\"position\":[925,285],\"parameters\":{},\"typeVersion\":1},{\"id\":\"af19bb6d-5f0a-41ca-93b2-dbd27c3fd07e\",\"name\":\"Set\",\"type\":\"n8n-nodes-base.set\",\"position\":[1345,725],\"parameters\":{\"values\":{\"number\":[{\"name\":\"page\"},{\"name\":\"perpage\",\"value\":15}],\"string\":[{\"name\":\"githubUser\",\"value\":\"that-one-tom\"}]},\"options\":{}},\"typeVersion\":1},{\"id\":\"d8402820-fa72-4957-8cf6-432f928ae799\",\"name\":\"Item Lists - Create Items from Body\",\"type\":\"n8n-nodes-base.itemLists\",\"notes\":\"Create Items from Body\",\"position\":[1525,-15],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"body\"},\"notesInFlow\":false,\"typeVersion\":1},{\"id\":\"598939cd-e4c0-4a90-bd1f-f2b13ccbe072\",\"name\":\"HTML Extract - Extract Article Title\",\"type\":\"n8n-nodes-base.htmlExtract\",\"position\":[1505,285],\"parameters\":{\"options\":{},\"sourceData\":\"binary\",\"extractionValues\":{\"values\":[{\"key\":\"ArticleTitle\",\"cssSelector\":\"#firstHeading\"}]}},\"typeVersion\":1},{\"id\":\"1c9b609c-5e41-4444-ade7-e1069943c904\",\"name\":\"Item Lists - Fetch Body\",\"type\":\"n8n-nodes-base.itemLists\",\"position\":[1705,725],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"body\"},\"typeVersion\":1,\"alwaysOutputData\":true},{\"id\":\"15dfab42-440c-4d06-9ba2-b7b17371d009\",\"name\":\"If - Are we finished?\",\"type\":\"n8n-nodes-base.if\",\"position\":[1885,725],\"parameters\":{\"conditions\":{\"string\":[{\"value1\":\"={{$node[\\\"HTTP Request - Get my Stars\\\"].json[\\\"body\\\"]}}\",\"operation\":\"isEmpty\"}]}},\"executeOnce\":true,\"typeVersion\":1},{\"id\":\"ba6e6904-6749-4ea2-84c1-8409b795bcf5\",\"name\":\"Set - Increment Page\",\"type\":\"n8n-nodes-base.set\",\"position\":[2105,745],\"parameters\":{\"values\":{\"string\":[{\"name\":\"page\",\"value\":\"={{$node[\\\"Set\\\"].json[\\\"page\\\"]++}}\"}]},\"options\":{}},\"executeOnce\":true,\"typeVersion\":1},{\"id\":\"9f0df828-27d7-4994-8934-c8fe88af8566\",\"name\":\"HTTP Request - Get Mock Albums\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1345,-15],\"parameters\":{\"url\":\"https://jsonplaceholder.typicode.com/albums\",\"options\":{\"response\":{\"response\":{\"fullResponse\":true}}}},\"typeVersion\":3},{\"id\":\"cbc64010-f6f4-4c35-b4e2-9e1d4a748308\",\"name\":\"HTTP Request - Get Wikipedia Page\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1325,285],\"parameters\":{\"url\":\"https://en.wikipedia.org/wiki/Special:Random\",\"options\":{\"redirect\":{\"redirect\":{\"followRedirects\":true}},\"response\":{\"response\":{\"responseFormat\":\"file\"}}}},\"typeVersion\":3},{\"id\":\"a1a19268-0be8-4379-99a4-4285c68691b5\",\"name\":\"HTTP Request - Get my Stars\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1525,725],\"parameters\":{\"url\":\"=https://api.github.com/users/{{$node[\\\"Set\\\"].json[\\\"githubUser\\\"]}}/starred\",\"options\":{\"response\":{\"response\":{\"fullResponse\":true}}},\"sendQuery\":true,\"queryParameters\":{\"parameters\":[{\"name\":\"per_page\",\"value\":\"={{$node[\\\"Set\\\"].json[\\\"perpage\\\"]}}\"},{\"name\":\"page\",\"value\":\"={{$node[\\\"Set\\\"].json[\\\"page\\\"]}}\"}]}},\"typeVersion\":3}],\"connections\":{\"Set\":{\"main\":[[{\"node\":\"HTTP Request - Get my Stars\",\"type\":\"main\",\"index\":0}]]},\"Set - Increment Page\":{\"main\":[[{\"node\":\"HTTP Request - Get my Stars\",\"type\":\"main\",\"index\":0}]]},\"If - Are we finished?\":{\"main\":[null,[{\"node\":\"Set - Increment Page\",\"type\":\"main\",\"index\":0}]]},\"On clicking 'execute'\":{\"main\":[[{\"node\":\"Set\",\"type\":\"main\",\"index\":0},{\"node\":\"HTTP Request - Get Mock Albums\",\"type\":\"main\",\"index\":0},{\"node\":\"HTTP Request - Get Wikipedia Page\",\"type\":\"main\",\"index\":0}]]},\"Item Lists - Fetch Body\":{\"main\":[[{\"node\":\"If - Are we finished?\",\"type\":\"main\",\"index\":0}]]},\"HTTP Request - Get my Stars\":{\"main\":[[{\"node\":\"Item Lists - Fetch Body\",\"type\":\"main\",\"index\":0}]]},\"HTTP Request - Get Mock Albums\":{\"main\":[[{\"node\":\"Item Lists - Create Items from Body\",\"type\":\"main\",\"index\":0}]]},\"HTTP Request - Get Wikipedia Page\":{\"main\":[[{\"node\":\"HTML Extract - Extract Article Title\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 10, "node_types": {"manualTrigger": 1, "set": 2, "itemLists": 2, "htmlExtract": 1, "if": 1, "httpRequest": 3}, "services": ["http"], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": false, "has_ai": false}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: Automate your post-event networking with this intelligent n8n workflow. Triggered instantly after an event, it collects attendee and interaction data, enriches profiles with LinkedIn insights, and uses GPT-4 to analyze engagement and generate tailored follow-up messages. High-value leads are prioritized, messages are sent via email, LinkedIn, or Slack, and all activity is logged in your CRM and database. Save hours of manual follow-up while boosting relationship-building and ROI. 🤝✨ Advanced Features Webhook automation – Starts instantly on event completion Multi-Source Enrichment – Combines event data, interactions, and LinkedIn profiles AI-Powered Insights – GPT-4 analyzes behavior and suggests personalized talking points Smart Priority Filtering – Routes leads into High, Medium, and Low"}, {"role": "assistant", "content": "\n**Analyse du besoin**: Automate your post-event networking with this intelligent n8n workflow. Triggered instantly after an event, it collects attendee and interaction data, enriches profiles with LinkedIn insights, and use...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 20 nodes utilisant ai, database, http.\nStructure: code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"EdsA8tMTiX0U8OGD\",\"meta\":{\"instanceId\":\"dd69efaf8212c74ad206700d104739d3329588a6f3f8381a46a481f34c9cc281\",\"templateCredsSetupCompleted\":true},\"name\":\"Smart Event Follow-Up & Networking Assistant\",\"tags\":[],\"nodes\":[{\"id\":\"77382348-01bf-4d73-806c-67af02c67114\",\"name\":\"Webhook Trigger\",\"type\":\"n8n-nodes-base.webhook\",\"position\":[-272,432],\"webhookId\":\"a962b8dd-4b73-48b3-bb5f-fb7968adca40\",\"parameters\":{\"path\":\"networking-assistant\",\"options\":{},\"httpMethod\":\"POST\",\"responseMode\":\"responseNode\"},\"typeVersion\":1},{\"id\":\"e935b3a3-a41e-45c5-b830-c45476ea5f09\",\"name\":\"Get Attendees\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-48,240],\"parameters\":{\"url\":\"=https://api.eventplatform.com/events/{{ $json.body.eventId }}/attendees\",\"options\":{},\"authentication\":\"genericCredentialType\"},\"typeVersion\":4.1},{\"id\":\"e089c5fe-2a41-4b9a-bc76-0318bab22bc6\",\"name\":\"Get Interactions\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-48,432],\"parameters\":{\"url\":\"=https://api.eventplatform.com/events/{{ $json.body.eventId }}/interactions\",\"options\":{},\"authentication\":\"genericCredentialType\"},\"typeVersion\":4.1},{\"id\":\"5f7f56f1-b1d1-4fa9-9e87-982128a37b5d\",\"name\":\"Enrich LinkedIn Data\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-48,624],\"parameters\":{\"url\":\"=https://api.linkedin.com/v2/people/{{ $json.linkedinId }}\",\"options\":{},\"authentication\":\"genericCredentialType\"},\"typeVersion\":4.1},{\"id\":\"06001185-5d97-4290-9832-3dc0c806f3bc\",\"name\":\"Merge & Enrich Data\",\"type\":\"n8n-nodes-base.code\",\"position\":[176,432],\"parameters\":{},\"typeVersion\":2},{\"id\":\"2c79001e-7667-4fac-a26b-ab64c001ca94\",\"name\":\"AI Analyze Profile\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[480,656],\"parameters\":{\"model\":\"=gpt-4o\",\"options\":{\"temperature\":0.8}},\"typeVersion\":1},{\"id\":\"345b815d-2f48-438c-8a4d-8cf50db45492\",\"name\":\"Filter High Priority\",\"type\":\"n8n-nodes-base.filter\",\"position\":[752,240],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"caseSensitive\":false},\"conditions\":[{\"operator\":{\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.followUpPriority }}\",\"rightValue\":\"high\"}]}},\"typeVersion\":2},{\"id\":\"3893012b-cbc5-44a9-b345-c288cf759562\",\"name\":\"Filter Medium Priority\",\"type\":\"n8n-nodes-base.filter\",\"position\":[752,640],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"caseSensitive\":false},\"conditions\":[{\"operator\":{\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.followUpPriority }}\",\"rightValue\":\"medium\"}]}},\"typeVersion\":2},{\"id\":\"ca7083ce-c154-40d1-aee0-a792efdb1539\",\"name\":\"Generate Email\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[1056,352],\"parameters\":{\"options\":{}},\"typeVersion\":1},{\"id\":\"702d8331-1bbf-4a34-afac-4977fcd40098\",\"name\":\"Generate LinkedIn Msg\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[1056,864],\"parameters\":{\"options\":{}},\"typeVersion\":1},{\"id\":\"bd5c3beb-0e48-45a1-b88d-1657e87a1664\",\"name\":\"Send LinkedIn\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1328,528],\"parameters\":{\"url\":\"=https://api.linkedin.com/v2/messages\",\"options\":{},\"sendBody\":true,\"authentication\":\"genericCredentialType\",\"bodyParameters\":{\"parameters\":[{\"name\":\"recipient\",\"value\":\"={{ $json.linkedinId }}\"},{\"name\":\"message\",\"value\":\"={{ $json.generatedLinkedInMsg }}\"}]}},\"typeVersion\":4.1},{\"id\":\"f8b77773-301d-4846-b205-462123837c66\",\"name\":\"Slack Notification\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1328,784],\"parameters\":{\"url\":\"=https://slack.com/api/chat.postMessage\",\"options\":{},\"sendBody\":true,\"authentication\":\"genericCredentialType\",\"bodyParameters\":{\"parameters\":[{\"name\":\"channel\",\"value\":\"={{ $json.slackUserId }}\"},{\"name\":\"text\",\"value\":\"=Follow up with {{ $json.name }} from event!\"}]}},\"typeVersion\":4.1},{\"id\":\"12fa20d1-4bb6-4f08-8422-73b32e68cc12\",\"name\":\"Update CRM\",\"type\":\"n8n-nodes-base.hubspot\",\"position\":[1552,336],\"parameters\":{\"email\":\"={{ $json.email }}\",\"options\":{},\"additionalFields\":{}},\"typeVersion\":2},{\"id\":\"25976c83-8a67-41bc-9fbf-57bb9c662c20\",\"name\":\"Save to Database\",\"type\":\"n8n-nodes-base.postgres\",\"position\":[1776,432],\"parameters\":{\"table\":\"networking_followups\",\"schema\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"public\"},\"columns\":{\"value\":{},\"schema\":[],\"mappings\":[{\"value\":\"={{ $json.id }}\",\"column\":\"attendee_id\"},{\"value\":\"={{ $('Webhook Trigger').first().json.body.eventId }}\",\"column\":\"event_id\"},{\"value\":\"={{ $json.followUpPriority }}\",\"column\":\"priority\"},{\"value\":\"={{ $json.interactionScore }}\",\"column\":\"interaction_score\"},{\"value\":true,\"column\":\"email_sent\"},{\"value\":\"={{ JSON.stringify($json.aiInsights) }}\",\"column\":\"ai_insights\"},{\"value\":\"={{ $now }}\",\"column\":\"created_at\"}],\"mappingMode\":\"autoMapInputData\",\"matchingColumns\":[],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{}},\"typeVersion\":2.4},{\"id\":\"0f3ab05d-2f77-45eb-9fa0-b296bb645410\",\"name\":\"Generate Analytics\",\"type\":\"n8n-nodes-base.code\",\"position\":[2000,432],\"parameters\":{},\"typeVersion\":2},{\"id\":\"1f32a972-e373-4b26-b2d1-d2f3151dff21\",\"name\":\"Send Response\",\"type\":\"n8n-nodes-base.respondToWebhook\",\"position\":[2224,432],\"parameters\":{\"options\":{},\"respondWith\":\"json\",\"responseBody\":\"={{ {\\n success: true,\\n message: 'Networking assistant completed',\\n analytics: $json\\n} }}\"},\"typeVersion\":1},{\"id\":\"cb0350f4-0ff5-4050-b790-3af2ad5e96d7\",\"name\":\"AI Agent\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[400,432],\"parameters\":{\"options\":{}},\"typeVersion\":2.2},{\"id\":\"220f2155-4052-4454-994a-bc88dc574a5d\",\"name\":\"AI Agent1\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[976,128],\"parameters\":{\"options\":{}},\"typeVersion\":2.2},{\"id\":\"4c17b902-da18-40f1-b8c0-9d78e2a21c0d\",\"name\":\"AI Agent2\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[976,640],\"parameters\":{\"options\":{}},\"typeVersion\":2.2},{\"id\":\"2c9cc858-4882-4645-9570-97783d4c5e6f\",\"name\":\"Send email\",\"type\":\"n8n-nodes-base.emailSend\",\"position\":[1328,240],\"webhookId\":\"ea153704-a86b-4095-9f7f-58de6409bda2\",\"parameters\":{\"options\":{\"allowUnauthorizedCerts\":false},\"subject\":\"=Great connecting at {{ $('Webhook Trigger').first().json.body.eventName }}!\",\"toEmail\":\"xyz@gmail.com\",\"fromEmail\":\"abc@gmail.com\"},\"typeVersion\":2}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"AI Agent\":{\"main\":[[{\"node\":\"Filter High Priority\",\"type\":\"main\",\"index\":0},{\"node\":\"Filter Medium Priority\",\"type\":\"main\",\"index\":0}]]},\"AI Agent1\":{\"main\":[[{\"node\":\"Send email\",\"type\":\"main\",\"index\":0}]]},\"AI Agent2\":{\"main\":[[{\"node\":\"Send LinkedIn\",\"type\":\"main\",\"index\":0},{\"node\":\"Slack Notification\",\"type\":\"main\",\"index\":0}]]},\"Send email\":{\"main\":[[{\"node\":\"Update CRM\",\"type\":\"main\",\"index\":0}]]},\"Update CRM\":{\"main\":[[{\"node\":\"Save to Database\",\"type\":\"main\",\"index\":0}]]},\"Get Attendees\":{\"main\":[[{\"node\":\"Merge & Enrich Data\",\"type\":\"main\",\"index\":0}]]},\"Send LinkedIn\":{\"main\":[[{\"node\":\"Update CRM\",\"type\":\"main\",\"index\":0}]]},\"Generate Email\":{\"ai_languageModel\":[[{\"node\":\"AI Agent1\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Webhook Trigger\":{\"main\":[[{\"node\":\"Get Attendees\",\"type\":\"main\",\"index\":0},{\"node\":\"Get Interactions\",\"type\":\"main\",\"index\":0},{\"node\":\"Enrich LinkedIn Data\",\"type\":\"main\",\"index\":0}]]},\"Get Interactions\":{\"main\":[[{\"node\":\"Merge & Enrich Data\",\"type\":\"main\",\"index\":0}]]},\"Save to Database\":{\"main\":[[{\"node\":\"Generate Analytics\",\"type\":\"main\",\"index\":0}]]},\"AI Analyze Profile\":{\"ai_languageModel\":[[{\"node\":\"AI Agent\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Generate Analytics\":{\"main\":[[{\"node\":\"Send Response\",\"type\":\"main\",\"index\":0}]]},\"Slack Notification\":{\"main\":[[{\"node\":\"Save to Database\",\"type\":\"main\",\"index\":0}]]},\"Merge & Enrich Data\":{\"main\":[[{\"node\":\"AI Agent\",\"type\":\"main\",\"index\":0}]]},\"Enrich LinkedIn Data\":{\"main\":[[{\"node\":\"Merge & Enrich Data\",\"type\":\"main\",\"index\":0}]]},\"Filter High Priority\":{\"main\":[[{\"node\":\"AI Agent1\",\"type\":\"main\",\"index\":0}]]},\"Generate LinkedIn Msg\":{\"ai_languageModel\":[[{\"node\":\"AI Agent2\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Filter Medium Priority\":{\"main\":[[{\"node\":\"AI Agent2\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 20, "node_types": {"webhook": 1, "httpRequest": 5, "code": 2, "lmChatOpenAi": 3, "filter": 2, "hubspot": 1, "postgres": 1, "respondToWebhook": 1, "agent": 3, "emailSend": 1}, "services": ["ai", "database", "http"], "complexity": "complex", "has_conditions": false, "has_loops": false, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Automate Event Follow-Ups with GPT-4, LinkedIn & HubSpot Multi-Channel Outreach"}, {"role": "assistant", "content": "\n**Analyse du besoin**: Automate your post-event networking with this intelligent n8n workflow. Triggered instantly after an event, it collects attendee and interaction data, enriches profiles with LinkedIn insights, and use...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 20 nodes utilisant ai, database, http.\nStructure: code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"EdsA8tMTiX0U8OGD\",\"meta\":{\"instanceId\":\"dd69efaf8212c74ad206700d104739d3329588a6f3f8381a46a481f34c9cc281\",\"templateCredsSetupCompleted\":true},\"name\":\"Smart Event Follow-Up & Networking Assistant\",\"tags\":[],\"nodes\":[{\"id\":\"77382348-01bf-4d73-806c-67af02c67114\",\"name\":\"Webhook Trigger\",\"type\":\"n8n-nodes-base.webhook\",\"position\":[-272,432],\"webhookId\":\"a962b8dd-4b73-48b3-bb5f-fb7968adca40\",\"parameters\":{\"path\":\"networking-assistant\",\"options\":{},\"httpMethod\":\"POST\",\"responseMode\":\"responseNode\"},\"typeVersion\":1},{\"id\":\"e935b3a3-a41e-45c5-b830-c45476ea5f09\",\"name\":\"Get Attendees\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-48,240],\"parameters\":{\"url\":\"=https://api.eventplatform.com/events/{{ $json.body.eventId }}/attendees\",\"options\":{},\"authentication\":\"genericCredentialType\"},\"typeVersion\":4.1},{\"id\":\"e089c5fe-2a41-4b9a-bc76-0318bab22bc6\",\"name\":\"Get Interactions\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-48,432],\"parameters\":{\"url\":\"=https://api.eventplatform.com/events/{{ $json.body.eventId }}/interactions\",\"options\":{},\"authentication\":\"genericCredentialType\"},\"typeVersion\":4.1},{\"id\":\"5f7f56f1-b1d1-4fa9-9e87-982128a37b5d\",\"name\":\"Enrich LinkedIn Data\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-48,624],\"parameters\":{\"url\":\"=https://api.linkedin.com/v2/people/{{ $json.linkedinId }}\",\"options\":{},\"authentication\":\"genericCredentialType\"},\"typeVersion\":4.1},{\"id\":\"06001185-5d97-4290-9832-3dc0c806f3bc\",\"name\":\"Merge & Enrich Data\",\"type\":\"n8n-nodes-base.code\",\"position\":[176,432],\"parameters\":{},\"typeVersion\":2},{\"id\":\"2c79001e-7667-4fac-a26b-ab64c001ca94\",\"name\":\"AI Analyze Profile\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[480,656],\"parameters\":{\"model\":\"=gpt-4o\",\"options\":{\"temperature\":0.8}},\"typeVersion\":1},{\"id\":\"345b815d-2f48-438c-8a4d-8cf50db45492\",\"name\":\"Filter High Priority\",\"type\":\"n8n-nodes-base.filter\",\"position\":[752,240],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"caseSensitive\":false},\"conditions\":[{\"operator\":{\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.followUpPriority }}\",\"rightValue\":\"high\"}]}},\"typeVersion\":2},{\"id\":\"3893012b-cbc5-44a9-b345-c288cf759562\",\"name\":\"Filter Medium Priority\",\"type\":\"n8n-nodes-base.filter\",\"position\":[752,640],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"caseSensitive\":false},\"conditions\":[{\"operator\":{\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.followUpPriority }}\",\"rightValue\":\"medium\"}]}},\"typeVersion\":2},{\"id\":\"ca7083ce-c154-40d1-aee0-a792efdb1539\",\"name\":\"Generate Email\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[1056,352],\"parameters\":{\"options\":{}},\"typeVersion\":1},{\"id\":\"702d8331-1bbf-4a34-afac-4977fcd40098\",\"name\":\"Generate LinkedIn Msg\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[1056,864],\"parameters\":{\"options\":{}},\"typeVersion\":1},{\"id\":\"bd5c3beb-0e48-45a1-b88d-1657e87a1664\",\"name\":\"Send LinkedIn\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1328,528],\"parameters\":{\"url\":\"=https://api.linkedin.com/v2/messages\",\"options\":{},\"sendBody\":true,\"authentication\":\"genericCredentialType\",\"bodyParameters\":{\"parameters\":[{\"name\":\"recipient\",\"value\":\"={{ $json.linkedinId }}\"},{\"name\":\"message\",\"value\":\"={{ $json.generatedLinkedInMsg }}\"}]}},\"typeVersion\":4.1},{\"id\":\"f8b77773-301d-4846-b205-462123837c66\",\"name\":\"Slack Notification\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1328,784],\"parameters\":{\"url\":\"=https://slack.com/api/chat.postMessage\",\"options\":{},\"sendBody\":true,\"authentication\":\"genericCredentialType\",\"bodyParameters\":{\"parameters\":[{\"name\":\"channel\",\"value\":\"={{ $json.slackUserId }}\"},{\"name\":\"text\",\"value\":\"=Follow up with {{ $json.name }} from event!\"}]}},\"typeVersion\":4.1},{\"id\":\"12fa20d1-4bb6-4f08-8422-73b32e68cc12\",\"name\":\"Update CRM\",\"type\":\"n8n-nodes-base.hubspot\",\"position\":[1552,336],\"parameters\":{\"email\":\"={{ $json.email }}\",\"options\":{},\"additionalFields\":{}},\"typeVersion\":2},{\"id\":\"25976c83-8a67-41bc-9fbf-57bb9c662c20\",\"name\":\"Save to Database\",\"type\":\"n8n-nodes-base.postgres\",\"position\":[1776,432],\"parameters\":{\"table\":\"networking_followups\",\"schema\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"public\"},\"columns\":{\"value\":{},\"schema\":[],\"mappings\":[{\"value\":\"={{ $json.id }}\",\"column\":\"attendee_id\"},{\"value\":\"={{ $('Webhook Trigger').first().json.body.eventId }}\",\"column\":\"event_id\"},{\"value\":\"={{ $json.followUpPriority }}\",\"column\":\"priority\"},{\"value\":\"={{ $json.interactionScore }}\",\"column\":\"interaction_score\"},{\"value\":true,\"column\":\"email_sent\"},{\"value\":\"={{ JSON.stringify($json.aiInsights) }}\",\"column\":\"ai_insights\"},{\"value\":\"={{ $now }}\",\"column\":\"created_at\"}],\"mappingMode\":\"autoMapInputData\",\"matchingColumns\":[],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{}},\"typeVersion\":2.4},{\"id\":\"0f3ab05d-2f77-45eb-9fa0-b296bb645410\",\"name\":\"Generate Analytics\",\"type\":\"n8n-nodes-base.code\",\"position\":[2000,432],\"parameters\":{},\"typeVersion\":2},{\"id\":\"1f32a972-e373-4b26-b2d1-d2f3151dff21\",\"name\":\"Send Response\",\"type\":\"n8n-nodes-base.respondToWebhook\",\"position\":[2224,432],\"parameters\":{\"options\":{},\"respondWith\":\"json\",\"responseBody\":\"={{ {\\n success: true,\\n message: 'Networking assistant completed',\\n analytics: $json\\n} }}\"},\"typeVersion\":1},{\"id\":\"cb0350f4-0ff5-4050-b790-3af2ad5e96d7\",\"name\":\"AI Agent\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[400,432],\"parameters\":{\"options\":{}},\"typeVersion\":2.2},{\"id\":\"220f2155-4052-4454-994a-bc88dc574a5d\",\"name\":\"AI Agent1\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[976,128],\"parameters\":{\"options\":{}},\"typeVersion\":2.2},{\"id\":\"4c17b902-da18-40f1-b8c0-9d78e2a21c0d\",\"name\":\"AI Agent2\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[976,640],\"parameters\":{\"options\":{}},\"typeVersion\":2.2},{\"id\":\"2c9cc858-4882-4645-9570-97783d4c5e6f\",\"name\":\"Send email\",\"type\":\"n8n-nodes-base.emailSend\",\"position\":[1328,240],\"webhookId\":\"ea153704-a86b-4095-9f7f-58de6409bda2\",\"parameters\":{\"options\":{\"allowUnauthorizedCerts\":false},\"subject\":\"=Great connecting at {{ $('Webhook Trigger').first().json.body.eventName }}!\",\"toEmail\":\"xyz@gmail.com\",\"fromEmail\":\"abc@gmail.com\"},\"typeVersion\":2}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"AI Agent\":{\"main\":[[{\"node\":\"Filter High Priority\",\"type\":\"main\",\"index\":0},{\"node\":\"Filter Medium Priority\",\"type\":\"main\",\"index\":0}]]},\"AI Agent1\":{\"main\":[[{\"node\":\"Send email\",\"type\":\"main\",\"index\":0}]]},\"AI Agent2\":{\"main\":[[{\"node\":\"Send LinkedIn\",\"type\":\"main\",\"index\":0},{\"node\":\"Slack Notification\",\"type\":\"main\",\"index\":0}]]},\"Send email\":{\"main\":[[{\"node\":\"Update CRM\",\"type\":\"main\",\"index\":0}]]},\"Update CRM\":{\"main\":[[{\"node\":\"Save to Database\",\"type\":\"main\",\"index\":0}]]},\"Get Attendees\":{\"main\":[[{\"node\":\"Merge & Enrich Data\",\"type\":\"main\",\"index\":0}]]},\"Send LinkedIn\":{\"main\":[[{\"node\":\"Update CRM\",\"type\":\"main\",\"index\":0}]]},\"Generate Email\":{\"ai_languageModel\":[[{\"node\":\"AI Agent1\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Webhook Trigger\":{\"main\":[[{\"node\":\"Get Attendees\",\"type\":\"main\",\"index\":0},{\"node\":\"Get Interactions\",\"type\":\"main\",\"index\":0},{\"node\":\"Enrich LinkedIn Data\",\"type\":\"main\",\"index\":0}]]},\"Get Interactions\":{\"main\":[[{\"node\":\"Merge & Enrich Data\",\"type\":\"main\",\"index\":0}]]},\"Save to Database\":{\"main\":[[{\"node\":\"Generate Analytics\",\"type\":\"main\",\"index\":0}]]},\"AI Analyze Profile\":{\"ai_languageModel\":[[{\"node\":\"AI Agent\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Generate Analytics\":{\"main\":[[{\"node\":\"Send Response\",\"type\":\"main\",\"index\":0}]]},\"Slack Notification\":{\"main\":[[{\"node\":\"Save to Database\",\"type\":\"main\",\"index\":0}]]},\"Merge & Enrich Data\":{\"main\":[[{\"node\":\"AI Agent\",\"type\":\"main\",\"index\":0}]]},\"Enrich LinkedIn Data\":{\"main\":[[{\"node\":\"Merge & Enrich Data\",\"type\":\"main\",\"index\":0}]]},\"Filter High Priority\":{\"main\":[[{\"node\":\"AI Agent1\",\"type\":\"main\",\"index\":0}]]},\"Generate LinkedIn Msg\":{\"ai_languageModel\":[[{\"node\":\"AI Agent2\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Filter Medium Priority\":{\"main\":[[{\"node\":\"AI Agent2\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 20, "node_types": {"webhook": 1, "httpRequest": 5, "code": 2, "lmChatOpenAi": 3, "filter": 2, "hubspot": 1, "postgres": 1, "respondToWebhook": 1, "agent": 3, "emailSend": 1}, "services": ["ai", "database", "http"], "complexity": "complex", "has_conditions": false, "has_loops": false, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: Learn Customer Onboarding Automation with n8n ✅ How It Works This smart onboarding automation handles new customer signups by: Receiving signup data via webhook Validating required customer info Creating a contact in HubSpot CRM Sending a personalized welcome email Delivering onboarding documents after 2 hours Sending a personal check-in email after 1 day Sending a Week 1 success guide after 3 days Updating CRM status and notifying the team at each milestone It’s designed for professional onboarding, with built-in timing, CRM integration, and smart notifications to improve engagement and retention. 🛠️ Setup Steps Create Webhook Add a Webhook node in n8n with POST method — this triggers when a new customer signs up. Validate Customer Data Add an IF node to check if email and customerName ar"}, {"role": "assistant", "content": "\n**Analyse du besoin**: Learn Customer Onboarding Automation with n8n\n✅ How It Works\n\nThis smart onboarding automation handles new customer signups by:\n\nReceiving signup data via webhook\nValidating required customer info\nCre...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 15 nodes utilisant nodes natifs.\nStructure: logique conditionnelle, flux standard.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"lZbh3p9grft1d8dr\",\"meta\":{\"instanceId\":\"2000c64071c20843606b95c63795bb0797c41036047055a6586498e855b96efc\"},\"name\":\"Learn Customer Onboarding Automation with n8n\",\"tags\":[],\"nodes\":[{\"id\":\"37703ea3-a8ed-4f05-bb97-dc353311440f\",\"name\":\"New Customer Webhook\",\"type\":\"n8n-nodes-base.webhook\",\"position\":[-700,380],\"webhookId\":\"customer-onboarding-start\",\"parameters\":{\"path\":\"customer-onboarding-start\",\"options\":{},\"httpMethod\":\"POST\"},\"typeVersion\":1},{\"id\":\"b0884a2d-7a79-466a-ab6f-59d36837ed81\",\"name\":\"Create HubSpot Contact\",\"type\":\"n8n-nodes-base.hubspot\",\"position\":[-220,340],\"parameters\":{\"resource\":\"contact\",\"operation\":\"create\",\"authentication\":\"appToken\"},\"typeVersion\":1},{\"id\":\"3251b814-a373-44e5-833f-f801bea6af57\",\"name\":\"Send Team Notification\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[60,260],\"webhookId\":\"e319793b-83b0-4b4e-8cf5-af921cc0e9ec\",\"parameters\":{\"operation\":\"send\"},\"typeVersion\":1},{\"id\":\"d897da64-acd7-4a01-9906-8812f883ff5a\",\"name\":\"Send Welcome Email\",\"type\":\"n8n-nodes-base.emailSend\",\"position\":[60,460],\"parameters\":{\"options\":{},\"subject\":\"Welcome to [Company Name] - Your Journey Starts Here! 🎉\"},\"typeVersion\":1},{\"id\":\"325c5909-063b-4dc8-ae2d-186952e09b5d\",\"name\":\"Wait 2 Hours\",\"type\":\"n8n-nodes-base.wait\",\"position\":[360,360],\"webhookId\":\"ed102052-76a3-4302-a179-f8e09d0f7aed\",\"parameters\":{\"amount\":2},\"typeVersion\":1},{\"id\":\"aabccc2b-84fd-4d6b-bb5b-b6b09920fc63\",\"name\":\"Send Onboarding Documents\",\"type\":\"n8n-nodes-base.emailSend\",\"position\":[660,360],\"parameters\":{\"options\":{},\"subject\":\"Your Onboarding Documents Are Ready! 📋\"},\"typeVersion\":1},{\"id\":\"51b18819-b308-4b57-8248-2776b0c93dde\",\"name\":\"Wait 1 Day\",\"type\":\"n8n-nodes-base.wait\",\"position\":[960,360],\"webhookId\":\"c37979cb-b222-4f35-a0f9-b7dff99ccea8\",\"parameters\":{\"unit\":\"days\"},\"typeVersion\":1},{\"id\":\"73a825f7-723c-43d3-8366-04a2fb4d21b6\",\"name\":\"Update CRM Status\",\"type\":\"n8n-nodes-base.hubspot\",\"position\":[1260,260],\"parameters\":{\"resource\":\"contact\",\"operation\":\"update\"},\"typeVersion\":1},{\"id\":\"becff115-7a2d-4e0b-987a-930063b75e9d\",\"name\":\"Send Personal Check-in\",\"type\":\"n8n-nodes-base.emailSend\",\"position\":[1260,460],\"parameters\":{\"options\":{\"replyTo\":\"success@company.com\"},\"subject\":\"How's your first day going? 🌟\"},\"typeVersion\":1},{\"id\":\"f8c6b848-65ff-4fd3-a505-9a9341e46a01\",\"name\":\"Wait 2 More Days\",\"type\":\"n8n-nodes-base.wait\",\"position\":[1560,360],\"webhookId\":\"4d254f31-2974-4d7b-8669-0f1df857209a\",\"parameters\":{\"unit\":\"days\",\"amount\":2},\"typeVersion\":1},{\"id\":\"412cd830-fd51-4fea-a5ed-8df244bcb833\",\"name\":\"Send Week 1 Success Guide\",\"type\":\"n8n-nodes-base.emailSend\",\"position\":[2120,340],\"parameters\":{\"options\":{},\"subject\":\"Your Week 1 Success Guide + Exclusive Training 🎯\"},\"typeVersion\":1},{\"id\":\"82f636c2-678c-4725-83c0-bf56f87ac961\",\"name\":\"Mark Week 1 Complete\",\"type\":\"n8n-nodes-base.hubspot\",\"position\":[2340,100],\"parameters\":{\"resource\":\"contact\",\"operation\":\"update\"},\"typeVersion\":1},{\"id\":\"20bc62f4-b62f-4150-aa63-7b19975fb3b4\",\"name\":\"Notify Team of Completion\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[2400,540],\"webhookId\":\"00e4a472-30f4-4f63-a96e-8c3deb69c704\",\"parameters\":{\"operation\":\"send\"},\"typeVersion\":1},{\"id\":\"7b75ba51-9ea8-450f-b88f-def30185a1cb\",\"name\":\"Validate Required Fields\",\"type\":\"n8n-nodes-base.if\",\"position\":[-460,380],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":1,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"c1f5e1a0-8c2e-4d1f-9b3a-7e6d5c4b3a21\",\"operator\":{\"type\":\"string\",\"operation\":\"notEmpty\"},\"leftValue\":\"={{ $json.email }}\",\"rightValue\":\"\"},{\"id\":\"d2g6f2b1-9d3f-5e2g-ac4b-8f7e6d5c4b32\",\"operator\":{\"type\":\"string\",\"operation\":\"notEmpty\"},\"leftValue\":\"={{ $json.customerName }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2},{\"id\":\"53eb8ff6-22b2-44ac-a2ef-21c46ae403ce\",\"name\":\"Send Validation Error Alert\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-380,700],\"webhookId\":\"70027811-eb7c-4092-a728-e161bca136b5\",\"parameters\":{\"operation\":\"send\"},\"typeVersion\":1}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Wait 1 Day\":{\"main\":[[{\"node\":\"Update CRM Status\",\"type\":\"main\",\"index\":0},{\"node\":\"Send Personal Check-in\",\"type\":\"main\",\"index\":0}]]},\"Wait 2 Hours\":{\"main\":[[{\"node\":\"Send Onboarding Documents\",\"type\":\"main\",\"index\":0}]]},\"Wait 2 More Days\":{\"main\":[[{\"node\":\"Send Week 1 Success Guide\",\"type\":\"main\",\"index\":0}]]},\"Send Welcome Email\":{\"main\":[[{\"node\":\"Wait 2 Hours\",\"type\":\"main\",\"index\":0}]]},\"New Customer Webhook\":{\"main\":[[{\"node\":\"Validate Required Fields\",\"type\":\"main\",\"index\":0}]]},\"Create HubSpot Contact\":{\"main\":[[{\"node\":\"Send Team Notification\",\"type\":\"main\",\"index\":0},{\"node\":\"Send Welcome Email\",\"type\":\"main\",\"index\":0}]]},\"Send Personal Check-in\":{\"main\":[[{\"node\":\"Wait 2 More Days\",\"type\":\"main\",\"index\":0}]]},\"Validate Required Fields\":{\"main\":[[{\"node\":\"Create HubSpot Contact\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Send Validation Error Alert\",\"type\":\"main\",\"index\":0}]]},\"Send Onboarding Documents\":{\"main\":[[{\"node\":\"Wait 1 Day\",\"type\":\"main\",\"index\":0}]]},\"Send Week 1 Success Guide\":{\"main\":[[{\"node\":\"Mark Week 1 Complete\",\"type\":\"main\",\"index\":0},{\"node\":\"Notify Team of Completion\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 15, "node_types": {"webhook": 1, "hubspot": 3, "telegram": 3, "emailSend": 4, "wait": 3, "if": 1}, "services": [], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": false, "has_ai": false}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Customer Onboarding Automation with HubSpot, Email Sequences and Team Alerts"}, {"role": "assistant", "content": "\n**Analyse du besoin**: Learn Customer Onboarding Automation with n8n\n✅ How It Works\n\nThis smart onboarding automation handles new customer signups by:\n\nReceiving signup data via webhook\nValidating required customer info\nCre...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 15 nodes utilisant nodes natifs.\nStructure: logique conditionnelle, flux standard.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"lZbh3p9grft1d8dr\",\"meta\":{\"instanceId\":\"2000c64071c20843606b95c63795bb0797c41036047055a6586498e855b96efc\"},\"name\":\"Learn Customer Onboarding Automation with n8n\",\"tags\":[],\"nodes\":[{\"id\":\"37703ea3-a8ed-4f05-bb97-dc353311440f\",\"name\":\"New Customer Webhook\",\"type\":\"n8n-nodes-base.webhook\",\"position\":[-700,380],\"webhookId\":\"customer-onboarding-start\",\"parameters\":{\"path\":\"customer-onboarding-start\",\"options\":{},\"httpMethod\":\"POST\"},\"typeVersion\":1},{\"id\":\"b0884a2d-7a79-466a-ab6f-59d36837ed81\",\"name\":\"Create HubSpot Contact\",\"type\":\"n8n-nodes-base.hubspot\",\"position\":[-220,340],\"parameters\":{\"resource\":\"contact\",\"operation\":\"create\",\"authentication\":\"appToken\"},\"typeVersion\":1},{\"id\":\"3251b814-a373-44e5-833f-f801bea6af57\",\"name\":\"Send Team Notification\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[60,260],\"webhookId\":\"e319793b-83b0-4b4e-8cf5-af921cc0e9ec\",\"parameters\":{\"operation\":\"send\"},\"typeVersion\":1},{\"id\":\"d897da64-acd7-4a01-9906-8812f883ff5a\",\"name\":\"Send Welcome Email\",\"type\":\"n8n-nodes-base.emailSend\",\"position\":[60,460],\"parameters\":{\"options\":{},\"subject\":\"Welcome to [Company Name] - Your Journey Starts Here! 🎉\"},\"typeVersion\":1},{\"id\":\"325c5909-063b-4dc8-ae2d-186952e09b5d\",\"name\":\"Wait 2 Hours\",\"type\":\"n8n-nodes-base.wait\",\"position\":[360,360],\"webhookId\":\"ed102052-76a3-4302-a179-f8e09d0f7aed\",\"parameters\":{\"amount\":2},\"typeVersion\":1},{\"id\":\"aabccc2b-84fd-4d6b-bb5b-b6b09920fc63\",\"name\":\"Send Onboarding Documents\",\"type\":\"n8n-nodes-base.emailSend\",\"position\":[660,360],\"parameters\":{\"options\":{},\"subject\":\"Your Onboarding Documents Are Ready! 📋\"},\"typeVersion\":1},{\"id\":\"51b18819-b308-4b57-8248-2776b0c93dde\",\"name\":\"Wait 1 Day\",\"type\":\"n8n-nodes-base.wait\",\"position\":[960,360],\"webhookId\":\"c37979cb-b222-4f35-a0f9-b7dff99ccea8\",\"parameters\":{\"unit\":\"days\"},\"typeVersion\":1},{\"id\":\"73a825f7-723c-43d3-8366-04a2fb4d21b6\",\"name\":\"Update CRM Status\",\"type\":\"n8n-nodes-base.hubspot\",\"position\":[1260,260],\"parameters\":{\"resource\":\"contact\",\"operation\":\"update\"},\"typeVersion\":1},{\"id\":\"becff115-7a2d-4e0b-987a-930063b75e9d\",\"name\":\"Send Personal Check-in\",\"type\":\"n8n-nodes-base.emailSend\",\"position\":[1260,460],\"parameters\":{\"options\":{\"replyTo\":\"success@company.com\"},\"subject\":\"How's your first day going? 🌟\"},\"typeVersion\":1},{\"id\":\"f8c6b848-65ff-4fd3-a505-9a9341e46a01\",\"name\":\"Wait 2 More Days\",\"type\":\"n8n-nodes-base.wait\",\"position\":[1560,360],\"webhookId\":\"4d254f31-2974-4d7b-8669-0f1df857209a\",\"parameters\":{\"unit\":\"days\",\"amount\":2},\"typeVersion\":1},{\"id\":\"412cd830-fd51-4fea-a5ed-8df244bcb833\",\"name\":\"Send Week 1 Success Guide\",\"type\":\"n8n-nodes-base.emailSend\",\"position\":[2120,340],\"parameters\":{\"options\":{},\"subject\":\"Your Week 1 Success Guide + Exclusive Training 🎯\"},\"typeVersion\":1},{\"id\":\"82f636c2-678c-4725-83c0-bf56f87ac961\",\"name\":\"Mark Week 1 Complete\",\"type\":\"n8n-nodes-base.hubspot\",\"position\":[2340,100],\"parameters\":{\"resource\":\"contact\",\"operation\":\"update\"},\"typeVersion\":1},{\"id\":\"20bc62f4-b62f-4150-aa63-7b19975fb3b4\",\"name\":\"Notify Team of Completion\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[2400,540],\"webhookId\":\"00e4a472-30f4-4f63-a96e-8c3deb69c704\",\"parameters\":{\"operation\":\"send\"},\"typeVersion\":1},{\"id\":\"7b75ba51-9ea8-450f-b88f-def30185a1cb\",\"name\":\"Validate Required Fields\",\"type\":\"n8n-nodes-base.if\",\"position\":[-460,380],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":1,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"c1f5e1a0-8c2e-4d1f-9b3a-7e6d5c4b3a21\",\"operator\":{\"type\":\"string\",\"operation\":\"notEmpty\"},\"leftValue\":\"={{ $json.email }}\",\"rightValue\":\"\"},{\"id\":\"d2g6f2b1-9d3f-5e2g-ac4b-8f7e6d5c4b32\",\"operator\":{\"type\":\"string\",\"operation\":\"notEmpty\"},\"leftValue\":\"={{ $json.customerName }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2},{\"id\":\"53eb8ff6-22b2-44ac-a2ef-21c46ae403ce\",\"name\":\"Send Validation Error Alert\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-380,700],\"webhookId\":\"70027811-eb7c-4092-a728-e161bca136b5\",\"parameters\":{\"operation\":\"send\"},\"typeVersion\":1}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Wait 1 Day\":{\"main\":[[{\"node\":\"Update CRM Status\",\"type\":\"main\",\"index\":0},{\"node\":\"Send Personal Check-in\",\"type\":\"main\",\"index\":0}]]},\"Wait 2 Hours\":{\"main\":[[{\"node\":\"Send Onboarding Documents\",\"type\":\"main\",\"index\":0}]]},\"Wait 2 More Days\":{\"main\":[[{\"node\":\"Send Week 1 Success Guide\",\"type\":\"main\",\"index\":0}]]},\"Send Welcome Email\":{\"main\":[[{\"node\":\"Wait 2 Hours\",\"type\":\"main\",\"index\":0}]]},\"New Customer Webhook\":{\"main\":[[{\"node\":\"Validate Required Fields\",\"type\":\"main\",\"index\":0}]]},\"Create HubSpot Contact\":{\"main\":[[{\"node\":\"Send Team Notification\",\"type\":\"main\",\"index\":0},{\"node\":\"Send Welcome Email\",\"type\":\"main\",\"index\":0}]]},\"Send Personal Check-in\":{\"main\":[[{\"node\":\"Wait 2 More Days\",\"type\":\"main\",\"index\":0}]]},\"Validate Required Fields\":{\"main\":[[{\"node\":\"Create HubSpot Contact\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Send Validation Error Alert\",\"type\":\"main\",\"index\":0}]]},\"Send Onboarding Documents\":{\"main\":[[{\"node\":\"Wait 1 Day\",\"type\":\"main\",\"index\":0}]]},\"Send Week 1 Success Guide\":{\"main\":[[{\"node\":\"Mark Week 1 Complete\",\"type\":\"main\",\"index\":0},{\"node\":\"Notify Team of Completion\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 15, "node_types": {"webhook": 1, "hubspot": 3, "telegram": 3, "emailSend": 4, "wait": 3, "if": 1}, "services": [], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": false, "has_ai": false}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: 🤖 Interactive Academic Chatbot (Telegram + MongoDB) Overview 📋 This project is a template for building a complete academic virtual assistant using n8n. It connects to Telegram, answers frequently asked questions by querying MongoDB, keeps the community informed about key dates (via web scraping), and collects user feedback for continuous improvement. How It Works Architecture and Workflow ⚙️ n8n: Orchestration of 3 workflows (chatbot, scraping worker, announcer). Telegram: Frontend for user interaction and sending announcements. MongoDB: Centralized database for FAQs, academic calendar, and feedback logs. Web Scraping: HTTP Request and HTML Extract nodes to read the university's web calendar. Cron: For automatic periodic executions (daily and weekly). Core Processes 🧠 Real-time reception o"}, {"role": "assistant", "content": "\n**Analyse du besoin**: 🤖 Interactive Academic Chatbot (Telegram + MongoDB)\nOverview 📋\n\nThis project is a template for building a complete academic virtual assistant using n8n. It connects to Telegram, answers frequently ask...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 53 nodes utilisant ai, google, http.\nStructure: traitement par lots, code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"qVwL4UVRZaWLVZtQ\",\"meta\":{\"instanceId\":\"8a5440a5ddd0e75b8a9a2e3575b14d94d566aa1e1140eba5b0cc9b9eb91aaea3\",\"templateCredsSetupCompleted\":true},\"name\":\"ESPOLBot CALENDARIO|FAQS\",\"tags\":[],\"nodes\":[{\"id\":\"6d06b9e5-4027-4626-8315-2b02a3087727\",\"name\":\"Construir_Prompt_Gemini1\",\"type\":\"n8n-nodes-base.code\",\"position\":[-1008,2448],\"parameters\":{\"jsCode\":\"const preguntaUsuario = $json.pregunta_usuario;\\nconst faqsRelevantes = $json.contexto_faqs || [];\\n\\nlet contextoFAQs = '';\\nif (faqsRelevantes.length > 0) {\\n contextoFAQs = 'Aqui hay informacion relevante de la base de datos:\\\\n\\\\n';\\n contextoFAQs += faqsRelevantes.map((faq, index) => {\\n return `${index + 1}. P: ${faq.pregunta}\\\\n R: ${faq.respuesta}${faq.enlaces ? `\\\\n Link: ${faq.enlaces}` : ''}`;\\n }).join('\\\\n\\\\n');\\n} else {\\n contextoFAQs = 'No encontre informacion especifica en la base de datos para esta pregunta.';\\n}\\n\\nconst prompt = `Eres un asistente de ESPOL. Un estudiante te pregunto:\\n\\n\\\"${preguntaUsuario}\\\"\\n\\n${contextoFAQs}\\n\\nIMPORTANTE:\\n- La pregunta del usuario ES VALIDA y CLARA\\n- Si hay informacion arriba, usala para responder\\n- Si NO hay informacion especifica, di algo como: \\\"No tengo informacion especifica sobre [tema], pero puedes contactar a ESPOL\\\"\\n- NUNCA digas \\\"no has hecho ninguna pregunta\\\"\\n\\nContactos generales:\\n- Email: admision@espol.edu.ec\\n- Telefono: (04) 2269-269\\n- Web: https://www.espol.edu.ec\\n\\nResponde de forma COMPLETA, clara y util. Incluye TODOS los detalles necesarios:`;\\n\\nreturn [{\\n json: {\\n prompt: prompt\\n }\\n}];\"},\"typeVersion\":2},{\"id\":\"95fcc718-5c12-423d-b062-b9935d3f8506\",\"name\":\"Buscar_FAQs_Relevantes\",\"type\":\"n8n-nodes-base.code\",\"position\":[-1264,2448],\"parameters\":{\"jsCode\":\"function limpiarTexto(texto) {\\n if (!texto) return '';\\n return texto\\n .toLowerCase()\\n .normalize('NFD').replace(/[\\\\u0300-\\\\u036f]/g, '')\\n .replace(/[¿?¡!.,;:]/g, '')\\n .replace(/\\\\s+/g, ' ')\\n .trim();\\n}\\n\\n// Leer la pregunta del Telegram Trigger\\n// En runOnceForAllItems, usar .all() para acceder al primer (y normalmente único) mensaje\\nconst telegramInput = $('Telegram Trigger - Inicio').all()[0]?.json || {};\\nconst preguntaUsuario = telegramInput.message?.text || '';\\nconst chatId = telegramInput.message?.chat?.id || '';\\n\\n// Las FAQs vienen del input (MongoDB)\\nconst todasLasFAQs = $input.all();\\n\\nconst preguntaLimpia = limpiarTexto(preguntaUsuario);\\nconst palabrasUsuario = preguntaLimpia.split(' ').filter(p => p.length > 2);\\n\\nconst faqsRelevantes = [];\\n\\nconsole.log(`========================================`);\\nconsole.log(`Pregunta usuario: \\\"${preguntaUsuario}\\\"`);\\nconsole.log(`Chat ID: ${chatId}`);\\nconsole.log(`Palabras clave: ${palabrasUsuario.join(', ')}`);\\nconsole.log(`Total FAQs en MongoDB: ${todasLasFAQs.length}`);\\n\\nfor (const faq of todasLasFAQs) {\\n const preguntaFAQ = faq.json.PREGUNTA || faq.json.pregunta || '';\\n if (!preguntaFAQ) continue;\\n \\n const preguntaFAQLimpia = limpiarTexto(preguntaFAQ);\\n \\n let coincidencias = 0;\\n for (const palabra of palabrasUsuario) {\\n if (preguntaFAQLimpia.includes(palabra)) {\\n coincidencias++;\\n }\\n }\\n \\n if (coincidencias >= 2) {\\n const score = coincidencias / palabrasUsuario.length;\\n \\n faqsRelevantes.push({\\n pregunta: preguntaFAQ,\\n respuesta: faq.json.RESPUESTA || faq.json.respuesta || '',\\n enlaces: faq.json.ENLACES || faq.json.enlaces || null,\\n similitud: Math.round(score * 100) / 100,\\n coincidencias: coincidencias\\n });\\n }\\n}\\n\\nfaqsRelevantes.sort((a, b) => b.coincidencias - a.coincidencias);\\nconst top10 = faqsRelevantes.slice(0, 10);\\n\\nconsole.log(`FAQs encontradas: ${top10.length}`);\\nif (top10.length > 0) {\\n console.log(`Top 5 candidatas:`);\\n top10.slice(0, 5).forEach((faq, i) => {\\n console.log(` ${i+1}. \\\"${faq.pregunta.substring(0, 70)}...\\\" (${faq.coincidencias} palabras)`);\\n });\\n} else {\\n console.log(`⚠️ NO SE ENCONTRARON FAQs`);\\n}\\nconsole.log(`========================================`);\\n\\nreturn [{\\n json: {\\n pregunta_usuario: preguntaUsuario,\\n contexto_faqs: top10,\\n total_encontradas: top10.length,\\n chat_id: chatId\\n }\\n}];\"},\"typeVersion\":2},{\"id\":\"d5e736d4-9d75-44d5-b1c8-dfe94b289e68\",\"name\":\"Respuesta Usuario1\",\"type\":\"n8n-nodes-base.switch\",\"position\":[-1616,1184],\"parameters\":{\"rules\":{\"values\":[{\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"3874c471-84a4-4058-8a35-0cc833b8617d\",\"operator\":{\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.callback_query.data }}\",\"rightValue\":\"feedback_yes\"}]}},{\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"a53cc39a-2efc-4196-9425-1afba6fc8d7d\",\"operator\":{\"name\":\"filter.operator.equals\",\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.callback_query.data }}\",\"rightValue\":\"feedback_no\"}]}}]},\"options\":{}},\"typeVersion\":3.3},{\"id\":\"d9139b9c-e970-4c60-88b8-47bd105ab0aa\",\"name\":\"Sí - Agradecimiento1\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-1264,1008],\"webhookId\":\"d64de90b-2449-4bcc-8815-f43c2e94c0b5\",\"parameters\":{\"text\":\"🎉 ¡Genial! Me alegra mucho saber que pude ayudarte 💪 Si necesitas algo más, estoy aquí para ti 🤖\",\"chatId\":\"={{ $json.result.id }}\",\"additionalFields\":{\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"9c41f1ef-12bf-4620-9719-821461334db6\",\"name\":\"No - Mensaje Feedback1\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-1264,1152],\"webhookId\":\"606e94b8-5fcd-4977-852e-d0030aacf8a6\",\"parameters\":{\"text\":\"=😔 Lamento que la información no te haya sido útil.\\n¿Podrías contarme qué necesitabas exactamente para mejorar mi ayuda? 🤖\",\"chatId\":\"={{ $json.callback_query.message.chat.id }}\",\"forceReply\":{\"force_reply\":true},\"replyMarkup\":\"forceReply\",\"additionalFields\":{\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"cc0258e3-303c-44e5-8c96-80287ba1ab88\",\"name\":\"Comandos1\",\"type\":\"n8n-nodes-base.switch\",\"position\":[-1248,1664],\"parameters\":{\"rules\":{\"values\":[{\"outputKey\":\"/help\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"62d19c71-6b1b-4d67-9a45-8aff710df07c\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json[\\\"message\\\"] && $json[\\\"message\\\"][\\\"text\\\"] === \\\"/help\\\" }}\",\"rightValue\":\"/start\"}]},\"renameOutput\":true},{\"outputKey\":\"/faqs\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"4a392957-3709-4c6e-a7ac-6f6004836860\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json[\\\"message\\\"] && $json[\\\"message\\\"][\\\"text\\\"] === \\\"/faqs\\\" }}\",\"rightValue\":\"\"}]},\"renameOutput\":true},{\"outputKey\":\"/contact\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"32b9b535-3e0a-4d3f-8691-fdc1e955a9ce\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json[\\\"message\\\"] && $json[\\\"message\\\"][\\\"text\\\"] === \\\"/contact\\\" }}\",\"rightValue\":\"\"}]},\"renameOutput\":true},{\"outputKey\":\"/events\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"9393b68b-7c44-48cf-b2d0-d23289673ff6\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json[\\\"message\\\"] && $json[\\\"message\\\"][\\\"text\\\"] === \\\"/events\\\" }}\",\"rightValue\":\"\"}]},\"renameOutput\":true},{\"outputKey\":\"/feedback\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"df2037b1-36f0-4428-bdd4-b5118f687d8f\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json[\\\"message\\\"] && $json[\\\"message\\\"][\\\"text\\\"] === \\\"/feedback\\\" }}\",\"rightValue\":\"\"}]},\"renameOutput\":true},{\"outputKey\":\"/start\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"58d0352b-c98a-4ac7-bf60-f6a6e6919744\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json[\\\"message\\\"] && $json[\\\"message\\\"][\\\"text\\\"] === \\\"/start\\\" }}\",\"rightValue\":\"\"}]},\"renameOutput\":true}]},\"options\":{},\"looseTypeValidation\":true},\"typeVersion\":3.3},{\"id\":\"79a97506-c1e2-4049-a62a-e5820b681a0d\",\"name\":\"Inicio - Feedback\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-880,1312],\"webhookId\":\"c87b9628-09ed-468b-ab95-9b97e4c4f0ef\",\"parameters\":{\"text\":\"=💬 *Enviar Feedback*\\n\\n¿Tienes alguna sugerencia o comentario sobre el bot? \\n\\n📝 Escribe tu mensaje a continuación y lo revisaremos.\\n\\n🤖 *¡Tu opinión es importante!* \\n\\n💡 *Tip:* Los botones 👍 👎 aparecen después de cada respuesta para que califiques la información.\",\"chatId\":\"={{ $json.message.chat.id }}\",\"replyMarkup\":\"inlineKeyboard\",\"inlineKeyboard\":{\"rows\":[{\"row\":{\"buttons\":[{\"text\":\"👍 Sí, me ayudó\",\"additionalFields\":{\"callback_data\":\"feedback_yes\"}},{\"text\":\"👎 No, no me ayudó\",\"additionalFields\":{\"callback_data\":\"feedback_no\"}}]}}]},\"additionalFields\":{\"parse_mode\":\"Markdown\",\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"accfeb10-fcb6-4b1e-a1bb-a40ed82ebcdd\",\"name\":\"FAQs\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-880,784],\"webhookId\":\"04237280-d7f2-4b1e-96cf-37343b850b8b\",\"parameters\":{\"text\":\"💬 Sección de Consultas – ChatBot ESPOL\\n\\nEstás en la sección de preguntas frecuentes.\\nAquí puedes escribir cualquier duda o consulta sobre la universidad —por ejemplo, temas de matrícula, eventos, horarios o servicios estudiantiles— y te responderé enseguida.\\n\\n✍️ Escribe tu pregunta para continuar.\\nPor ejemplo: “Necesito información sobre los eventos de esta semana” o “¿Dónde puedo comunicarme con admisiones?”\",\"chatId\":\"={{ $('Telegram Trigger - Inicio').item.json.message.chat.id }}\",\"additionalFields\":{\"parse_mode\":\"Markdown\",\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"ccd1f1ed-5aa2-402c-a40e-5650ee6066d7\",\"name\":\"Leer FAQs de MongoDB\",\"type\":\"n8n-nodes-base.mongoDb\",\"position\":[-1520,2448],\"parameters\":{\"options\":{},\"collection\":\"espol_faqs\"},\"typeVersion\":1.2},{\"id\":\"6529ea5d-0af3-4acc-b81b-087730a484b6\",\"name\":\"Telegram Trigger - Inicio\",\"type\":\"n8n-nodes-base.telegramTrigger\",\"position\":[-1872,1744],\"webhookId\":\"472c70d1-8362-4668-83dc-3e7c2985bc08\",\"parameters\":{\"updates\":[\"message\",\"callback_query\",\"*\"],\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"5bfddfd3-92ac-432f-aa64-3f19ab58f30a\",\"name\":\"Respuesta Contact\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-880,960],\"webhookId\":\"57a49a16-8222-4da4-8df5-06b6325c4083\",\"parameters\":{\"text\":\"=📞 *Información de Contacto ESPOL*\\n\\n🌐 Web: https://www.espol.edu.ec\\n📧 Email: admision@espol.edu.ec\\n📱 Teléfono: (04) 2269-269\\n\\n📍 Campus Gustavo Galindo Velasco\\nKm. 30.5 Vía Perimetral\\nGuayaquil, Ecuador\\n\\n📧 Otros contactos:\\nComunicación: comunicacion@espol.edu.ec\\nRelaciones Externas y Vinculación Corporativa: relex@espol.edu.ec\\nPostgrados: postgrad@espol.edu.ec\\nTransparencia: transparencia@espol.edu.ec\",\"chatId\":\"={{ $('Telegram Trigger - Inicio').item.json.message.chat.id }}\",\"additionalFields\":{\"parse_mode\":\"Markdown\",\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"8aa3525d-815a-486a-92cb-9d9e5da991e5\",\"name\":\"Respuesta Events\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-880,1136],\"webhookId\":\"8688a44d-b766-45c4-b314-3ef4dc105e1d\",\"parameters\":{\"text\":\"=📅 *Próximos Eventos Académicos*\\n\\nPara ver el calendario completo de eventos, visita:\\nhttps://www.espol.edu.ec/es/calendario-academico\\n\\nO pregúntame sobre fechas específicas, por ejemplo:\\n\\\"¿Cuándo son las vacaciones?\\\"\\n\\\"¿Cuándo es el examen de admisión?\\\"\",\"chatId\":\"={{ $json.message.chat.id }}\",\"additionalFields\":{\"parse_mode\":\"Markdown\",\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"767c3c89-dfb0-4505-8c87-a0208fe31aba\",\"name\":\"Limpiar texto Gemini\",\"type\":\"n8n-nodes-base.code\",\"position\":[-480,2448],\"parameters\":{\"jsCode\":\"const geminiResponse = $input.first().json;\\nconst chatId = $('Buscar_FAQs_Relevantes').first().json.chat_id;\\n\\nlet texto = '';\\n\\ntry {\\n if (geminiResponse.candidates && geminiResponse.candidates[0] && geminiResponse.candidates[0].content && geminiResponse.candidates[0].content.parts) {\\n texto = geminiResponse.candidates[0].content.parts[0].text;\\n } else if (geminiResponse.content && geminiResponse.content.parts) {\\n texto = geminiResponse.content.parts[0].text;\\n } else if (geminiResponse.text) {\\n texto = geminiResponse.text;\\n } else {\\n texto = \\\"Lo siento, hubo un problema al procesar la respuesta.\\\";\\n }\\n} catch (error) {\\n texto = \\\"Lo siento, ocurrio un error.\\\";\\n}\\n\\nif (texto && texto.length > 0) {\\n texto = texto.replace(/\\\\*\\\\*/g, '').replace(/`/g, '').trim();\\n}\\n\\nreturn [{\\n json: {\\n texto_limpio: texto,\\n chat_id: chatId\\n }\\n}];\"},\"typeVersion\":2},{\"id\":\"7cabbbc4-e002-4c04-a4d9-b5c3633e98af\",\"name\":\"Get a chat\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-1488,1056],\"webhookId\":\"4540ece6-38eb-40ac-bb7c-862f2e198807\",\"parameters\":{\"chatId\":\"={{ $json.callback_query.message.chat.id }}\",\"resource\":\"chat\"},\"typeVersion\":1.2},{\"id\":\"b5cdf1bf-6f19-4e62-a812-022e5fe6073c\",\"name\":\"Switch_Que_BD_Leer\",\"type\":\"n8n-nodes-base.switch\",\"position\":[-1856,2304],\"parameters\":{\"rules\":{\"values\":[{\"outputKey\":\"=Consultar Calendario\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"9404fad9-6063-443e-9a4c-80c86a20a6a9\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json.es_consulta_calendario }}\",\"rightValue\":\"\"}]},\"renameOutput\":true}]},\"options\":{\"fallbackOutput\":\"extra\"}},\"typeVersion\":3.3},{\"id\":\"09ddecdf-9223-4371-bd53-9d836315b7a3\",\"name\":\"Detector_Calendario_Pre\",\"type\":\"n8n-nodes-base.code\",\"position\":[-2064,2304],\"parameters\":{\"jsCode\":\"// ===== DETECTOR PRE-LECTURA DE CALENDARIO =====\\n\\nfunction limpiarTexto(texto) {\\n if (!texto) return '';\\n return texto\\n .toLowerCase()\\n .normalize('NFD').replace(/[\\\\u0300-\\\\u036f]/g, '')\\n .replace(/[¿?¡!.,;:]/g, '')\\n .replace(/\\\\s+/g, ' ')\\n .trim();\\n}\\n\\n// Procesar todos los items entrantes del Trigger\\nconst inputItems = $('Telegram Trigger - Inicio').all();\\nconst resultados = [];\\n\\nfor (const item of inputItems) {\\n const preguntaUsuario = item.json.message?.text || '';\\n const chatId = item.json.message?.chat?.id || '';\\n const preguntaLimpia = limpiarTexto(preguntaUsuario);\\n\\n // ===== PALABRAS CLAVE DE CALENDARIO =====\\n const palabrasClaveCalendario = {\\n eventos: [\\n 'matricula', 'matriculas', 'matriculacion',\\n 'inicio de clases', 'fin de clases', 'clases',\\n 'primer termino', 'segundo termino', 'tercer termino',\\n 'examenes', 'examen', 'prueba', 'pruebas',\\n 'evaluaciones', 'evaluacion',\\n 'suspension', 'feriado', 'feriados',\\n 'vacaciones', 'receso',\\n 'cambio de carrera', 'cambio de materia',\\n 'retiro', 'retiros',\\n 'solicitudes', 'solicitud',\\n 'inscripciones', 'inscripcion',\\n 'graduacion', 'grado',\\n 'titulacion',\\n 'becas', 'beca',\\n 'nivelacion'\\n ],\\n \\n tiempo: [\\n 'cuando', 'fecha', 'fechas', 'dia', 'dias',\\n 'plazo', 'plazos', 'periodo', 'periodos',\\n 'termino', 'terminos', 'semestre', 'año',\\n 'inicio', 'fin', 'cierre', 'apertura',\\n 'hasta cuando', 'desde cuando',\\n 'calendario', 'cronograma',\\n 'horario', 'horarios',\\n 'proxima', 'proximo', 'siguiente'\\n ],\\n \\n terminos: [\\n '2024-2025', '2025-2026',\\n 'PAO', 'PAOI', 'PAOII', 'IPAO', 'IIPAO', 'PAO1', 'PAO2',\\n 'primer', 'segundo', 'tercer',\\n 'trimestre', 'bimestre', 'semestral'\\n ]\\n };\\n\\n // Combinar todas las palabras clave\\n const todasLasPalabrasClave = [\\n ...palabrasClaveCalendario.eventos,\\n ...palabrasClaveCalendario.tiempo,\\n ...palabrasClaveCalendario.terminos\\n ];\\n\\n // ===== DETECCIÓN =====\\n let palabrasEncontradas = [];\\n let puntuacion = 0;\\n\\n for (const palabra of todasLasPalabrasClave) {\\n if (preguntaLimpia.includes(palabra)) {\\n palabrasEncontradas.push(palabra);\\n if (palabrasClaveCalendario.eventos.includes(palabra)) {\\n puntuacion += 2;\\n } else {\\n puntuacion += 1;\\n }\\n }\\n }\\n\\n // Decisión: ¿Es consulta de calendario?\\n const esConsultaCalendario = puntuacion >= 2 || palabrasEncontradas.length >= 2;\\n\\n // LOGS\\n console.log(`========================================`);\\n console.log(`🔍 DETECTOR PRE-LECTURA DE CALENDARIO`);\\n console.log(`Pregunta: \\\"${preguntaUsuario}\\\"`);\\n console.log(`Palabras encontradas: ${palabrasEncontradas.join(', ') || 'ninguna'}`);\\n console.log(`Puntuación: ${puntuacion}`);\\n console.log(`¿Es calendario? ${esConsultaCalendario ? '✅ SÍ' : '❌ NO'}`);\\n console.log(`${esConsultaCalendario ? '→ Irá a BD_Calendario' : '→ Irá a FAQs (flujo normal)'}`);\\n console.log(`========================================`);\\n\\n resultados.push({\\n json: {\\n pregunta_usuario: preguntaUsuario,\\n chat_id: chatId,\\n es_consulta_calendario: esConsultaCalendario,\\n palabras_encontradas: palabrasEncontradas,\\n puntuacion: puntuacion\\n }\\n });\\n}\\n\\nreturn resultados;\"},\"typeVersion\":2},{\"id\":\"81ea9f6c-121c-4bc5-99e4-e947dae8bf7a\",\"name\":\"Mensaje de Gemini\",\"type\":\"@n8n/n8n-nodes-langchain.googleGemini\",\"position\":[-800,2448],\"parameters\":{\"modelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"models/gemini-2.5-flash-lite-preview-06-17\",\"cachedResultName\":\"models/gemini-2.5-flash-lite-preview-06-17\"},\"options\":{\"temperature\":0.3,\"maxOutputTokens\":2000},\"messages\":{\"values\":[{\"content\":\"={{ $json.prompt }}\"}]},\"simplify\":false},\"typeVersion\":1,\"alwaysOutputData\":false},{\"id\":\"8116c6c4-e4ca-4450-89ab-17df67b4b886\",\"name\":\"Enviar Respuesta sobre faqs\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-224,2448],\"webhookId\":\"0096bd46-0086-4c23-87a8-a63bfebca2d8\",\"parameters\":{\"text\":\"={{ $json.texto_limpio }}\\n\\n💬 ¿Deseas revisar otra consulta o hacer una nueva pregunta?\",\"chatId\":\"={{ $json.chat_id }}\",\"replyMarkup\":\"inlineKeyboard\",\"inlineKeyboard\":{\"rows\":[{\"row\":{\"buttons\":[{\"text\":\"👍 Sí\",\"additionalFields\":{\"callback_data\":\"=feedback_yes\"}},{\"text\":\"👎 No\",\"additionalFields\":{\"callback_data\":\"=feedback_no\"}}]}}]},\"additionalFields\":{\"parse_mode\":\"HTML\",\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"5f4eed47-a777-4d27-a80a-bcc145808f42\",\"name\":\"Guardado en cvs Feedback\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[-1264,1296],\"parameters\":{\"columns\":{\"value\":{\"id\":\"={{ $json.message.chat.id }}\",\"Nombre\":\"={{ $json.message.reply_to_message.chat.first_name }}\",\"Comentario\":\"={{ $json.message.text }}\"},\"schema\":[{\"id\":\"id\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"id\",\"defaultMatch\":true,\"canBeUsedToMatch\":true},{\"id\":\"Nombre\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"Nombre\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"Comentario\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"Comentario\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[\"id\"],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{},\"operation\":\"append\",\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gid=0\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1dcEsIPMMnjBtQ1YXy5Zc50OWwBVOcWXpxkJUJWZmE4E/edit#gid=0\",\"cachedResultName\":\"Sheet1\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1dcEsIPMMnjBtQ1YXy5Zc50OWwBVOcWXpxkJUJWZmE4E\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1dcEsIPMMnjBtQ1YXy5Zc50OWwBVOcWXpxkJUJWZmE4E/edit?usp=drivesdk\",\"cachedResultName\":\"Feedback\"}},\"typeVersion\":4.7},{\"id\":\"cdf6ad08-7f31-467e-9feb-9d3a8e1c9ba6\",\"name\":\"Construir_Prompt_Calendario1\",\"type\":\"n8n-nodes-base.code\",\"position\":[-1008,2160],\"parameters\":{\"jsCode\":\"const preguntaUsuario = $json.consulta || $json.pregunta_usuario || $json.pregunta || '';\\nconst chatId = $json.chat_id;\\n\\n// Preferir el nuevo esquema del buscador\\nlet eventos = Array.isArray($json.resultados) ? $json.resultados : [];\\n\\n// Compatibilidad con el arreglo antiguo { eventos_calendario: [...] }\\nif ((!eventos || eventos.length === 0) && Array.isArray($json.eventos_calendario)) {\\n eventos = $json.eventos_calendario.map((e) => ({\\n PERIODO_FECHAS: e.periodo || e.PERIODO_FECHAS || '',\\n ACTIVIDADES_GRADO: e.actividades_grado || e.ACTIVIDADES_GRADO || '',\\n PROCESOS_GRADO: e.procesos_grado || e.PROCESOS_GRADO || '',\\n ACTIVIDADES_FORMACION: e.actividades_formacion || e.ACTIVIDADES_FORMACION || '',\\n fecha_inicio_ts: e.fecha_inicio_ts ?? null,\\n score: e.score ?? null,\\n }));\\n}\\n\\n// Señal de “demasiadas coincidencias” y facetas sugeridas (si vienen del buscador)\\nconst demasiadas = Boolean($json.demasiadas_coincidencias);\\nconst filtros = $json.filtros_sugeridos || null;\\n\\n// === Funciones auxiliares ===\\nfunction safe(v) { return (v == null ? '' : String(v)); }\\n\\nfunction fmtFecha(ts) {\\n if (ts == null) return '';\\n try {\\n const d = new Date(Number(ts));\\n if (isNaN(d.getTime())) return '';\\n const dd = String(d.getDate()).padStart(2, '0');\\n const mm = String(d.getMonth() + 1).padStart(2, '0');\\n const yyyy = d.getFullYear();\\n return `${yyyy}-${mm}-${dd}`;\\n } catch { return ''; }\\n}\\n\\n// === Determinar PAO actual según la fecha del sistema ===\\nconst ahora = new Date();\\nconst mesActual = ahora.getMonth() + 1;\\nconst anioActual = ahora.getFullYear();\\n\\nlet paoActual = '';\\nif (mesActual >= 5 && mesActual <= 9) paoActual = 'PAO I';\\nelse if (mesActual >= 9 || mesActual <= 2) paoActual = 'PAO II';\\nelse paoActual = 'Vacaciones o PAE';\\n\\nconst contextoTiempo = `📆 Fecha actual: ${anioActual}-${String(mesActual).padStart(2, '0')} (${paoActual} en curso)`;\\n\\n// === Ordenar eventos por relevancia y fecha ===\\nconst eventosOrdenados = [...eventos].sort((a, b) => {\\n const sa = (a.score == null) ? -Infinity : Number(a.score);\\n const sb = (b.score == null) ? -Infinity : Number(b.score);\\n if (sb !== sa) return sb - sa;\\n\\n const ta = (a.fecha_inicio_ts == null) ? Number.POSITIVE_INFINITY : Number(a.fecha_inicio_ts);\\n const tb = (b.fecha_inicio_ts == null) ? Number.POSITIVE_INFINITY : Number(b.fecha_inicio_ts);\\n return ta - tb;\\n});\\n\\nlet contextoCalendario = '';\\n\\nif (eventosOrdenados.length > 0) {\\n contextoCalendario = '📅 He encontrado estas coincidencias (ordenadas por relevancia):\\\\n\\\\n';\\n\\n // Mostrar solo el top 10\\n const toShow = eventosOrdenados.slice(0, 10);\\n\\n contextoCalendario += toShow.map((ev, idx) => {\\n const periodo = safe(ev.PERIODO_FECHAS || ev.periodo);\\n const ag = safe(ev.ACTIVIDADES_GRADO || ev.actividades_grado);\\n const pg = safe(ev.PROCESOS_GRADO || ev.procesos_grado);\\n const af = safe(ev.ACTIVIDADES_FORMACION || ev.actividades_formacion);\\n const fechaISO = fmtFecha(ev.fecha_inicio_ts);\\n const score = (ev.score != null) ? Number(ev.score).toFixed(3) : '';\\n\\n let info = `${idx + 1}. 📌 ${periodo || '(sin fecha)'}`;\\n if (fechaISO) info += `\\\\n 🗓️ Inicio (estimado): ${fechaISO}`;\\n if (ag.trim()) info += `\\\\n 🎓 Actividades de Grado: ${ag}`;\\n if (pg.trim()) info += `\\\\n 📋 Procesos: ${pg}`;\\n if (af.trim()) info += `\\\\n 🔧 Formación Técnica: ${af}`;\\n if (score) info += `\\\\n 🔎 score:${score}`;\\n return info;\\n }).join('\\\\n\\\\n');\\n\\n // Sugerencias si hay demasiadas coincidencias\\n if (demasiadas) {\\n const tips = [];\\n if (filtros?.posibles_anios?.length) tips.push(`• especifica año: ${filtros.posibles_anios.slice(-3).join(' / ')}`);\\n if (filtros?.posibles_meses?.length) tips.push(`• añade mes: ${filtros.posibles_meses.slice(0, 4).join(' / ')}`);\\n if (filtros?.posibles_tipos_evaluacion?.length) tips.push(`• tipo de evaluación: ${filtros.posibles_tipos_evaluacion.join(' / ')}`);\\n if (filtros?.posibles_ciclos?.length) tips.push(`• ciclo: ${filtros.posibles_ciclos.join(' / ')}`);\\n\\n if (tips.length) {\\n contextoCalendario += '\\\\n\\\\n⚠️ Hay muchas coincidencias. Sugerencias para refinar:\\\\n' + tips.join('\\\\n');\\n }\\n }\\n\\n} else {\\n contextoCalendario = 'No encontré información específica en el calendario académico para tu consulta.';\\n}\\n\\n// === Reglas de interpretación PAO/PAE ===\\nconst reglasPAO = `\\nREGLAS DE INTERPRETACIÓN (PAO/PAE y feriados):\\n• Si un evento dice “vacaciones” y la fecha cae ENTRE finales de febrero y los primeros días de mayo ⇒ corresponde a VACACIONES del PAO II.\\n• Desde inicios de mayo hasta inicios/mediados de septiembre ⇒ corresponde a PAO I.\\n• Si un evento cae entre finales de septiembre y la 1.ª o 2.ª semana de febrero ⇒ corresponde a PAO II (período lectivo).\\n• En PAO II, si aparecen “vacaciones estudiantiles” del 28 de diciembre al 1 de enero ⇒ son feriado (no vacaciones entre PAOs).\\n• PAE (Programa de Acompañamiento/Evaluación) ocurre normalmente desde inicios de marzo hasta finales de abril o inicios de mayo.\\n• Si dentro de un PAO aparece “vacaciones”, interprétalas como feriados específicos, no como cambio de PAO.\\n• Si el evento no indica explícitamente PAO I o II, infiérelo con estas reglas. Si hay ambigüedad o la fecha cae fuera de rango, indica que no hay información específica.\\n`.trim();\\n\\n// === Construcción final del prompt ===\\nconst prompt = `Eres un asistente de ESPOL especializado en calendario académico.\\n\\n${contextoTiempo}\\n\\nPregunta del estudiante:\\n\\\"${preguntaUsuario}\\\"\\n\\n${contextoCalendario}\\n\\n${reglasPAO}\\n\\nINSTRUCCIONES IMPORTANTES (ESTRICTAS):\\n1) Si existe la lista anterior, elige SOLO 1 evento que sea la MEJOR COINCIDENCIA para la pregunta.\\n • Considera intención (evaluación/vacaciones/inicio/fin), ordinal (primera/segunda/tercera),\\n y año/mes implícitos o explícitos.\\n • Si ningún evento es claramente pertinente, responde que NO hay información específica.\\n2) No inventes datos. No cites eventos que no estén arriba.\\n3) Si das un resultado, preséntalo claro y breve con emojis, destacando FECHA y ACTIVIDAD.\\n4) Si NO hay información específica, sugiere contactar a:\\n 📧 Email: admision@espol.edu.ec\\n 📞 Teléfono: (04) 2269-269\\n 🌐 Web: https://www.espol.edu.ec\\n5) Si identificas el PAO (I o II) por las fechas, indícalo entre paréntesis o nota breve (“según fechas corresponde al PAO I/II”).\\n6) Responde de forma clara, organizada y útil.`;\\n\\n// === Salida para el siguiente nodo (Gemini) ===\\nreturn [{\\n json: {\\n prompt,\\n chat_id: chatId\\n }\\n}];\\n\"},\"typeVersion\":2},{\"id\":\"728f012c-ceed-400d-a643-8f1353d9f8f1\",\"name\":\"Message a model1\",\"type\":\"@n8n/n8n-nodes-langchain.googleGemini\",\"position\":[-800,2160],\"parameters\":{\"modelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"models/gemini-2.5-flash-preview-05-20\",\"cachedResultName\":\"models/gemini-2.5-flash-preview-05-20\"},\"options\":{\"temperature\":0.3,\"maxOutputTokens\":200000000},\"messages\":{\"values\":[{\"content\":\"={{ $json.prompt }}\"}]},\"simplify\":false},\"typeVersion\":1},{\"id\":\"4af01328-9345-4714-a79d-ea81b2a16a38\",\"name\":\"Limpiar_Texto_Gemini1\",\"type\":\"n8n-nodes-base.code\",\"position\":[-480,2160],\"parameters\":{\"jsCode\":\"// ---- 1) Extracción robusta del texto de Gemini ----\\nfunction extraerTextoGemini(payload) {\\n // Formato más común: candidates[0].content.parts[*].text\\n try {\\n const parts = payload?.candidates?.[0]?.content?.parts;\\n if (Array.isArray(parts) && parts.length > 0) {\\n // Concatenar todos los parts .text\\n const textos = parts\\n .map(p => (typeof p?.text === 'string' ? p.text : ''))\\n .filter(Boolean);\\n if (textos.length) return textos.join('\\\\n').trim();\\n }\\n } catch {}\\n\\n // Alternativos:\\n if (typeof payload?.text === 'string' && payload.text.trim()) {\\n return payload.text.trim();\\n }\\n\\n if (Array.isArray(payload?.content?.parts) && payload.content.parts.length > 0) {\\n const textos2 = payload.content.parts\\n .map(p => (typeof p?.text === 'string' ? p.text : ''))\\n .filter(Boolean);\\n if (textos2.length) return textos2.join('\\\\n').trim();\\n }\\n\\n // Último recurso: stringify recortado\\n try {\\n const s = JSON.stringify(payload);\\n if (s && s.length) return s.substring(0, 8000);\\n } catch {}\\n\\n return 'Lo siento, no pude procesar tu consulta.';\\n}\\n\\nconst respuestaGemini = extraerTextoGemini($json);\\n\\n// ---- 2) Recuperar chat_id desde varios nodos/ubicaciones ----\\nlet chatId = $json.chat_id;\\n\\nif (!chatId) {\\n // Tu prompt actual\\n try { chatId = $('Construir_Prompt_Calendario1').first()?.json?.chat_id; } catch {}\\n}\\nif (!chatId) {\\n // Nombre anterior\\n try { chatId = $('Construir_Prompt_Calendario').first()?.json?.chat_id; } catch {}\\n}\\nif (!chatId) {\\n try { chatId = $('Buscar_Eventos_Calendario').first()?.json?.chat_id; } catch {}\\n}\\nif (!chatId) {\\n try { chatId = $('Detector_Calendario_Pre').first()?.json?.chat_id; } catch {}\\n}\\nif (!chatId) {\\n // Telegram Trigger\\n try { chatId = $('Telegram Trigger - Inicio').first()?.json?.message?.chat?.id; } catch {}\\n}\\n\\n// ---- 3) Limpieza / saneamiento para enviar por Telegram con parse_mode HTML ----\\nfunction escapeHTML(s) {\\n // Evita que Telegram interprete etiquetas si usas parse_mode: \\\"HTML\\\"\\n return s.replace(/&/g, '&')\\n .replace(//g, '>');\\n}\\n\\nfunction limpiarRespuesta(texto) {\\n if (!texto) return 'Lo siento, no obtuve una respuesta válida.';\\n\\n // Eliminar bloques de código ```...``` (incluye variantes con lenguaje)\\n texto = texto.replace(/```[\\\\s\\\\S]*?```/g, '');\\n\\n // Eliminar comillas invertidas inline `\\n texto = texto.replace(/`+/g, '');\\n\\n // Convertir enlaces markdown [texto](url) → \\\"texto (url)\\\"\\n texto = texto.replace(/\\\\[([^\\\\]]+)\\\\]\\\\((https?:\\\\/\\\\/[^\\\\s)]+)\\\\)/g, '$1 ($2)');\\n\\n // Quitar markdown simple de estilo: **negritas**, *itálicas*, __subrayado__ _\\n texto = texto.replace(/\\\\*\\\\*(.*?)\\\\*\\\\*/g, '$1')\\n .replace(/\\\\*(.*?)\\\\*/g, '$1')\\n .replace(/__(.*?)__/g, '$1')\\n .replace(/_(.*?)_/g, '$1');\\n\\n // Quitar encabezados markdown (##, ###, etc.)\\n texto = texto.replace(/^\\\\s{0,3}#{1,6}\\\\s+/gm, '');\\n\\n // Normalizar saltos y espacios\\n texto = texto.replace(/\\\\r/g, '')\\n .replace(/\\\\n{3,}/g, '\\\\n\\\\n')\\n .replace(/[ \\\\t]+\\\\n/g, '\\\\n')\\n .trim();\\n\\n // Escapar HTML para Telegram (parse_mode: \\\"HTML\\\")\\n texto = escapeHTML(texto);\\n\\n // Límite prudente para Telegram (4096 es el duro). Dejamos margen.\\n const LIMITE = 3500;\\n if (texto.length > LIMITE) {\\n texto = texto.substring(0, LIMITE - 20).trimEnd() + '… (mensaje acortado)';\\n }\\n\\n return texto;\\n}\\n\\nconst textoLimpio = limpiarRespuesta(respuestaGemini);\\n\\n// ---- 4) Logs útiles ----\\nconsole.log(`========================================`);\\nconsole.log(`🧹 LIMPIEZA DE TEXTO`);\\nconsole.log(`Chat ID encontrado: ${chatId}`);\\nconsole.log(`Texto original (100): ${String(respuestaGemini).substring(0, 100)}...`);\\nconsole.log(`Texto limpio (100): ${textoLimpio.substring(0, 100)}...`);\\nconsole.log(`========================================`);\\n\\n// ---- 5) Salida ----\\nreturn [{\\n json: {\\n texto_limpio: textoLimpio,\\n chat_id: chatId,\\n respuesta_original: respuestaGemini\\n }\\n}];\"},\"typeVersion\":2},{\"id\":\"84c7ffb2-d72d-432a-ac54-9892d31ac5b9\",\"name\":\"Enviar Respuesta sobre calendario1\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-240,2160],\"webhookId\":\"c4b9e9ad-3d55-4653-b1eb-e4621c6425d8\",\"parameters\":{\"text\":\"={{ $json.texto_limpio }}\\n\\n💬 ¿Deseas revisar otra consulta o hacer una nueva pregunta?\",\"chatId\":\"={{ $json.chat_id }}\",\"replyMarkup\":\"inlineKeyboard\",\"inlineKeyboard\":{\"rows\":[{\"row\":{\"buttons\":[{\"text\":\"👍 Sí\",\"additionalFields\":{\"callback_data\":\"=feedback_yes\"}},{\"text\":\"👎 No\",\"additionalFields\":{\"callback_data\":\"=feedback_no\"}}]}}]},\"additionalFields\":{\"parse_mode\":\"HTML\",\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"144e290f-5f0a-400b-b82b-269d90d5f32a\",\"name\":\"Calendario Académico\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[-1520,2160],\"parameters\":{\"options\":{\"outputFormatting\":{\"values\":{\"date\":\"FORMATTED_STRING\",\"general\":\"UNFORMATTED_VALUE\"}},\"returnFirstMatch\":false},\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":1817620056,\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit#gid=1817620056\",\"cachedResultName\":\"CALENDAR\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit?usp=drivesdk\",\"cachedResultName\":\"BASE-DATOS-FAQ_ESPOL\"}},\"typeVersion\":4.7},{\"id\":\"21267be1-e42b-4362-aefc-42bf96705258\",\"name\":\"Buscar_Eventos_Calendario1\",\"type\":\"n8n-nodes-base.code\",\"position\":[-1264,2160],\"parameters\":{\"jsCode\":\"const detectorItems = $('Detector_Calendario_Pre').all();\\nconst detector =\\n Array.isArray(detectorItems) && detectorItems.length > 0\\n ? detectorItems[0].json\\n : {};\\nconst preguntaUsuario = detector.pregunta_usuario || '';\\nconst chatId = detector.chat_id ?? null;\\nconst filas = $input.all().map(it => it.json || {});\\n\\nconst HOY = new Date();\\nconst ANIO_ACTUAL = HOY.getFullYear();\\nconst ANIO_SIG = ANIO_ACTUAL + 1;\\n\\n// ---------- helpers ----------\\nfunction limpiarTexto(t) {\\n if (!t) return '';\\n return String(t)\\n .toLowerCase()\\n .normalize('NFD').replace(/[\\\\u0300-\\\\u036f]/g, '')\\n .replace(/[^a-z0-9ñ\\\\s]/gi, ' ')\\n .replace(/\\\\s+/g, ' ')\\n .trim();\\n}\\n\\nconst STOP = new Set([\\n \\\"de\\\",\\\"la\\\",\\\"que\\\",\\\"el\\\",\\\"en\\\",\\\"y\\\",\\\"a\\\",\\\"los\\\",\\\"del\\\",\\\"se\\\",\\\"las\\\",\\\"por\\\",\\\"un\\\",\\\"para\\\",\\\"con\\\",\\\"no\\\",\\\"una\\\",\\n \\\"su\\\",\\\"al\\\",\\\"lo\\\",\\\"como\\\",\\\"mas\\\",\\\"más\\\",\\\"pero\\\",\\\"sus\\\",\\\"le\\\",\\\"ya\\\",\\\"o\\\",\\\"fue\\\",\\\"ha\\\",\\\"si\\\",\\\"sí\\\",\\\"porque\\\",\\n \\\"muy\\\",\\\"sin\\\",\\\"sobre\\\",\\\"tambien\\\",\\\"también\\\",\\\"entre\\\",\\\"cuando\\\",\\\"todo\\\",\\\"esta\\\",\\\"está\\\",\\\"ser\\\",\\\"son\\\",\\n \\\"dos\\\",\\\"han\\\",\\\"hay\\\",\\\"donde\\\",\\\"quien\\\",\\\"quién\\\",\\\"desde\\\",\\\"cada\\\",\\\"cual\\\",\\\"cuál\\\",\\\"cuales\\\",\\\"cuáles\\\"\\n]);\\nfunction tokenizar(t) { return limpiarTexto(t).split(' ').filter(x => x && x.length > 2 && !STOP.has(x)); }\\n\\nfunction baseEs(w) {\\n w = limpiarTexto(w);\\n if (!w) return '';\\n w = w.replace(/\\\\b1(ra|era)\\\\b/g, 'primera')\\n .replace(/\\\\b2da\\\\b/g, 'segunda')\\n .replace(/\\\\b3ra\\\\b/g, 'tercera');\\n if (w.endsWith('es')) w = w.slice(0, -2);\\n else if (w.endsWith('s')) w = w.slice(0, -1);\\n w = w.replace(/evaluacione?$/,'evaluacion');\\n return w;\\n}\\nfunction matchToken(userTok, rowTok) {\\n const u = baseEs(userTok), r = baseEs(rowTok);\\n if (!u || !r) return false;\\n if (u === r) return true;\\n if (u.length >= 5 && (r.includes(u) || u.includes(r))) return true;\\n return false;\\n}\\n\\nfunction detectarIntencion(pregunta) {\\n const p = limpiarTexto(pregunta);\\n if (/(vacaciones|receso|feriado|descanso)/.test(p)) return \\\"vacaciones\\\";\\n if (/(evaluacion|evaluación|examen|parcial|prueba|evaluar|evaluaciones)/.test(p)) return \\\"evaluacion\\\";\\n if (/(inicio|empieza|matriculacion|matriculación|induccion|inducción|apertura|arranque)/.test(p)) return \\\"inicio\\\";\\n if (/(final|fin|cierre|termina|culmina|conclusion|conclusión)/.test(p)) return \\\"fin\\\";\\n if (/(eleccion|elección|votacion|votación)/.test(p)) return \\\"elecciones\\\";\\n return \\\"otro\\\";\\n}\\nfunction detectarOrdinal(p) {\\n const t = limpiarTexto(p);\\n if (/\\\\b(primera|1ra|1era)\\\\b/.test(t) || /\\\\bevaluacion\\\\s*i\\\\b/.test(t)) return 1;\\n if (/\\\\b(segunda|2da)\\\\b/.test(t) || /\\\\bevaluacion\\\\s*ii\\\\b/.test(t)) return 2;\\n if (/\\\\b(tercera|3ra)\\\\b/.test(t) || /\\\\bevaluacion\\\\s*iii\\\\b/.test(t)) return 3;\\n return 0;\\n}\\n\\nconst MESES = { ene:0, enero:0, feb:1, febrero:1, mar:2, marzo:2, abr:3, abril:3, may:4, mayo:4, jun:5, junio:5, jul:6, julio:6, ago:7, agosto:7, sep:8, sept:8, septiembre:8, oct:9, octubre:9, nov:10, noviembre:10, dic:11, diciembre:11 };\\n\\nfunction normalizarPeriodo(p) {\\n if (!p) return '';\\n return String(p).replace(/([0-9])([a-zA-Z])/g, '$1 $2').replace(/\\\\s*-\\\\s*/g, ' - ').replace(/\\\\s+/g, ' ').trim();\\n}\\nfunction parseFechaInicio(periodo) {\\n const txt = normalizarPeriodo(periodo).toLowerCase();\\n\\n // \\\"13 - 17 julio 2026\\\"\\n let m = /(\\\\d{1,2})\\\\s*-\\\\s*(\\\\d{1,2})\\\\s+([a-záéíóúñ]+)\\\\s+(\\\\d{4})/.exec(txt);\\n if (m) {\\n const d1 = parseInt(m[1], 10);\\n const mes = MESES[m[3].normalize('NFD').replace(/[\\\\u0300-\\\\u036f]/g, '')];\\n const year = parseInt(m[4], 10);\\n if (mes != null) return new Date(year, mes, d1, 0, 0, 0, 0).getTime();\\n }\\n\\n // \\\"30 marzo - 03 abril 2026\\\"\\n m = /(\\\\d{1,2})\\\\s+([a-záéíóúñ]+)\\\\s*-\\\\s*(\\\\d{1,2})\\\\s+([a-záéíóúñ]+)\\\\s+(\\\\d{4})/.exec(txt);\\n if (m) {\\n const d1 = parseInt(m[1], 10);\\n const mes1 = MESES[m[2].normalize('NFD').replace(/[\\\\u0300-\\\\u036f]/g, '')];\\n const year = parseInt(m[5], 10);\\n if (mes1 != null) return new Date(year, mes1, d1, 0, 0, 0, 0).getTime();\\n }\\n\\n // sin año → asume actual\\n m = /(\\\\d{1,2})\\\\s*-\\\\s*(\\\\d{1,2})\\\\s+([a-záéíóúñ]+)/.exec(txt);\\n if (m) {\\n const d1 = parseInt(m[1], 10);\\n const mes1 = MESES[m[3].normalize('NFD').replace(/[\\\\u0300-\\\\u036f]/g, '')];\\n if (mes1 != null) return new Date(ANIO_ACTUAL, mes1, d1, 0, 0, 0, 0).getTime();\\n }\\n m = /(\\\\d{1,2})\\\\s+([a-záéíóúñ]+)\\\\s*-\\\\s*(\\\\d{1,2})\\\\s+([a-záéíóúñ]+)/.exec(txt);\\n if (m) {\\n const d1 = parseInt(m[1], 10);\\n const mes1 = MESES[m[2].normalize('NFD').replace(/[\\\\u0300-\\\\u036f]/g, '')];\\n if (mes1 != null) return new Date(ANIO_ACTUAL, mes1, d1, 0, 0, 0, 0).getTime();\\n }\\n return null;\\n}\\nfunction extraerAniosTexto(texto) {\\n const t = String(texto || '');\\n const m = t.match(/\\\\b(20\\\\d{2})\\\\b/g);\\n if (!m) return new Set();\\n return new Set(m.map(x => parseInt(x, 10)));\\n}\\nfunction extraerAniosPregunta(p) { return extraerAniosTexto(p); }\\nfunction extraerMesesPregunta(p) {\\n const t = limpiarTexto(p);\\n const meses = new Set();\\n Object.keys(MESES).forEach(k => { if (new RegExp(`\\\\\\\\b${k}\\\\\\\\b`).test(t)) meses.add(MESES[k]); });\\n return meses;\\n}\\nfunction yearFromTs(ts) { if (ts == null) return null; try { return new Date(ts).getFullYear(); } catch { return null; } }\\n\\nconst intencion = detectarIntencion(preguntaUsuario);\\nconst ordinalBuscado = detectarOrdinal(preguntaUsuario);\\nconst tokensUsuario = tokenizar(preguntaUsuario);\\nconst setTokens = new Set(tokensUsuario);\\nconst aniosPregunta = extraerAniosPregunta(preguntaUsuario);\\nconst mesesPregunta = extraerMesesPregunta(preguntaUsuario);\\nconst HARD_FILTER_BY_YEAR = aniosPregunta.size > 0;\\n\\n// ---------- scoring ----------\\nconst PESOS = { PERIODO_FECHAS: 0.8, ACTIVIDADES_GRADO: 1.0, PROCESOS_GRADO: 0.6, ACTIVIDADES_FORMACION: 0.9 };\\nconst BONUS_INTENCION = 2.2;\\nconst BONUS_FRASE_EXACTA = 1.0;\\nconst BONUS_TIENE_EVALUACION = 0.7;\\nconst BONUS_ORDINAL_MATCH = 1.5;\\nconst PENALIZA_ORD_DISTINTO = 0.5;\\nconst PENALIZA_SIN_EVAL_CON_ORD = 0.35;\\n\\nconst BONUS_ANIO_ACTUAL_STRONG = 1.1;\\nconst PENALIZA_ANIO_NO_ACTUAL = 0.6;\\nconst BONUS_MATCH_ANIO_PREGUNTA = 1.2;\\nconst BONUS_MATCH_MES_ACTUAL = 0.6;\\nconst BONUS_ANIO_EXPLICITO = 0.3;\\n\\nconst UMBRAL_SCORE_MIN = 0;\\nconst UMBRAL_DEMASIADAS = 25; // ← si hay más que esto, sugerimos refinar\\n\\nif (!preguntaUsuario || !limpiarTexto(preguntaUsuario)) {\\n return [{ json: { ok:false, motivo:\\\"pregunta_vacia\\\", mensaje:\\\"No se recibió una pregunta (pregunta_usuario).\\\", chat_id:chatId } }];\\n}\\nif (!Array.isArray(filas) || filas.length === 0) {\\n return [{ json: { ok:false, motivo:\\\"sin_datos\\\", mensaje:\\\"No llegaron filas desde Google Sheets.\\\", chat_id:chatId } }];\\n}\\n\\nfunction filaTokens(row) {\\n const F = (k) => { const v = row[k]; return (v == null) ? '' : String(v); };\\n const actTecKey = 'ACTIVIDADES DE FORMACIÓN TÉCNICA Y TECNOLÓGICA';\\n const campos = {\\n row_number: row.row_number ?? null,\\n PERIODO_FECHAS: F('PERIODO_FECHAS'),\\n ACTIVIDADES_GRADO: F('ACTIVIDADES_GRADO'),\\n PROCESOS_GRADO: F('PROCESOS_GRADO'),\\n ACTIVIDADES_FORMACION: F(actTecKey) || F('ACTIVIDADES_FORMACION') || ''\\n };\\n const textoTotal = [campos.PERIODO_FECHAS, campos.ACTIVIDADES_GRADO, campos.PROCESOS_GRADO, campos.ACTIVIDADES_FORMACION].filter(Boolean).join(' | ');\\n const normTotal = limpiarTexto(textoTotal);\\n const toks = {\\n PERIODO_FECHAS: tokenizar(campos.PERIODO_FECHAS),\\n ACTIVIDADES_GRADO: tokenizar(campos.ACTIVIDADES_GRADO),\\n PROCESOS_GRADO: tokenizar(campos.PROCESOS_GRADO),\\n ACTIVIDADES_FORMACION: tokenizar(campos.ACTIVIDADES_FORMACION),\\n TOTAL: tokenizar(textoTotal)\\n };\\n const aniosTexto = extraerAniosTexto(textoTotal);\\n const tsInicio = parseFechaInicio(campos.PERIODO_FECHAS);\\n const anioTs = yearFromTs(tsInicio);\\n const aniosFila = new Set(aniosTexto);\\n if (anioTs != null) aniosFila.add(anioTs);\\n let mesInicio = null;\\n if (tsInicio != null) mesInicio = new Date(tsInicio).getMonth();\\n\\n return { campos, textoTotal, normTotal, toks, aniosFila, tsInicio, mesInicio };\\n}\\nfunction filaTieneOrdinalEvaluacion(norm) {\\n const hasEval = /\\\\bevaluacion\\\\b/.test(norm);\\n const primera = hasEval && (/\\\\bprimera\\\\b/.test(norm) || /\\\\bevaluacion\\\\s*i\\\\b/.test(norm) || /\\\\bi\\\\s*evaluacion\\\\b/.test(norm));\\n const segunda = hasEval && (/\\\\bsegunda\\\\b/.test(norm) || /\\\\bevaluacion\\\\s*ii\\\\b/.test(norm) || /\\\\bii\\\\s*evaluacion\\\\b/.test(norm));\\n const tercera = hasEval && (/\\\\btercera\\\\b/.test(norm) || /\\\\bevaluacion\\\\s*iii\\\\b/.test(norm) || /\\\\biii\\\\s*evaluacion\\\\b/.test(norm));\\n return { hasEval, primera, segunda, tercera };\\n}\\nfunction intersect(setA, setB) { for (const x of setA) if (setB.has(x)) return true; return false; }\\n\\nfunction puntuar(row) {\\n const { campos, textoTotal, normTotal, toks, aniosFila, tsInicio, mesInicio } = filaTokens(row);\\n if (!normTotal) return null;\\n\\n if (HARD_FILTER_BY_YEAR) {\\n if (aniosFila.size > 0 && !intersect(aniosFila, aniosPregunta)) return null;\\n // si no hay año en la fila, la dejamos pasar con score bajo (puedes excluirla retornando null)\\n }\\n\\n let score = 0, coincidencias = 0;\\n const matchPorCampo = { PERIODO_FECHAS: [], ACTIVIDADES_GRADO: [], PROCESOS_GRADO: [], ACTIVIDADES_FORMACION: [] };\\n const matchTokens = [];\\n\\n for (const t of setTokens) {\\n let hit = false;\\n for (const campo of Object.keys(PESOS)) {\\n const arr = toks[campo];\\n if (arr && arr.some(rt => matchToken(t, rt))) {\\n score += PESOS[campo];\\n matchPorCampo[campo].push(t);\\n hit = true;\\n }\\n }\\n if (hit) { coincidencias++; matchTokens.push(t); }\\n }\\n\\n const INTENT_TERMS = {\\n vacaciones: [\\\"vacaciones\\\",\\\"receso\\\",\\\"feriado\\\",\\\"descanso\\\",\\\"estudiantiles\\\"],\\n evaluacion: [\\\"evaluacion\\\",\\\"evaluaciones\\\",\\\"examen\\\",\\\"parcial\\\",\\\"prueba\\\",\\\"ciclo\\\",\\\"semana de evaluacion\\\"],\\n inicio: [\\\"inicio\\\",\\\"empieza\\\",\\\"apertura\\\",\\\"induccion\\\",\\\"matriculacion\\\",\\\"novatos\\\"],\\n fin: [\\\"final\\\",\\\"fin\\\",\\\"cierre\\\",\\\"termina\\\",\\\"culmina\\\",\\\"conclusion\\\",\\\"proceso final\\\"],\\n elecciones: [\\\"eleccion\\\",\\\"votacion\\\"]\\n };\\n if (intencion !== 'otro') {\\n const terms = INTENT_TERMS[intencion] || [];\\n if (terms.some(term => normTotal.includes(limpiarTexto(term)))) score += BONUS_INTENCION;\\n }\\n\\n const ord = filaTieneOrdinalEvaluacion(normTotal);\\n if (intencion === 'evaluacion' && ord.hasEval) score += BONUS_TIENE_EVALUACION;\\n if (ordinalBuscado) {\\n const ok = (ordinalBuscado === 1 && ord.primera) || (ordinalBuscado === 2 && ord.segunda) || (ordinalBuscado === 3 && ord.tercera);\\n if (ok) score += BONUS_ORDINAL_MATCH;\\n else {\\n if (ord.primera || ord.segunda || ord.tercera) score -= PENALIZA_ORD_DISTINTO;\\n if (!ord.hasEval) score -= PENALIZA_SIN_EVAL_CON_ORD;\\n }\\n }\\n\\n if (HARD_FILTER_BY_YEAR) {\\n if (aniosFila.size > 0 && intersect(aniosFila, aniosPregunta)) score += BONUS_MATCH_ANIO_PREGUNTA;\\n } else {\\n if (aniosFila.size > 0) {\\n if (aniosFila.has(ANIO_ACTUAL)) score += BONUS_ANIO_ACTUAL_STRONG;\\n else score -= PENALIZA_ANIO_NO_ACTUAL;\\n }\\n }\\n\\n if (mesesPregunta.size > 0 && mesInicio != null) {\\n if (mesesPregunta.has(mesInicio)) {\\n if (!HARD_FILTER_BY_YEAR && (aniosFila.size === 0 || aniosFila.has(ANIO_ACTUAL))) score += BONUS_MATCH_MES_ACTUAL;\\n else score += BONUS_MATCH_MES_ACTUAL * 0.6;\\n }\\n }\\n\\n if (/\\\\b20\\\\d{2}\\\\b/.test(normTotal)) score += BONUS_ANIO_EXPLICITO;\\n\\n const frase = limpiarTexto(preguntaUsuario);\\n if (frase && normTotal.includes(frase)) score += BONUS_FRASE_EXACTA;\\n\\n const len = normTotal.split(' ').length || 1;\\n score = score / Math.pow(len, 0.03);\\n\\n return {\\n row_number: campos.row_number,\\n PERIODO_FECHAS: campos.PERIODO_FECHAS,\\n ACTIVIDADES_GRADO: campos.ACTIVIDADES_GRADO,\\n PROCESOS_GRADO: campos.PROCESOS_GRADO,\\n ACTIVIDADES_FORMACION: campos.ACTIVIDADES_FORMACION,\\n preview: textoTotal,\\n score: Number(score.toFixed(4)),\\n coincidencias,\\n match_tokens: matchTokens,\\n match_por_campo: matchPorCampo,\\n fecha_inicio_ts: tsInicio,\\n mes_inicio: mesInicio,\\n anios_fila: [...aniosFila]\\n };\\n}\\n\\n// ---------- ejecutar y ordenar ----------\\nconst evaluadas = [];\\nfor (const row of filas) {\\n const r = puntuar(row);\\n if (!r) continue;\\n if (r.score > UMBRAL_SCORE_MIN || r.coincidencias > 0) evaluadas.push(r);\\n}\\n\\nevaluadas.sort((a, b) => {\\n if (b.score !== a.score) return b.score - a.score;\\n if (b.coincidencias !== a.coincidencias) return b.coincidencias - a.coincidencias;\\n const ta = a.fecha_inicio_ts ?? Number.POSITIVE_INFINITY;\\n const tb = b.fecha_inicio_ts ?? Number.POSITIVE_INFINITY;\\n return ta - tb;\\n});\\n\\n// chat_ids válidos (si existen en la data)\\nconst chatIds = $input.all()\\n .map(it => it.json?.CHAT_ID)\\n .filter(id => id !== undefined && id !== null && String(id).trim() !== '')\\n .map(id => String(id).trim());\\nconst chat_ids_validos = [...new Set(chatIds)];\\n\\n// ---------- sin resultados ----------\\nif (evaluadas.length === 0) {\\n const sugerencias = { email: \\\"admision@espol.edu.ec\\\", telefono: \\\"(04) 2269-269\\\", web: \\\"https://www.espol.edu.ec\\\" };\\n const yearInfo = aniosPregunta.size > 0 ? ` para el/los año(s): ${[...aniosPregunta].join(', ')}` : ` para el año ${ANIO_ACTUAL}`;\\n const mensaje = [\\n `😕 No encontré información específica${yearInfo}.`,\\n \\\"Puedes comunicarte por:\\\",\\n `📧 ${sugerencias.email}`,\\n `📞 ${sugerencias.telefono}`,\\n `🌐 ${sugerencias.web}`\\n ].join('\\\\n');\\n\\n return [{ json: {\\n ok: false,\\n consulta: preguntaUsuario,\\n intencion_detectada: intencion,\\n mensaje,\\n sugerencias_contacto: sugerencias,\\n chat_id: chatId,\\n chat_ids_validos\\n }}];\\n}\\n\\n// ---------- construir sugerencias si hay demasiadas coincidencias ----------\\nfunction nombreMes(idx) {\\n const nombres = ['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre'];\\n return (idx >=0 && idx <=11) ? nombres[idx] : null;\\n}\\nfunction recolectarFacetas(rows) {\\n const anios = new Set();\\n const meses = new Set();\\n const tiposEval = new Set(); // primera/segunda/tercera\\n const ciclos = new Set(); // Ciclo 1/2/3\\n\\n for (const r of rows) {\\n (r.anios_fila || []).forEach(y => anios.add(y));\\n if (typeof r.mes_inicio === 'number') meses.add(r.mes_inicio);\\n\\n const norm = limpiarTexto(`${r.PERIODO_FECHAS} ${r.ACTIVIDADES_GRADO} ${r.PROCESOS_GRADO} ${r.ACTIVIDADES_FORMACION}`);\\n if (/\\\\bprimera\\\\b/.test(norm) || /\\\\bevaluacion\\\\s*i\\\\b/.test(norm)) tiposEval.add('primera');\\n if (/\\\\bsegunda\\\\b/.test(norm) || /\\\\bevaluacion\\\\s*ii\\\\b/.test(norm)) tiposEval.add('segunda');\\n if (/\\\\btercera\\\\b/.test(norm) || /\\\\bevaluacion\\\\s*iii\\\\b/.test(norm)) tiposEval.add('tercera');\\n\\n const m = norm.match(/\\\\bciclo\\\\s*(1|2|3)\\\\b/);\\n if (m) ciclos.add(`Ciclo ${m[1]}`);\\n }\\n\\n return {\\n anios: [...anios].sort((a,b)=>a-b),\\n meses: [...meses].sort((a,b)=>a-b).map(nombreMes).filter(Boolean),\\n tiposEval: [...tiposEval],\\n ciclos: [...ciclos]\\n };\\n}\\n\\nlet sugerencia_reformulacion = null;\\nlet filtros_sugeridos = null;\\nconst DEMASIADAS = evaluadas.length > UMBRAL_DEMASIADAS;\\n\\nif (DEMASIADAS) {\\n const facetas = recolectarFacetas(evaluadas);\\n filtros_sugeridos = {\\n posibles_anios: facetas.anios,\\n posibles_meses: facetas.meses,\\n posibles_tipos_evaluacion: facetas.tiposEval,\\n posibles_ciclos: facetas.ciclos\\n };\\n\\n const tips = [];\\n if (facetas.anios.length > 0) tips.push(`• especifica año: **${facetas.anios.slice(-3).join(' / ')}**`);\\n if (facetas.meses.length > 0) tips.push(`• añade mes: **${facetas.meses.slice(0,4).join(' / ')}**`);\\n if (facetas.tiposEval.length > 0) tips.push(`• tipo de evaluación: **${facetas.tiposEval.join(' / ')}**`);\\n if (facetas.ciclos.length > 0) tips.push(`• ciclo: **${facetas.ciclos.join(' / ')}**`);\\n\\n // ejemplo guiado\\n const ejemplo = [];\\n if (intencion === 'evaluacion') {\\n const ejA = facetas.anios[0] ?? ANIO_ACTUAL;\\n const ejMes = facetas.meses[0] ?? 'julio';\\n ejemplo.push(`Ej.: \\\"¿Cuándo es la **primera evaluación** de **${ejMes} ${ejA}** en PAE?\\\"`);\\n } else if (facetas.meses.length > 0 || facetas.anios.length > 0) {\\n const ejA = facetas.anios[0] ?? ANIO_ACTUAL;\\n const ejMes = facetas.meses[0] ?? 'abril';\\n ejemplo.push(`Ej.: \\\"Actividades formativas de **${ejMes} ${ejA}**\\\"`);\\n }\\n\\n sugerencia_reformulacion =\\n `🔎 He encontrado **${evaluadas.length}** coincidencias. ` +\\n `Para llegar más rápido a lo que necesitas, prueba a refinar tu pregunta:\\\\n` +\\n (tips.length ? tips.join('\\\\n') + '\\\\n' : '') +\\n (ejemplo.length ? ejemplo.join('\\\\n') : '');\\n}\\n\\n// ---------- mensaje formateado (todas las coincidencias) ----------\\nconst encabezado = `📅 Encontré ${evaluadas.length} coincidencia(s) para:\\\\n“${preguntaUsuario}”`;\\nconst cuerpo = evaluadas.map((e, i) => {\\n const partes = [];\\n partes.push(`${i+1}. 📌 ${e.PERIODO_FECHAS || '(sin fecha)'}`);\\n if (e.ACTIVIDADES_GRADO?.trim()) partes.push(` 🎓 Actividades de Grado: ${e.ACTIVIDADES_GRADO}`);\\n if (e.PROCESOS_GRADO?.trim()) partes.push(` 📋 Procesos: ${e.PROCESOS_GRADO}`);\\n if (e.ACTIVIDADES_FORMACION?.trim()) partes.push(` 🔧 Formación Técnica: ${e.ACTIVIDADES_FORMACION}`);\\n return partes.join('\\\\n');\\n}).join('\\\\n\\\\n');\\n\\nconst mensaje_formateado = sugerencia_reformulacion\\n ? `${encabezado}\\\\n\\\\n${cuerpo}\\\\n\\\\n${sugerencia_reformulacion}`\\n : `${encabezado}\\\\n\\\\n${cuerpo}`;\\n\\nreturn [{\\n json: {\\n ok: true,\\n consulta: preguntaUsuario,\\n intencion_detectada: intencion,\\n ordinal_detectado: detectarOrdinal(preguntaUsuario) || null,\\n anios_detectados_en_pregunta: [...aniosPregunta],\\n meses_detectados_en_pregunta: [...mesesPregunta],\\n total_evaluadas: filas.length,\\n total_encontrados: evaluadas.length,\\n demasiadas_coincidencias: DEMASIADAS,\\n umbral_demasiadas: UMBRAL_DEMASIADAS,\\n filtros_sugeridos, // ← facetas para construir botones/quick-replies si quieres\\n resultados: evaluadas, // ← TODAS las coincidencias ordenadas\\n mensaje_formateado,\\n chat_id: chatId,\\n chat_ids_validos: chat_ids_validos\\n }\\n}];\"},\"typeVersion\":2},{\"id\":\"2f04c332-95f8-4251-a7d8-c3183c3bf341\",\"name\":\"Mensaje Help\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-880,608],\"webhookId\":\"cec2b109-dbe4-4246-a86e-ab226fd460a7\",\"parameters\":{\"text\":\"=🤖 Bienvenido al ChatBot ESPOL\\n\\n👋 ¡Hola! Soy ChatBot ESPOL, tu asistente virtual de la Escuela Superior Politécnica del Litoral.\\nEstoy aquí para responder tus preguntas sobre la universidad: matrículas, eventos, horarios, docentes, servicios estudiantiles y mucho más.\\n\\n💬 Solo escribe tu duda y te responderé al instante.\\nPor ejemplo:\\n\\n“¿Cuándo empiezan las matrículas?”\\n“¿Qué eventos hay esta semana?”\\n“¿Dónde puedo contactar a Bienestar Estudiantil?”\\n\\nTambién puedes usar estos comandos:\\n\\n/help – Ver los comandos disponibles\\n\\n/faqs – Acceder a la sección de consultas y preguntas frecuentes\\n\\n/contact – Mostrar contactos y canales oficiales\\n\\n/events – Ver próximos eventos\\n\\n/feedback – Enviar sugerencias o comentarios sobre el bot o los servicios\\n\\n🎓 Tu información, siempre a un mensaje de distancia.\\n¿Sobre qué te gustaría consultar hoy?\",\"chatId\":\"={{ $json.message.chat.id }}\",\"additionalFields\":{\"parse_mode\":\"Markdown\",\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"58882226-f879-4ae5-b653-025ae55e833f\",\"name\":\"BIENVENIDA\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-880,1504],\"webhookId\":\"67736a18-8268-4b0b-a904-77b356cf3059\",\"parameters\":{\"text\":\"=👋🏽 ¡Qué más, politécnico o futuro politécnico! \\n\\nBienvenido al bot oficial de ayuda para toda la comunidad de la ESPOL 🐢💛💙. \\n\\nAquí puedes preguntarme lo que necesites sobre tu vida politécnica o lo que se viene en la U: \\n📅 Fechas importantes del calendario académico. \\n🎓 Preguntas frecuentes de todas las facultades — tanto pregrado como postgrado. \\n🎟️ Info sobre becas, clubes, cursos, eventos, transporte, servicios y más. \\n\\nY pilas 👀, porque cada semana te voy a mandar un recordatorio con lo más relevante que se viene para que no se te pase nada — ni matrícula, ni retiro, ni feriado 😎. Así que tranqui, compa, pregunta nomás.\\n\\n¡Vamos con todo, politécnico! 🚀💪\",\"chatId\":\"={{ $json.message.chat.id }}\",\"additionalFields\":{\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"5f1bf72a-e7f4-405f-a1fc-549008b73747\",\"name\":\"Google Gemini Chat Model\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatGoogleGemini\",\"position\":[-672,1680],\"parameters\":{\"options\":{},\"modelName\":\"models/gemini-2.5-flash-lite\"},\"typeVersion\":1},{\"id\":\"bef601ae-58f3-4785-a49e-4a7225c34ed9\",\"name\":\"BD_ESPOL\",\"type\":\"n8n-nodes-base.googleSheetsTool\",\"position\":[-528,1712],\"parameters\":{\"options\":{},\"sheetName\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('Sheet', ``, 'string') }}\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit?usp=drivesdk\",\"cachedResultName\":\"BASE-DATOS-FAQ_ESPOL\"}},\"typeVersion\":4.7},{\"id\":\"c925a437-914c-4e86-8619-2a670ee53c40\",\"name\":\"PREGUNTAS AL AZAR DE GUIA\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[-672,1504],\"parameters\":{\"text\":\"=El usuario acaba de iniciar el bot con /start.\\nNo le muestres un mensaje de bienvenida.\\nSólo sugiérele 5 preguntas al azar (diferentes cada vez) que podría hacerle al bot, relacionadas con la información que está guardada en BD_ESPOL (preguntas frecuentes de facultades, calendario académico, becas, clubes, cursos, eventos, etc.).\\n\\nEjemplo de formato esperado:\\n\\n👋🏽 ¡Qué más, futuro politécnico! Bienvenido al bot de ayuda de la ESPOL 🐢💛💙\\nAquí puedes preguntar lo que necesites sobre tu vida universitaria o lo que se viene en el semestre.\\n\\nPuedes empezar con algo como:\\n• ¿Cuándo abren las matrículas?\\n• ¿Qué clubes hay en la ESPOL?\\n• ¿Dónde puedo ver las fechas de titulación?\\n• ¿Quien es el coordinador de la FIMCP?\\n• ¿Cuando empiezan las vacaciones del IIPAO 2025?\\n¡Dale nomás, pregunta lo que necesites que el bot te ayuda al instante! 😎\",\"options\":{\"systemMessage\":\"=Eres un asistente politécnico amigable y juvenil, que habla con tono guayaco, relajado y positivo. Estás conectado a una base de datos llamada BD_ESPOL, que contiene información sobre preguntas frecuentes, calendario académico, becas, clubes, cursos, eventos, servicios, vida universitaria, transporte, titulación y reglamentos.\\n\\nTu objetivo es ayudar a los estudiantes y futuros politécnicos a orientarse en la ESPOL.\\n\\nCada vez que un usuario nuevo inicia conversación, no debes volver a saludar, ya que el bot principal ya lo hizo. Solo debes explicarle brevemente cómo puede usar el bot y mostrarle 5 preguntas aleatorias distintas cada vez que podría intentar para descubrir las funciones del bot.\\n\\nEl mensaje debe sonar natural, como si fueras un compañero universitario de Guayaquil, usando expresiones relajadas pero respetuosas.\\nEvita usar asteriscos, puntos o cualquier formato Markdown. Usa guiones (-) para enumerar las preguntas.\\n\\nLas preguntas deben cubrir temas variados: calendario académico, becas, facultades, servicios, transporte, vida universitaria, titulación y eventos.\\nCada vez que respondas, cambia el orden o tipo de preguntas para que no sean las mismas.\\n\\nEjemplo de estilo y estructura:\\nAquí puedes preguntar sobre fechas, becas, clubes o eventos\\nMira, puedes probar con algo como\\n\\n- ¿Cuándo empiezan las clases?\\n\\n- ¿Qué becas hay disponibles?\\n\\n- ¿Dónde veo los cursos extracurriculares?\\n\\n- ¿Qué eventos hay esta semana?\\n\\n- ¿Cómo puedo unirme a un club estudiantil?\\n\\nTermina siempre con una frase motivadora tipo\\n\\n¡Dale, pregunta nomás!\\n\\n¡Pruébalo y ve lo bacán que está esto!\"},\"promptType\":\"define\"},\"typeVersion\":3},{\"id\":\"b74244ac-ed9a-4979-95ac-d15a620c7df4\",\"name\":\"Wait\",\"type\":\"n8n-nodes-base.wait\",\"position\":[-368,1504],\"webhookId\":\"d38e8f38-68a5-4b15-b8c3-4dce9f102f38\",\"parameters\":{},\"typeVersion\":1.1},{\"id\":\"3104667b-6c32-4a83-9627-23609865000e\",\"name\":\"GUIA DE COMO PREGUNTAR\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-208,1504],\"webhookId\":\"4e6cea20-85ce-4b9a-b931-8fa22d93b87b\",\"parameters\":{\"text\":\"={{ $json.output }}\",\"chatId\":\"={{ $('Telegram Trigger - Inicio').item.json.message.chat.id }}\",\"additionalFields\":{\"parse_mode\":\"HTML\",\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"dff25489-2b4d-49da-9398-9efa73bbe8f5\",\"name\":\"Google Gemini Chat Model1\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatGoogleGemini\",\"position\":[-3168,1840],\"parameters\":{\"options\":{}},\"typeVersion\":1},{\"id\":\"7e30adff-e90b-495b-af22-d82ab8a464a3\",\"name\":\"BD_CALENDARIO1\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[-3872,1664],\"parameters\":{\"options\":{},\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":1817620056,\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit#gid=1817620056\",\"cachedResultName\":\"CALENDAR\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit?usp=drivesdk\",\"cachedResultName\":\"BASE-DATOS-FAQ_ESPOL\"}},\"typeVersion\":4.7},{\"id\":\"6ee54764-d999-48bc-a498-d4ded389b2f9\",\"name\":\"GENERADOR DE ANUNCIOS1\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[-3168,1664],\"parameters\":{\"text\":\"=Convierte el siguiente texto en un mensaje casual ecuatoriano:\\n\\nPeriodo: {{ $json[\\\"RESULTADOS[0].PERIODO_FECHAS\\\"] }}\\nActividades: {{ $json[\\\"RESULTADOS[0].ACTIVIDADES_GRADO\\\"] }}\\nProcesos: {{ $json[\\\"RESULTADOS[0].PROCESOS_GRADO\\\"] }}\\nFormacion tecnica: {{ $json['RESULTADOS[0][\\\\'ACTIVIDADES DE FORMACIÓN TÉCNICA Y TECNOLÓGICA\\\\']'] }}\\n\",\"options\":{\"systemMessage\":\"=Eres un redactor ecuatoriano experto en comunicación universitaria. Tu tarea es convertir los datos de tres semanas (anterior, actual y siguiente) en un solo mensaje casual, fresco y cercano, como si lo dijera un estudiante politécnico. \\n\\nSigue estas reglas:\\n\\n1. **Prioriza la semana del medio (la actual)**. Es la principal. Describe sus actividades con entusiasmo, usando un tono motivador y natural.\\n2. Luego menciona brevemente lo ocurrido **la semana pasada (primer item)**, con frases tipo: \\n “Si te lo perdiste la semana pasada…” o “Por si no te enteraste…”.\\n3. Finalmente, habla de **la semana siguiente (último item)**, pero nunca digas “la próxima semana” a secas. \\n Siempre menciona explícitamente **la fecha del periodo**, por ejemplo: \\n “Y para la semana del 17 al 21 de noviembre…” \\n Usa frases como: “prepárate para”, “se viene”, “atentos que en la semana del…”.\\n4. Usa expresiones naturales de Ecuador como *pilas, ñaño, pana, de una, qué bestia, bacán, full, a romperla*.\\n5. Separa las secciones con saltos de línea y mantén un estilo cercano y fluido, tipo mensaje de Telegram o redes.\\n6. No inventes información fuera del JSON, solo reformula y organiza lo recibido.\\n7. El resultado final debe ser un **solo texto en español ecuatoriano**, sin etiquetas, ni formato JSON, ni comillas.\\n\\nEjemplo de estructura esperada:\\n\\n¡Qué más, mi gente politécnica! Esta semana del 10 al 14 de noviembre se viene con todo 💪. \\nSeguimos a full con las actividades formativas y los panas de Formación Técnica también están dándole duro. ¡Qué bestia la energía que se siente en el campus! \\n\\nSi te lo perdiste la semana pasada, hubo evaluaciones y descansos para recargar pilas. ¡Espero que hayas aprovechado! 😎 \\n\\nY atentos para la semana del 17 al 21 de noviembre, que llega la PRIMERA EVALUACIÓN del grado. ¡A romperla con todo el ñeque, panas! 📚🔥\\n\"},\"promptType\":\"define\"},\"typeVersion\":3},{\"id\":\"8c041a63-8828-4f90-b670-85e018f73157\",\"name\":\"ENVIO DE MENSAJE DE VOZ1\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-2400,1536],\"webhookId\":\"ae4eba6e-2e6a-4a50-a4ec-6c527850b3c7\",\"parameters\":{\"file\":\"={{ $('GENERADOR DE MENSAJE DE VOZ').item.json.URL }}\",\"chatId\":\"={{ $json.chatId }}\",\"operation\":\"sendAudio\",\"additionalFields\":{\"caption\":\"={{ \\n(() => {\\n const today = new Date();\\n const dayOfWeek = today.getDay(); // 0=domingo\\n const diffMonday = (dayOfWeek === 0 ? -6 : 1 - dayOfWeek) + 7; // +7 => próxima semana\\n const diffFriday = diffMonday + 4;\\n\\n const monday = new Date(today);\\n monday.setDate(today.getDate() + diffMonday);\\n\\n const friday = new Date(today);\\n friday.setDate(today.getDate() + diffFriday);\\n\\n const fmt = d => `${d.getDate().toString().padStart(2, '0')}/${(d.getMonth() + 1).toString().padStart(2, '0')}`;\\n\\n return `Anuncio Semanal - Semana del ${fmt(monday)} al ${fmt(friday)}`;\\n})()\\n}}\\n\"}},\"typeVersion\":1.2},{\"id\":\"9681b6de-a5db-443e-89a5-e6a927b92b89\",\"name\":\"ENVIO DE MENSAJE DE TEXTO1\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-2384,1824],\"webhookId\":\"fc1657ce-66de-4cae-940f-86f0afae3ae5\",\"parameters\":{\"text\":\"={{ $json.text }}\",\"chatId\":\"={{ $json.chatId }}\",\"additionalFields\":{\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"67e74e9f-13b3-4f5f-80f4-e35e75558704\",\"name\":\"OPTIMIZADOR\",\"type\":\"n8n-nodes-base.code\",\"position\":[-2800,1808],\"parameters\":{\"jsCode\":\"// Tu array de chat IDs\\nconst chatIds = $('ACTIVIDADES DE LA SEMANA1').first().json.CHAT_IDS_VALIDOS; // reemplaza con tus IDs\\n\\n// Mensaje a enviar\\nconst mensaje = $input.first().json.output;\\n\\n// Creamos un item por cada chat ID\\nreturn chatIds.map(id => ({\\n json: {\\n chatId: id,\\n text: mensaje\\n }\\n}));\\n\"},\"typeVersion\":2},{\"id\":\"23d73abe-5b2b-42c5-b50f-fea043f4cd1a\",\"name\":\"OPTIMIZADOR1\",\"type\":\"n8n-nodes-base.code\",\"position\":[-2640,1584],\"parameters\":{\"jsCode\":\"// Tu array de chat IDs\\nconst chatIds = $('ACTIVIDADES DE LA SEMANA1').first().json.CHAT_IDS_VALIDOS; // reemplaza con tus IDs\\n\\n// Mensaje a enviar\\nconst mensaje = $input.first().json.output;\\n\\n// Creamos un item por cada chat ID\\nreturn chatIds.map(id => ({\\n json: {\\n chatId: id,\\n text: mensaje\\n }\\n}));\\n\"},\"typeVersion\":2},{\"id\":\"5dfc42b7-8684-4e92-95ca-7e1154345402\",\"name\":\"GENERADOR DE MENSAJE DE VOZ\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-2800,1584],\"parameters\":{\"url\":\"https://ttsmp3.com/makemp3_new.php\",\"method\":\"POST\",\"options\":{\"response\":{\"response\":{\"responseFormat\":\"json\"}}},\"sendBody\":true,\"contentType\":\"form-urlencoded\",\"bodyParameters\":{\"parameters\":[{\"name\":\"msg\",\"value\":\"={{ $json.output }}\"},{\"name\":\"lang\",\"value\":\"Mia\"},{\"name\":\"source\",\"value\":\"ttsmp3\"}]}},\"typeVersion\":4.2},{\"id\":\"7008a1aa-c9fb-4777-aac2-63f51cb88d49\",\"name\":\"OBTENER_ID1\",\"type\":\"n8n-nodes-base.set\",\"position\":[-880,1712],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"fc9b6408-8e37-4395-935f-33985719dae3\",\"name\":\"chat_id\",\"type\":\"number\",\"value\":\"={{ $json.message.chat.id }}\"}]}},\"typeVersion\":3.4},{\"id\":\"0310e05e-bc18-48de-952d-2c7e5163ab1f\",\"name\":\"AGREGA ID_UNICAS1\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[-624,1856],\"parameters\":{\"columns\":{\"value\":{\"CHAT_ID\":\"={{ $json.chat_id }}\"},\"schema\":[{\"id\":\"PERIODO_FECHAS\",\"type\":\"string\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"PERIODO_FECHAS\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"ACTIVIDADES_GRADO\",\"type\":\"string\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"ACTIVIDADES_GRADO\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"PROCESOS_GRADO\",\"type\":\"string\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"PROCESOS_GRADO\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"ACTIVIDADES DE FORMACIÓN TÉCNICA Y TECNOLÓGICA\",\"type\":\"string\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"ACTIVIDADES DE FORMACIÓN TÉCNICA Y TECNOLÓGICA\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"CHAT_ID\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"CHAT_ID\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[\"CHAT_ID\"],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{},\"operation\":\"append\",\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":1817620056,\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit#gid=1817620056\",\"cachedResultName\":\"CALENDAR\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit?usp=drivesdk\",\"cachedResultName\":\"BASE-DATOS-FAQ_ESPOL\"}},\"typeVersion\":4.7},{\"id\":\"6f2891fd-2874-4273-aeeb-5092191df6ec\",\"name\":\"Split Out\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-3056,560],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"PERIODOS-FECHAS, ACTIVIDADES_GRADO, PROCESOS_GRADO, ACTIVIDADES_TECNICAS-TECNOLÓGICAS\"},\"typeVersion\":1},{\"id\":\"525e2001-f72e-4f12-b0b8-1773498e9298\",\"name\":\"HTML\",\"type\":\"n8n-nodes-base.html\",\"position\":[-3248,560],\"parameters\":{\"options\":{},\"operation\":\"extractHtmlContent\",\"extractionValues\":{\"values\":[{\"key\":\"PERIODOS-FECHAS\",\"cssSelector\":\"table tbody tr td:first-child\",\"returnArray\":true},{\"key\":\"ACTIVIDADES_GRADO\",\"cssSelector\":\"table tbody tr td:nth-child(2)\",\"returnArray\":true},{\"key\":\"PROCESOS_GRADO\",\"cssSelector\":\"table tbody tr td:nth-child(3)\",\"returnArray\":true},{\"key\":\"ACTIVIDADES_TECNICAS-TECNOLÓGICAS\",\"cssSelector\":\"table tbody tr td:nth-child(4)\",\"returnArray\":true}]}},\"typeVersion\":1.2},{\"id\":\"4fc9dc13-c0a9-424e-8fab-873ae62f7c09\",\"name\":\"BD-CALENDARIO\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[-2656,560],\"parameters\":{\"columns\":{\"value\":{\"PERIODO_FECHAS\":\"={{ $json[\\\"PERIODOS-FECHAS\\\"] }}\",\"PROCESOS_GRADO\":\"={{ $json.PROCESOS_GRADO }}\",\"ACTIVIDADES_GRADO\":\"={{ $json.ACTIVIDADES_GRADO }}\",\"ACTIVIDADES DE FORMACIÓN TÉCNICA Y TECNOLÓGICA\":\"={{ $json[\\\"ACTIVIDADES_TECNICAS-TECNOLÓGICAS\\\"] }}\"},\"schema\":[{\"id\":\"PERIODO_FECHAS\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"PERIODO_FECHAS\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"ACTIVIDADES_GRADO\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"ACTIVIDADES_GRADO\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"PROCESOS_GRADO\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"PROCESOS_GRADO\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"ACTIVIDADES DE FORMACIÓN TÉCNICA Y TECNOLÓGICA\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"ACTIVIDADES DE FORMACIÓN TÉCNICA Y TECNOLÓGICA\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"CHAT_ID\",\"type\":\"string\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"CHAT_ID\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[\"PERIODO_FECHAS\"],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{},\"operation\":\"appendOrUpdate\",\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":1817620056,\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit#gid=1817620056\",\"cachedResultName\":\"CALENDAR\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit?usp=drivesdk\",\"cachedResultName\":\"BASE-DATOS-FAQ_ESPOL\"}},\"typeVersion\":4.7},{\"id\":\"db4dfee5-023e-4736-8b12-4f62879a3907\",\"name\":\"SCRRAPPING\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-3488,560],\"parameters\":{\"url\":\"https://www.espol.edu.ec/es/vida-politecnica/calendario-grado\",\"options\":{\"timeout\":60000},\"sendHeaders\":true,\"headerParameters\":{\"parameters\":[{\"name\":\"User-Agent\",\"value\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36\"}]}},\"typeVersion\":4.2},{\"id\":\"d23cb762-8460-41b9-b291-179baa9985d2\",\"name\":\"CORRECTOR DE FECHAS\",\"type\":\"n8n-nodes-base.code\",\"position\":[-2880,560],\"parameters\":{\"jsCode\":\"// Recibir items\\nconst itemsIn = $input.all();\\nlet currentYear = '';\\nconst results = [];\\n\\nfunction detectMonth(text) {\\n // Detecta el mes en el texto (minúsculas para evitar errores)\\n const months = {\\n enero: 1, febrero: 2, marzo: 3, abril: 4, mayo: 5, junio: 6,\\n julio: 7, agosto: 8, septiembre: 9, octubre: 10, noviembre: 11, diciembre: 12\\n };\\n const lower = text.toLowerCase();\\n for (const [month, num] of Object.entries(months)) {\\n if (lower.includes(month)) return num;\\n }\\n return null;\\n}\\n\\nfor (const item of itemsIn) {\\n const data = item.json;\\n let period = data[\\\"PERIODOS-FECHAS\\\"] ? String(data[\\\"PERIODOS-FECHAS\\\"]).trim() : \\\"\\\";\\n\\n // Detectar si hay un año explícito\\n const yearMatch = period.match(/\\\\b(20\\\\d{2})\\\\b/);\\n if (yearMatch) {\\n currentYear = parseInt(yearMatch[1]);\\n }\\n\\n // Si es encabezado, mantener igual\\n if (/^(VACACIONES|PAE|PAO)/i.test(period)) {\\n results.push({ json: { ...data } });\\n continue;\\n }\\n\\n // Detectar meses del período\\n const firstMonth = detectMonth(period.split('-')[0] || '');\\n const secondMonth = detectMonth(period.split('-')[1] || '');\\n\\n // Si tenemos dos meses y el segundo es menor que el primero → cambio de año\\n if (firstMonth && secondMonth && secondMonth < firstMonth) {\\n currentYear++;\\n }\\n\\n // Si no hay año en el texto, agregar el actual\\n if (!/\\\\b20\\\\d{2}\\\\b/.test(period) && currentYear) {\\n period = `${period} ${currentYear}`;\\n }\\n\\n results.push({\\n json: {\\n ...data,\\n \\\"PERIODOS-FECHAS\\\": period\\n }\\n });\\n}\\n\\nreturn results;\\n\"},\"typeVersion\":2},{\"id\":\"797b1458-c900-40af-89fb-866cf15e0ee8\",\"name\":\"Switch\",\"type\":\"n8n-nodes-base.switch\",\"position\":[-1712,1712],\"parameters\":{\"rules\":{\"values\":[{\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":false,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"0e1c1bb4-3315-4632-a9dc-5f917baf41da\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json.callback_query !== undefined }}\",\"rightValue\":\"0\"}]}},{\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":false,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"23c2e3a0-e7c8-46de-b504-2cabd445ed54\",\"operator\":{\"type\":\"string\",\"operation\":\"contains\"},\"leftValue\":\"={{ ($json.message?.reply_to_message?.text || '') }}\",\"rightValue\":\"Lamento que la información no te haya sido útil\"}]}},{\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":false,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"318d7097-ff17-4636-b7bf-958de3da6788\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json.message?.text?.startsWith('/') }}\",\"rightValue\":\"\"}]}}]},\"options\":{\"ignoreCase\":true,\"fallbackOutput\":\"extra\"},\"looseTypeValidation\":true},\"typeVersion\":3.3},{\"id\":\"207caeb2-0dad-4a90-8cb7-f943663ecfc6\",\"name\":\"Code in JavaScript1\",\"type\":\"n8n-nodes-base.code\",\"position\":[-3360,1664],\"parameters\":{\"jsCode\":\"const semanas = $input.all();\\n\\n// Inicializamos un objeto vacío\\nconst combinado = {};\\n\\n// Recorremos todas las semanas y sus claves\\nfor (const semana of semanas) {\\n const datos = semana.json;\\n for (const [clave, valor] of Object.entries(datos)) {\\n if (!combinado[clave]) combinado[clave] = [];\\n if (valor !== undefined && valor !== null && valor !== \\\"\\\")\\n combinado[clave].push(String(valor).trim());\\n }\\n}\\n\\n// Unimos los valores repetidos en un solo string, separados por comas\\nfor (const clave of Object.keys(combinado)) {\\n combinado[clave] = [...new Set(combinado[clave])].join(\\\", \\\");\\n}\\n\\n// Devolvemos un solo item con todo unido\\nreturn [{ json: combinado }];\\n\"},\"typeVersion\":2},{\"id\":\"2760029c-b039-4aab-95bd-005caeead0b6\",\"name\":\"Split Out2\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-3504,1664],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"RESULTADOS[0].PERIODO_FECHAS, RESULTADOS[0].ACTIVIDADES_GRADO, RESULTADOS[0].PROCESOS_GRADO, RESULTADOS[0]['ACTIVIDADES DE FORMACIÓN TÉCNICA Y TECNOLÓGICA']\"},\"typeVersion\":1},{\"id\":\"9dff1b64-2d74-4de5-8dee-cfcebfcd3977\",\"name\":\"ACTIVIDADES DE LA SEMANA1\",\"type\":\"n8n-nodes-base.code\",\"position\":[-3664,1664],\"parameters\":{\"jsCode\":\"// 🗓️ FECHA ACTUAL Y AÑO\\nconst hoy = new Date();\\nconst anioActual = hoy.getFullYear();\\n\\n// ✅ FUNCIÓN PARA CALCULAR EL LUNES DE UNA SEMANA RELATIVA\\nfunction obtenerLunes(base, desplazamientoSemanas = 0) {\\n const dia = base.getDay(); // 0=domingo, 1=lunes...\\n const lunes = new Date(base);\\n const diff = (1 - dia + 7) % 7; // hasta lunes\\n lunes.setDate(base.getDate() + diff + desplazamientoSemanas * 7);\\n return lunes;\\n}\\n\\n// 📆 CALCULAR LAS TRES SEMANAS CLAVE\\nconst lunesSemanaAnterior = obtenerLunes(hoy, -1);\\nconst lunesProximaSemana = obtenerLunes(hoy, 0);\\nconst lunesSemanaPosterior = obtenerLunes(hoy, 1);\\n\\n// 🧠 FUNCIÓN PARA INTERPRETAR RANGOS TIPO “09 - 13 NOVIEMBRE” O “9-13nov”\\nfunction parsearRango(rango) {\\n if (!rango || typeof rango !== \\\"string\\\") return null;\\n\\n rango = rango\\n .replace(/([0-9])([a-zA-ZñÑ])/g, \\\"$1 $2\\\")\\n .replace(/\\\\s+/g, \\\" \\\")\\n .trim()\\n .toLowerCase();\\n\\n const match = rango.match(/(\\\\d{1,2})\\\\s*-\\\\s*(\\\\d{1,2})\\\\s*([a-zñ]+)/);\\n if (!match) return null;\\n\\n const [, inicioStr, finStr, mesStr] = match;\\n const inicio = parseInt(inicioStr);\\n const fin = parseInt(finStr);\\n\\n const meses = {\\n ene: 0, enero: 0,\\n feb: 1, febrero: 1,\\n mar: 2, marzo: 2,\\n abr: 3, abril: 3,\\n may: 4, mayo: 4,\\n jun: 5, junio: 5,\\n jul: 6, julio: 6,\\n ago: 7, agosto: 7,\\n sep: 8, sept: 8, septiembre: 8,\\n oct: 9, octubre: 9,\\n nov: 10, noviembre: 10,\\n dic: 11, diciembre: 11\\n };\\n\\n const mesNum = meses[mesStr];\\n if (mesNum === undefined) return null;\\n\\n let anioRango = anioActual;\\n if (mesNum === 0 && hoy.getMonth() === 11) {\\n anioRango = anioActual + 1;\\n }\\n\\n const inicioFecha = new Date(anioRango, mesNum, inicio);\\n const finFecha = new Date(anioRango, mesNum, fin);\\n return { inicio: inicioFecha, fin: finFecha };\\n}\\n\\n// 🔍 FUNCIÓN PARA BUSCAR COINCIDENCIA DE SEMANA\\nfunction filtrarPorSemana(items, lunesReferencia) {\\n const resultados = [];\\n for (const item of items) {\\n const rango = parsearRango(item.json.PERIODO_FECHAS);\\n if (!rango) continue;\\n\\n const mismoInicio =\\n rango.inicio.getFullYear() === lunesReferencia.getFullYear() &&\\n rango.inicio.getDate() === lunesReferencia.getDate() &&\\n rango.inicio.getMonth() === lunesReferencia.getMonth();\\n\\n if (mismoInicio) resultados.push(item);\\n }\\n return resultados;\\n}\\n\\n// 📊 OBTENER RESULTADOS PARA CADA SEMANA\\nconst resultadosAnterior = filtrarPorSemana(items, lunesSemanaAnterior);\\nconst resultadosActual = filtrarPorSemana(items, lunesProximaSemana);\\nconst resultadosPosterior = filtrarPorSemana(items, lunesSemanaPosterior);\\n\\n// 🧹 CHAT_IDS VÁLIDOS (ÚNICOS)\\nconst chatIds = items\\n .map(item => item.json.CHAT_ID)\\n .filter(id => id !== undefined && id !== null && String(id).trim() !== \\\"\\\")\\n .map(id => String(id).trim());\\n\\nconst uniqueChatIds = [...new Set(chatIds)];\\n\\n// 🏁 SALIDA FINAL\\nreturn [\\n {\\n json: {\\n SEMANA: \\\"ANTERIOR\\\",\\n LUNES_SEMANA: lunesSemanaAnterior.toISOString().split(\\\"T\\\")[0],\\n RESULTADOS: resultadosAnterior.map(i => i.json),\\n CHAT_IDS_VALIDOS: uniqueChatIds\\n }\\n },\\n {\\n json: {\\n SEMANA: \\\"ACTUAL / PRÓXIMA\\\",\\n LUNES_SEMANA: lunesProximaSemana.toISOString().split(\\\"T\\\")[0],\\n RESULTADOS: resultadosActual.map(i => i.json),\\n CHAT_IDS_VALIDOS: uniqueChatIds\\n }\\n },\\n {\\n json: {\\n SEMANA: \\\"POSTERIOR\\\",\\n LUNES_SEMANA: lunesSemanaPosterior.toISOString().split(\\\"T\\\")[0],\\n RESULTADOS: resultadosPosterior.map(i => i.json),\\n CHAT_IDS_VALIDOS: uniqueChatIds\\n }\\n }\\n];\\n\"},\"typeVersion\":2},{\"id\":\"03a100d6-1492-4834-a638-653ff0a235ca\",\"name\":\"ANUNCIO SEMANAL\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"position\":[-4096,1680],\"parameters\":{\"rule\":{\"interval\":[{\"field\":\"weeks\",\"triggerAtHour\":19}]}},\"typeVersion\":1.2},{\"id\":\"af582ce7-df08-42dc-b4e6-e04bbc086c21\",\"name\":\"ACTUALIZAR CALENDARIO\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"position\":[-3728,560],\"parameters\":{\"rule\":{\"interval\":[{\"daysInterval\":7}]}},\"typeVersion\":1.2}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"HTML\":{\"main\":[[{\"node\":\"Split Out\",\"type\":\"main\",\"index\":0}]]},\"Wait\":{\"main\":[[{\"node\":\"GUIA DE COMO PREGUNTAR\",\"type\":\"main\",\"index\":0}]]},\"Switch\":{\"main\":[[{\"node\":\"Respuesta Usuario1\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Guardado en cvs Feedback\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Comandos1\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Detector_Calendario_Pre\",\"type\":\"main\",\"index\":0}]]},\"BD_ESPOL\":{\"ai_tool\":[[{\"node\":\"PREGUNTAS AL AZAR DE GUIA\",\"type\":\"ai_tool\",\"index\":0}]]},\"Comandos1\":{\"main\":[[{\"node\":\"Mensaje Help\",\"type\":\"main\",\"index\":0}],[{\"node\":\"FAQs\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Respuesta Contact\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Respuesta Events\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Inicio - Feedback\",\"type\":\"main\",\"index\":0}],[{\"node\":\"BIENVENIDA\",\"type\":\"main\",\"index\":0},{\"node\":\"OBTENER_ID1\",\"type\":\"main\",\"index\":0}]]},\"Split Out\":{\"main\":[[{\"node\":\"CORRECTOR DE FECHAS\",\"type\":\"main\",\"index\":0}]]},\"BIENVENIDA\":{\"main\":[[{\"node\":\"PREGUNTAS AL AZAR DE GUIA\",\"type\":\"main\",\"index\":0}]]},\"Get a chat\":{\"main\":[[{\"node\":\"Sí - Agradecimiento1\",\"type\":\"main\",\"index\":0}]]},\"SCRRAPPING\":{\"main\":[[{\"node\":\"HTML\",\"type\":\"main\",\"index\":0}]]},\"Split Out2\":{\"main\":[[{\"node\":\"Code in JavaScript1\",\"type\":\"main\",\"index\":0}]]},\"OBTENER_ID1\":{\"main\":[[{\"node\":\"AGREGA ID_UNICAS1\",\"type\":\"main\",\"index\":0}]]},\"OPTIMIZADOR\":{\"main\":[[{\"node\":\"ENVIO DE MENSAJE DE TEXTO1\",\"type\":\"main\",\"index\":0}]]},\"OPTIMIZADOR1\":{\"main\":[[{\"node\":\"ENVIO DE MENSAJE DE VOZ1\",\"type\":\"main\",\"index\":0}]]},\"BD_CALENDARIO1\":{\"main\":[[{\"node\":\"ACTIVIDADES DE LA SEMANA1\",\"type\":\"main\",\"index\":0}]]},\"ANUNCIO SEMANAL\":{\"main\":[[{\"node\":\"BD_CALENDARIO1\",\"type\":\"main\",\"index\":0}]]},\"Message a model1\":{\"main\":[[{\"node\":\"Limpiar_Texto_Gemini1\",\"type\":\"main\",\"index\":0}]]},\"Inicio - Feedback\":{\"main\":[[]]},\"Mensaje de Gemini\":{\"main\":[[{\"node\":\"Limpiar texto Gemini\",\"type\":\"main\",\"index\":0}]]},\"Respuesta Usuario1\":{\"main\":[[{\"node\":\"Get a chat\",\"type\":\"main\",\"index\":0}],[{\"node\":\"No - Mensaje Feedback1\",\"type\":\"main\",\"index\":0}]]},\"Switch_Que_BD_Leer\":{\"main\":[[{\"node\":\"Calendario Académico\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Leer FAQs de MongoDB\",\"type\":\"main\",\"index\":0}]]},\"CORRECTOR DE FECHAS\":{\"main\":[[{\"node\":\"BD-CALENDARIO\",\"type\":\"main\",\"index\":0}]]},\"Code in JavaScript1\":{\"main\":[[{\"node\":\"GENERADOR DE ANUNCIOS1\",\"type\":\"main\",\"index\":0}]]},\"Leer FAQs de MongoDB\":{\"main\":[[{\"node\":\"Buscar_FAQs_Relevantes\",\"type\":\"main\",\"index\":0}]]},\"Limpiar texto Gemini\":{\"main\":[[{\"node\":\"Enviar Respuesta sobre faqs\",\"type\":\"main\",\"index\":0}]]},\"ACTUALIZAR CALENDARIO\":{\"main\":[[{\"node\":\"SCRRAPPING\",\"type\":\"main\",\"index\":0}]]},\"Calendario Académico\":{\"main\":[[{\"node\":\"Buscar_Eventos_Calendario1\",\"type\":\"main\",\"index\":0}]]},\"Limpiar_Texto_Gemini1\":{\"main\":[[{\"node\":\"Enviar Respuesta sobre calendario1\",\"type\":\"main\",\"index\":0}]]},\"Buscar_FAQs_Relevantes\":{\"main\":[[{\"node\":\"Construir_Prompt_Gemini1\",\"type\":\"main\",\"index\":0}]]},\"GENERADOR DE ANUNCIOS1\":{\"main\":[[{\"node\":\"OPTIMIZADOR\",\"type\":\"main\",\"index\":0}]]},\"No - Mensaje Feedback1\":{\"main\":[[]]},\"Detector_Calendario_Pre\":{\"main\":[[{\"node\":\"Switch_Que_BD_Leer\",\"type\":\"main\",\"index\":0}]]},\"Construir_Prompt_Gemini1\":{\"main\":[[{\"node\":\"Mensaje de Gemini\",\"type\":\"main\",\"index\":0}]]},\"Google Gemini Chat Model\":{\"ai_languageModel\":[[{\"node\":\"PREGUNTAS AL AZAR DE GUIA\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Guardado en cvs Feedback\":{\"main\":[[]]},\"ACTIVIDADES DE LA SEMANA1\":{\"main\":[[{\"node\":\"Split Out2\",\"type\":\"main\",\"index\":0}]]},\"Google Gemini Chat Model1\":{\"ai_languageModel\":[[{\"node\":\"GENERADOR DE ANUNCIOS1\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"PREGUNTAS AL AZAR DE GUIA\":{\"main\":[[{\"node\":\"Wait\",\"type\":\"main\",\"index\":0}]]},\"Telegram Trigger - Inicio\":{\"main\":[[{\"node\":\"Switch\",\"type\":\"main\",\"index\":0}]]},\"Buscar_Eventos_Calendario1\":{\"main\":[[{\"node\":\"Construir_Prompt_Calendario1\",\"type\":\"main\",\"index\":0}]]},\"Enviar Respuesta sobre faqs\":{\"main\":[[]]},\"GENERADOR DE MENSAJE DE VOZ\":{\"main\":[[{\"node\":\"OPTIMIZADOR1\",\"type\":\"main\",\"index\":0}]]},\"Construir_Prompt_Calendario1\":{\"main\":[[{\"node\":\"Message a model1\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 53, "node_types": {"code": 12, "switch": 4, "telegram": 14, "mongoDb": 1, "telegramTrigger": 1, "googleGemini": 2, "googleSheets": 5, "lmChatGoogleGemini": 2, "googleSheetsTool": 1, "agent": 2, "wait": 1, "httpRequest": 2, "set": 1, "splitOut": 2, "html": 1, "scheduleTrigger": 2}, "services": ["ai", "google", "http"], "complexity": "complex", "has_conditions": false, "has_loops": true, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: University FAQ & Calendar Assistant with Telegram, MongoDB and Gemini AI"}, {"role": "assistant", "content": "\n**Analyse du besoin**: 🤖 Interactive Academic Chatbot (Telegram + MongoDB)\nOverview 📋\n\nThis project is a template for building a complete academic virtual assistant using n8n. It connects to Telegram, answers frequently ask...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 53 nodes utilisant ai, google, http.\nStructure: traitement par lots, code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"qVwL4UVRZaWLVZtQ\",\"meta\":{\"instanceId\":\"8a5440a5ddd0e75b8a9a2e3575b14d94d566aa1e1140eba5b0cc9b9eb91aaea3\",\"templateCredsSetupCompleted\":true},\"name\":\"ESPOLBot CALENDARIO|FAQS\",\"tags\":[],\"nodes\":[{\"id\":\"6d06b9e5-4027-4626-8315-2b02a3087727\",\"name\":\"Construir_Prompt_Gemini1\",\"type\":\"n8n-nodes-base.code\",\"position\":[-1008,2448],\"parameters\":{\"jsCode\":\"const preguntaUsuario = $json.pregunta_usuario;\\nconst faqsRelevantes = $json.contexto_faqs || [];\\n\\nlet contextoFAQs = '';\\nif (faqsRelevantes.length > 0) {\\n contextoFAQs = 'Aqui hay informacion relevante de la base de datos:\\\\n\\\\n';\\n contextoFAQs += faqsRelevantes.map((faq, index) => {\\n return `${index + 1}. P: ${faq.pregunta}\\\\n R: ${faq.respuesta}${faq.enlaces ? `\\\\n Link: ${faq.enlaces}` : ''}`;\\n }).join('\\\\n\\\\n');\\n} else {\\n contextoFAQs = 'No encontre informacion especifica en la base de datos para esta pregunta.';\\n}\\n\\nconst prompt = `Eres un asistente de ESPOL. Un estudiante te pregunto:\\n\\n\\\"${preguntaUsuario}\\\"\\n\\n${contextoFAQs}\\n\\nIMPORTANTE:\\n- La pregunta del usuario ES VALIDA y CLARA\\n- Si hay informacion arriba, usala para responder\\n- Si NO hay informacion especifica, di algo como: \\\"No tengo informacion especifica sobre [tema], pero puedes contactar a ESPOL\\\"\\n- NUNCA digas \\\"no has hecho ninguna pregunta\\\"\\n\\nContactos generales:\\n- Email: admision@espol.edu.ec\\n- Telefono: (04) 2269-269\\n- Web: https://www.espol.edu.ec\\n\\nResponde de forma COMPLETA, clara y util. Incluye TODOS los detalles necesarios:`;\\n\\nreturn [{\\n json: {\\n prompt: prompt\\n }\\n}];\"},\"typeVersion\":2},{\"id\":\"95fcc718-5c12-423d-b062-b9935d3f8506\",\"name\":\"Buscar_FAQs_Relevantes\",\"type\":\"n8n-nodes-base.code\",\"position\":[-1264,2448],\"parameters\":{\"jsCode\":\"function limpiarTexto(texto) {\\n if (!texto) return '';\\n return texto\\n .toLowerCase()\\n .normalize('NFD').replace(/[\\\\u0300-\\\\u036f]/g, '')\\n .replace(/[¿?¡!.,;:]/g, '')\\n .replace(/\\\\s+/g, ' ')\\n .trim();\\n}\\n\\n// Leer la pregunta del Telegram Trigger\\n// En runOnceForAllItems, usar .all() para acceder al primer (y normalmente único) mensaje\\nconst telegramInput = $('Telegram Trigger - Inicio').all()[0]?.json || {};\\nconst preguntaUsuario = telegramInput.message?.text || '';\\nconst chatId = telegramInput.message?.chat?.id || '';\\n\\n// Las FAQs vienen del input (MongoDB)\\nconst todasLasFAQs = $input.all();\\n\\nconst preguntaLimpia = limpiarTexto(preguntaUsuario);\\nconst palabrasUsuario = preguntaLimpia.split(' ').filter(p => p.length > 2);\\n\\nconst faqsRelevantes = [];\\n\\nconsole.log(`========================================`);\\nconsole.log(`Pregunta usuario: \\\"${preguntaUsuario}\\\"`);\\nconsole.log(`Chat ID: ${chatId}`);\\nconsole.log(`Palabras clave: ${palabrasUsuario.join(', ')}`);\\nconsole.log(`Total FAQs en MongoDB: ${todasLasFAQs.length}`);\\n\\nfor (const faq of todasLasFAQs) {\\n const preguntaFAQ = faq.json.PREGUNTA || faq.json.pregunta || '';\\n if (!preguntaFAQ) continue;\\n \\n const preguntaFAQLimpia = limpiarTexto(preguntaFAQ);\\n \\n let coincidencias = 0;\\n for (const palabra of palabrasUsuario) {\\n if (preguntaFAQLimpia.includes(palabra)) {\\n coincidencias++;\\n }\\n }\\n \\n if (coincidencias >= 2) {\\n const score = coincidencias / palabrasUsuario.length;\\n \\n faqsRelevantes.push({\\n pregunta: preguntaFAQ,\\n respuesta: faq.json.RESPUESTA || faq.json.respuesta || '',\\n enlaces: faq.json.ENLACES || faq.json.enlaces || null,\\n similitud: Math.round(score * 100) / 100,\\n coincidencias: coincidencias\\n });\\n }\\n}\\n\\nfaqsRelevantes.sort((a, b) => b.coincidencias - a.coincidencias);\\nconst top10 = faqsRelevantes.slice(0, 10);\\n\\nconsole.log(`FAQs encontradas: ${top10.length}`);\\nif (top10.length > 0) {\\n console.log(`Top 5 candidatas:`);\\n top10.slice(0, 5).forEach((faq, i) => {\\n console.log(` ${i+1}. \\\"${faq.pregunta.substring(0, 70)}...\\\" (${faq.coincidencias} palabras)`);\\n });\\n} else {\\n console.log(`⚠️ NO SE ENCONTRARON FAQs`);\\n}\\nconsole.log(`========================================`);\\n\\nreturn [{\\n json: {\\n pregunta_usuario: preguntaUsuario,\\n contexto_faqs: top10,\\n total_encontradas: top10.length,\\n chat_id: chatId\\n }\\n}];\"},\"typeVersion\":2},{\"id\":\"d5e736d4-9d75-44d5-b1c8-dfe94b289e68\",\"name\":\"Respuesta Usuario1\",\"type\":\"n8n-nodes-base.switch\",\"position\":[-1616,1184],\"parameters\":{\"rules\":{\"values\":[{\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"3874c471-84a4-4058-8a35-0cc833b8617d\",\"operator\":{\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.callback_query.data }}\",\"rightValue\":\"feedback_yes\"}]}},{\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"a53cc39a-2efc-4196-9425-1afba6fc8d7d\",\"operator\":{\"name\":\"filter.operator.equals\",\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.callback_query.data }}\",\"rightValue\":\"feedback_no\"}]}}]},\"options\":{}},\"typeVersion\":3.3},{\"id\":\"d9139b9c-e970-4c60-88b8-47bd105ab0aa\",\"name\":\"Sí - Agradecimiento1\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-1264,1008],\"webhookId\":\"d64de90b-2449-4bcc-8815-f43c2e94c0b5\",\"parameters\":{\"text\":\"🎉 ¡Genial! Me alegra mucho saber que pude ayudarte 💪 Si necesitas algo más, estoy aquí para ti 🤖\",\"chatId\":\"={{ $json.result.id }}\",\"additionalFields\":{\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"9c41f1ef-12bf-4620-9719-821461334db6\",\"name\":\"No - Mensaje Feedback1\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-1264,1152],\"webhookId\":\"606e94b8-5fcd-4977-852e-d0030aacf8a6\",\"parameters\":{\"text\":\"=😔 Lamento que la información no te haya sido útil.\\n¿Podrías contarme qué necesitabas exactamente para mejorar mi ayuda? 🤖\",\"chatId\":\"={{ $json.callback_query.message.chat.id }}\",\"forceReply\":{\"force_reply\":true},\"replyMarkup\":\"forceReply\",\"additionalFields\":{\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"cc0258e3-303c-44e5-8c96-80287ba1ab88\",\"name\":\"Comandos1\",\"type\":\"n8n-nodes-base.switch\",\"position\":[-1248,1664],\"parameters\":{\"rules\":{\"values\":[{\"outputKey\":\"/help\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"62d19c71-6b1b-4d67-9a45-8aff710df07c\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json[\\\"message\\\"] && $json[\\\"message\\\"][\\\"text\\\"] === \\\"/help\\\" }}\",\"rightValue\":\"/start\"}]},\"renameOutput\":true},{\"outputKey\":\"/faqs\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"4a392957-3709-4c6e-a7ac-6f6004836860\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json[\\\"message\\\"] && $json[\\\"message\\\"][\\\"text\\\"] === \\\"/faqs\\\" }}\",\"rightValue\":\"\"}]},\"renameOutput\":true},{\"outputKey\":\"/contact\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"32b9b535-3e0a-4d3f-8691-fdc1e955a9ce\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json[\\\"message\\\"] && $json[\\\"message\\\"][\\\"text\\\"] === \\\"/contact\\\" }}\",\"rightValue\":\"\"}]},\"renameOutput\":true},{\"outputKey\":\"/events\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"9393b68b-7c44-48cf-b2d0-d23289673ff6\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json[\\\"message\\\"] && $json[\\\"message\\\"][\\\"text\\\"] === \\\"/events\\\" }}\",\"rightValue\":\"\"}]},\"renameOutput\":true},{\"outputKey\":\"/feedback\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"df2037b1-36f0-4428-bdd4-b5118f687d8f\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json[\\\"message\\\"] && $json[\\\"message\\\"][\\\"text\\\"] === \\\"/feedback\\\" }}\",\"rightValue\":\"\"}]},\"renameOutput\":true},{\"outputKey\":\"/start\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"58d0352b-c98a-4ac7-bf60-f6a6e6919744\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json[\\\"message\\\"] && $json[\\\"message\\\"][\\\"text\\\"] === \\\"/start\\\" }}\",\"rightValue\":\"\"}]},\"renameOutput\":true}]},\"options\":{},\"looseTypeValidation\":true},\"typeVersion\":3.3},{\"id\":\"79a97506-c1e2-4049-a62a-e5820b681a0d\",\"name\":\"Inicio - Feedback\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-880,1312],\"webhookId\":\"c87b9628-09ed-468b-ab95-9b97e4c4f0ef\",\"parameters\":{\"text\":\"=💬 *Enviar Feedback*\\n\\n¿Tienes alguna sugerencia o comentario sobre el bot? \\n\\n📝 Escribe tu mensaje a continuación y lo revisaremos.\\n\\n🤖 *¡Tu opinión es importante!* \\n\\n💡 *Tip:* Los botones 👍 👎 aparecen después de cada respuesta para que califiques la información.\",\"chatId\":\"={{ $json.message.chat.id }}\",\"replyMarkup\":\"inlineKeyboard\",\"inlineKeyboard\":{\"rows\":[{\"row\":{\"buttons\":[{\"text\":\"👍 Sí, me ayudó\",\"additionalFields\":{\"callback_data\":\"feedback_yes\"}},{\"text\":\"👎 No, no me ayudó\",\"additionalFields\":{\"callback_data\":\"feedback_no\"}}]}}]},\"additionalFields\":{\"parse_mode\":\"Markdown\",\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"accfeb10-fcb6-4b1e-a1bb-a40ed82ebcdd\",\"name\":\"FAQs\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-880,784],\"webhookId\":\"04237280-d7f2-4b1e-96cf-37343b850b8b\",\"parameters\":{\"text\":\"💬 Sección de Consultas – ChatBot ESPOL\\n\\nEstás en la sección de preguntas frecuentes.\\nAquí puedes escribir cualquier duda o consulta sobre la universidad —por ejemplo, temas de matrícula, eventos, horarios o servicios estudiantiles— y te responderé enseguida.\\n\\n✍️ Escribe tu pregunta para continuar.\\nPor ejemplo: “Necesito información sobre los eventos de esta semana” o “¿Dónde puedo comunicarme con admisiones?”\",\"chatId\":\"={{ $('Telegram Trigger - Inicio').item.json.message.chat.id }}\",\"additionalFields\":{\"parse_mode\":\"Markdown\",\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"ccd1f1ed-5aa2-402c-a40e-5650ee6066d7\",\"name\":\"Leer FAQs de MongoDB\",\"type\":\"n8n-nodes-base.mongoDb\",\"position\":[-1520,2448],\"parameters\":{\"options\":{},\"collection\":\"espol_faqs\"},\"typeVersion\":1.2},{\"id\":\"6529ea5d-0af3-4acc-b81b-087730a484b6\",\"name\":\"Telegram Trigger - Inicio\",\"type\":\"n8n-nodes-base.telegramTrigger\",\"position\":[-1872,1744],\"webhookId\":\"472c70d1-8362-4668-83dc-3e7c2985bc08\",\"parameters\":{\"updates\":[\"message\",\"callback_query\",\"*\"],\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"5bfddfd3-92ac-432f-aa64-3f19ab58f30a\",\"name\":\"Respuesta Contact\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-880,960],\"webhookId\":\"57a49a16-8222-4da4-8df5-06b6325c4083\",\"parameters\":{\"text\":\"=📞 *Información de Contacto ESPOL*\\n\\n🌐 Web: https://www.espol.edu.ec\\n📧 Email: admision@espol.edu.ec\\n📱 Teléfono: (04) 2269-269\\n\\n📍 Campus Gustavo Galindo Velasco\\nKm. 30.5 Vía Perimetral\\nGuayaquil, Ecuador\\n\\n📧 Otros contactos:\\nComunicación: comunicacion@espol.edu.ec\\nRelaciones Externas y Vinculación Corporativa: relex@espol.edu.ec\\nPostgrados: postgrad@espol.edu.ec\\nTransparencia: transparencia@espol.edu.ec\",\"chatId\":\"={{ $('Telegram Trigger - Inicio').item.json.message.chat.id }}\",\"additionalFields\":{\"parse_mode\":\"Markdown\",\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"8aa3525d-815a-486a-92cb-9d9e5da991e5\",\"name\":\"Respuesta Events\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-880,1136],\"webhookId\":\"8688a44d-b766-45c4-b314-3ef4dc105e1d\",\"parameters\":{\"text\":\"=📅 *Próximos Eventos Académicos*\\n\\nPara ver el calendario completo de eventos, visita:\\nhttps://www.espol.edu.ec/es/calendario-academico\\n\\nO pregúntame sobre fechas específicas, por ejemplo:\\n\\\"¿Cuándo son las vacaciones?\\\"\\n\\\"¿Cuándo es el examen de admisión?\\\"\",\"chatId\":\"={{ $json.message.chat.id }}\",\"additionalFields\":{\"parse_mode\":\"Markdown\",\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"767c3c89-dfb0-4505-8c87-a0208fe31aba\",\"name\":\"Limpiar texto Gemini\",\"type\":\"n8n-nodes-base.code\",\"position\":[-480,2448],\"parameters\":{\"jsCode\":\"const geminiResponse = $input.first().json;\\nconst chatId = $('Buscar_FAQs_Relevantes').first().json.chat_id;\\n\\nlet texto = '';\\n\\ntry {\\n if (geminiResponse.candidates && geminiResponse.candidates[0] && geminiResponse.candidates[0].content && geminiResponse.candidates[0].content.parts) {\\n texto = geminiResponse.candidates[0].content.parts[0].text;\\n } else if (geminiResponse.content && geminiResponse.content.parts) {\\n texto = geminiResponse.content.parts[0].text;\\n } else if (geminiResponse.text) {\\n texto = geminiResponse.text;\\n } else {\\n texto = \\\"Lo siento, hubo un problema al procesar la respuesta.\\\";\\n }\\n} catch (error) {\\n texto = \\\"Lo siento, ocurrio un error.\\\";\\n}\\n\\nif (texto && texto.length > 0) {\\n texto = texto.replace(/\\\\*\\\\*/g, '').replace(/`/g, '').trim();\\n}\\n\\nreturn [{\\n json: {\\n texto_limpio: texto,\\n chat_id: chatId\\n }\\n}];\"},\"typeVersion\":2},{\"id\":\"7cabbbc4-e002-4c04-a4d9-b5c3633e98af\",\"name\":\"Get a chat\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-1488,1056],\"webhookId\":\"4540ece6-38eb-40ac-bb7c-862f2e198807\",\"parameters\":{\"chatId\":\"={{ $json.callback_query.message.chat.id }}\",\"resource\":\"chat\"},\"typeVersion\":1.2},{\"id\":\"b5cdf1bf-6f19-4e62-a812-022e5fe6073c\",\"name\":\"Switch_Que_BD_Leer\",\"type\":\"n8n-nodes-base.switch\",\"position\":[-1856,2304],\"parameters\":{\"rules\":{\"values\":[{\"outputKey\":\"=Consultar Calendario\",\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"9404fad9-6063-443e-9a4c-80c86a20a6a9\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json.es_consulta_calendario }}\",\"rightValue\":\"\"}]},\"renameOutput\":true}]},\"options\":{\"fallbackOutput\":\"extra\"}},\"typeVersion\":3.3},{\"id\":\"09ddecdf-9223-4371-bd53-9d836315b7a3\",\"name\":\"Detector_Calendario_Pre\",\"type\":\"n8n-nodes-base.code\",\"position\":[-2064,2304],\"parameters\":{\"jsCode\":\"// ===== DETECTOR PRE-LECTURA DE CALENDARIO =====\\n\\nfunction limpiarTexto(texto) {\\n if (!texto) return '';\\n return texto\\n .toLowerCase()\\n .normalize('NFD').replace(/[\\\\u0300-\\\\u036f]/g, '')\\n .replace(/[¿?¡!.,;:]/g, '')\\n .replace(/\\\\s+/g, ' ')\\n .trim();\\n}\\n\\n// Procesar todos los items entrantes del Trigger\\nconst inputItems = $('Telegram Trigger - Inicio').all();\\nconst resultados = [];\\n\\nfor (const item of inputItems) {\\n const preguntaUsuario = item.json.message?.text || '';\\n const chatId = item.json.message?.chat?.id || '';\\n const preguntaLimpia = limpiarTexto(preguntaUsuario);\\n\\n // ===== PALABRAS CLAVE DE CALENDARIO =====\\n const palabrasClaveCalendario = {\\n eventos: [\\n 'matricula', 'matriculas', 'matriculacion',\\n 'inicio de clases', 'fin de clases', 'clases',\\n 'primer termino', 'segundo termino', 'tercer termino',\\n 'examenes', 'examen', 'prueba', 'pruebas',\\n 'evaluaciones', 'evaluacion',\\n 'suspension', 'feriado', 'feriados',\\n 'vacaciones', 'receso',\\n 'cambio de carrera', 'cambio de materia',\\n 'retiro', 'retiros',\\n 'solicitudes', 'solicitud',\\n 'inscripciones', 'inscripcion',\\n 'graduacion', 'grado',\\n 'titulacion',\\n 'becas', 'beca',\\n 'nivelacion'\\n ],\\n \\n tiempo: [\\n 'cuando', 'fecha', 'fechas', 'dia', 'dias',\\n 'plazo', 'plazos', 'periodo', 'periodos',\\n 'termino', 'terminos', 'semestre', 'año',\\n 'inicio', 'fin', 'cierre', 'apertura',\\n 'hasta cuando', 'desde cuando',\\n 'calendario', 'cronograma',\\n 'horario', 'horarios',\\n 'proxima', 'proximo', 'siguiente'\\n ],\\n \\n terminos: [\\n '2024-2025', '2025-2026',\\n 'PAO', 'PAOI', 'PAOII', 'IPAO', 'IIPAO', 'PAO1', 'PAO2',\\n 'primer', 'segundo', 'tercer',\\n 'trimestre', 'bimestre', 'semestral'\\n ]\\n };\\n\\n // Combinar todas las palabras clave\\n const todasLasPalabrasClave = [\\n ...palabrasClaveCalendario.eventos,\\n ...palabrasClaveCalendario.tiempo,\\n ...palabrasClaveCalendario.terminos\\n ];\\n\\n // ===== DETECCIÓN =====\\n let palabrasEncontradas = [];\\n let puntuacion = 0;\\n\\n for (const palabra of todasLasPalabrasClave) {\\n if (preguntaLimpia.includes(palabra)) {\\n palabrasEncontradas.push(palabra);\\n if (palabrasClaveCalendario.eventos.includes(palabra)) {\\n puntuacion += 2;\\n } else {\\n puntuacion += 1;\\n }\\n }\\n }\\n\\n // Decisión: ¿Es consulta de calendario?\\n const esConsultaCalendario = puntuacion >= 2 || palabrasEncontradas.length >= 2;\\n\\n // LOGS\\n console.log(`========================================`);\\n console.log(`🔍 DETECTOR PRE-LECTURA DE CALENDARIO`);\\n console.log(`Pregunta: \\\"${preguntaUsuario}\\\"`);\\n console.log(`Palabras encontradas: ${palabrasEncontradas.join(', ') || 'ninguna'}`);\\n console.log(`Puntuación: ${puntuacion}`);\\n console.log(`¿Es calendario? ${esConsultaCalendario ? '✅ SÍ' : '❌ NO'}`);\\n console.log(`${esConsultaCalendario ? '→ Irá a BD_Calendario' : '→ Irá a FAQs (flujo normal)'}`);\\n console.log(`========================================`);\\n\\n resultados.push({\\n json: {\\n pregunta_usuario: preguntaUsuario,\\n chat_id: chatId,\\n es_consulta_calendario: esConsultaCalendario,\\n palabras_encontradas: palabrasEncontradas,\\n puntuacion: puntuacion\\n }\\n });\\n}\\n\\nreturn resultados;\"},\"typeVersion\":2},{\"id\":\"81ea9f6c-121c-4bc5-99e4-e947dae8bf7a\",\"name\":\"Mensaje de Gemini\",\"type\":\"@n8n/n8n-nodes-langchain.googleGemini\",\"position\":[-800,2448],\"parameters\":{\"modelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"models/gemini-2.5-flash-lite-preview-06-17\",\"cachedResultName\":\"models/gemini-2.5-flash-lite-preview-06-17\"},\"options\":{\"temperature\":0.3,\"maxOutputTokens\":2000},\"messages\":{\"values\":[{\"content\":\"={{ $json.prompt }}\"}]},\"simplify\":false},\"typeVersion\":1,\"alwaysOutputData\":false},{\"id\":\"8116c6c4-e4ca-4450-89ab-17df67b4b886\",\"name\":\"Enviar Respuesta sobre faqs\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-224,2448],\"webhookId\":\"0096bd46-0086-4c23-87a8-a63bfebca2d8\",\"parameters\":{\"text\":\"={{ $json.texto_limpio }}\\n\\n💬 ¿Deseas revisar otra consulta o hacer una nueva pregunta?\",\"chatId\":\"={{ $json.chat_id }}\",\"replyMarkup\":\"inlineKeyboard\",\"inlineKeyboard\":{\"rows\":[{\"row\":{\"buttons\":[{\"text\":\"👍 Sí\",\"additionalFields\":{\"callback_data\":\"=feedback_yes\"}},{\"text\":\"👎 No\",\"additionalFields\":{\"callback_data\":\"=feedback_no\"}}]}}]},\"additionalFields\":{\"parse_mode\":\"HTML\",\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"5f4eed47-a777-4d27-a80a-bcc145808f42\",\"name\":\"Guardado en cvs Feedback\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[-1264,1296],\"parameters\":{\"columns\":{\"value\":{\"id\":\"={{ $json.message.chat.id }}\",\"Nombre\":\"={{ $json.message.reply_to_message.chat.first_name }}\",\"Comentario\":\"={{ $json.message.text }}\"},\"schema\":[{\"id\":\"id\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"id\",\"defaultMatch\":true,\"canBeUsedToMatch\":true},{\"id\":\"Nombre\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"Nombre\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"Comentario\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"Comentario\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[\"id\"],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{},\"operation\":\"append\",\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gid=0\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1dcEsIPMMnjBtQ1YXy5Zc50OWwBVOcWXpxkJUJWZmE4E/edit#gid=0\",\"cachedResultName\":\"Sheet1\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1dcEsIPMMnjBtQ1YXy5Zc50OWwBVOcWXpxkJUJWZmE4E\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1dcEsIPMMnjBtQ1YXy5Zc50OWwBVOcWXpxkJUJWZmE4E/edit?usp=drivesdk\",\"cachedResultName\":\"Feedback\"}},\"typeVersion\":4.7},{\"id\":\"cdf6ad08-7f31-467e-9feb-9d3a8e1c9ba6\",\"name\":\"Construir_Prompt_Calendario1\",\"type\":\"n8n-nodes-base.code\",\"position\":[-1008,2160],\"parameters\":{\"jsCode\":\"const preguntaUsuario = $json.consulta || $json.pregunta_usuario || $json.pregunta || '';\\nconst chatId = $json.chat_id;\\n\\n// Preferir el nuevo esquema del buscador\\nlet eventos = Array.isArray($json.resultados) ? $json.resultados : [];\\n\\n// Compatibilidad con el arreglo antiguo { eventos_calendario: [...] }\\nif ((!eventos || eventos.length === 0) && Array.isArray($json.eventos_calendario)) {\\n eventos = $json.eventos_calendario.map((e) => ({\\n PERIODO_FECHAS: e.periodo || e.PERIODO_FECHAS || '',\\n ACTIVIDADES_GRADO: e.actividades_grado || e.ACTIVIDADES_GRADO || '',\\n PROCESOS_GRADO: e.procesos_grado || e.PROCESOS_GRADO || '',\\n ACTIVIDADES_FORMACION: e.actividades_formacion || e.ACTIVIDADES_FORMACION || '',\\n fecha_inicio_ts: e.fecha_inicio_ts ?? null,\\n score: e.score ?? null,\\n }));\\n}\\n\\n// Señal de “demasiadas coincidencias” y facetas sugeridas (si vienen del buscador)\\nconst demasiadas = Boolean($json.demasiadas_coincidencias);\\nconst filtros = $json.filtros_sugeridos || null;\\n\\n// === Funciones auxiliares ===\\nfunction safe(v) { return (v == null ? '' : String(v)); }\\n\\nfunction fmtFecha(ts) {\\n if (ts == null) return '';\\n try {\\n const d = new Date(Number(ts));\\n if (isNaN(d.getTime())) return '';\\n const dd = String(d.getDate()).padStart(2, '0');\\n const mm = String(d.getMonth() + 1).padStart(2, '0');\\n const yyyy = d.getFullYear();\\n return `${yyyy}-${mm}-${dd}`;\\n } catch { return ''; }\\n}\\n\\n// === Determinar PAO actual según la fecha del sistema ===\\nconst ahora = new Date();\\nconst mesActual = ahora.getMonth() + 1;\\nconst anioActual = ahora.getFullYear();\\n\\nlet paoActual = '';\\nif (mesActual >= 5 && mesActual <= 9) paoActual = 'PAO I';\\nelse if (mesActual >= 9 || mesActual <= 2) paoActual = 'PAO II';\\nelse paoActual = 'Vacaciones o PAE';\\n\\nconst contextoTiempo = `📆 Fecha actual: ${anioActual}-${String(mesActual).padStart(2, '0')} (${paoActual} en curso)`;\\n\\n// === Ordenar eventos por relevancia y fecha ===\\nconst eventosOrdenados = [...eventos].sort((a, b) => {\\n const sa = (a.score == null) ? -Infinity : Number(a.score);\\n const sb = (b.score == null) ? -Infinity : Number(b.score);\\n if (sb !== sa) return sb - sa;\\n\\n const ta = (a.fecha_inicio_ts == null) ? Number.POSITIVE_INFINITY : Number(a.fecha_inicio_ts);\\n const tb = (b.fecha_inicio_ts == null) ? Number.POSITIVE_INFINITY : Number(b.fecha_inicio_ts);\\n return ta - tb;\\n});\\n\\nlet contextoCalendario = '';\\n\\nif (eventosOrdenados.length > 0) {\\n contextoCalendario = '📅 He encontrado estas coincidencias (ordenadas por relevancia):\\\\n\\\\n';\\n\\n // Mostrar solo el top 10\\n const toShow = eventosOrdenados.slice(0, 10);\\n\\n contextoCalendario += toShow.map((ev, idx) => {\\n const periodo = safe(ev.PERIODO_FECHAS || ev.periodo);\\n const ag = safe(ev.ACTIVIDADES_GRADO || ev.actividades_grado);\\n const pg = safe(ev.PROCESOS_GRADO || ev.procesos_grado);\\n const af = safe(ev.ACTIVIDADES_FORMACION || ev.actividades_formacion);\\n const fechaISO = fmtFecha(ev.fecha_inicio_ts);\\n const score = (ev.score != null) ? Number(ev.score).toFixed(3) : '';\\n\\n let info = `${idx + 1}. 📌 ${periodo || '(sin fecha)'}`;\\n if (fechaISO) info += `\\\\n 🗓️ Inicio (estimado): ${fechaISO}`;\\n if (ag.trim()) info += `\\\\n 🎓 Actividades de Grado: ${ag}`;\\n if (pg.trim()) info += `\\\\n 📋 Procesos: ${pg}`;\\n if (af.trim()) info += `\\\\n 🔧 Formación Técnica: ${af}`;\\n if (score) info += `\\\\n 🔎 score:${score}`;\\n return info;\\n }).join('\\\\n\\\\n');\\n\\n // Sugerencias si hay demasiadas coincidencias\\n if (demasiadas) {\\n const tips = [];\\n if (filtros?.posibles_anios?.length) tips.push(`• especifica año: ${filtros.posibles_anios.slice(-3).join(' / ')}`);\\n if (filtros?.posibles_meses?.length) tips.push(`• añade mes: ${filtros.posibles_meses.slice(0, 4).join(' / ')}`);\\n if (filtros?.posibles_tipos_evaluacion?.length) tips.push(`• tipo de evaluación: ${filtros.posibles_tipos_evaluacion.join(' / ')}`);\\n if (filtros?.posibles_ciclos?.length) tips.push(`• ciclo: ${filtros.posibles_ciclos.join(' / ')}`);\\n\\n if (tips.length) {\\n contextoCalendario += '\\\\n\\\\n⚠️ Hay muchas coincidencias. Sugerencias para refinar:\\\\n' + tips.join('\\\\n');\\n }\\n }\\n\\n} else {\\n contextoCalendario = 'No encontré información específica en el calendario académico para tu consulta.';\\n}\\n\\n// === Reglas de interpretación PAO/PAE ===\\nconst reglasPAO = `\\nREGLAS DE INTERPRETACIÓN (PAO/PAE y feriados):\\n• Si un evento dice “vacaciones” y la fecha cae ENTRE finales de febrero y los primeros días de mayo ⇒ corresponde a VACACIONES del PAO II.\\n• Desde inicios de mayo hasta inicios/mediados de septiembre ⇒ corresponde a PAO I.\\n• Si un evento cae entre finales de septiembre y la 1.ª o 2.ª semana de febrero ⇒ corresponde a PAO II (período lectivo).\\n• En PAO II, si aparecen “vacaciones estudiantiles” del 28 de diciembre al 1 de enero ⇒ son feriado (no vacaciones entre PAOs).\\n• PAE (Programa de Acompañamiento/Evaluación) ocurre normalmente desde inicios de marzo hasta finales de abril o inicios de mayo.\\n• Si dentro de un PAO aparece “vacaciones”, interprétalas como feriados específicos, no como cambio de PAO.\\n• Si el evento no indica explícitamente PAO I o II, infiérelo con estas reglas. Si hay ambigüedad o la fecha cae fuera de rango, indica que no hay información específica.\\n`.trim();\\n\\n// === Construcción final del prompt ===\\nconst prompt = `Eres un asistente de ESPOL especializado en calendario académico.\\n\\n${contextoTiempo}\\n\\nPregunta del estudiante:\\n\\\"${preguntaUsuario}\\\"\\n\\n${contextoCalendario}\\n\\n${reglasPAO}\\n\\nINSTRUCCIONES IMPORTANTES (ESTRICTAS):\\n1) Si existe la lista anterior, elige SOLO 1 evento que sea la MEJOR COINCIDENCIA para la pregunta.\\n • Considera intención (evaluación/vacaciones/inicio/fin), ordinal (primera/segunda/tercera),\\n y año/mes implícitos o explícitos.\\n • Si ningún evento es claramente pertinente, responde que NO hay información específica.\\n2) No inventes datos. No cites eventos que no estén arriba.\\n3) Si das un resultado, preséntalo claro y breve con emojis, destacando FECHA y ACTIVIDAD.\\n4) Si NO hay información específica, sugiere contactar a:\\n 📧 Email: admision@espol.edu.ec\\n 📞 Teléfono: (04) 2269-269\\n 🌐 Web: https://www.espol.edu.ec\\n5) Si identificas el PAO (I o II) por las fechas, indícalo entre paréntesis o nota breve (“según fechas corresponde al PAO I/II”).\\n6) Responde de forma clara, organizada y útil.`;\\n\\n// === Salida para el siguiente nodo (Gemini) ===\\nreturn [{\\n json: {\\n prompt,\\n chat_id: chatId\\n }\\n}];\\n\"},\"typeVersion\":2},{\"id\":\"728f012c-ceed-400d-a643-8f1353d9f8f1\",\"name\":\"Message a model1\",\"type\":\"@n8n/n8n-nodes-langchain.googleGemini\",\"position\":[-800,2160],\"parameters\":{\"modelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"models/gemini-2.5-flash-preview-05-20\",\"cachedResultName\":\"models/gemini-2.5-flash-preview-05-20\"},\"options\":{\"temperature\":0.3,\"maxOutputTokens\":200000000},\"messages\":{\"values\":[{\"content\":\"={{ $json.prompt }}\"}]},\"simplify\":false},\"typeVersion\":1},{\"id\":\"4af01328-9345-4714-a79d-ea81b2a16a38\",\"name\":\"Limpiar_Texto_Gemini1\",\"type\":\"n8n-nodes-base.code\",\"position\":[-480,2160],\"parameters\":{\"jsCode\":\"// ---- 1) Extracción robusta del texto de Gemini ----\\nfunction extraerTextoGemini(payload) {\\n // Formato más común: candidates[0].content.parts[*].text\\n try {\\n const parts = payload?.candidates?.[0]?.content?.parts;\\n if (Array.isArray(parts) && parts.length > 0) {\\n // Concatenar todos los parts .text\\n const textos = parts\\n .map(p => (typeof p?.text === 'string' ? p.text : ''))\\n .filter(Boolean);\\n if (textos.length) return textos.join('\\\\n').trim();\\n }\\n } catch {}\\n\\n // Alternativos:\\n if (typeof payload?.text === 'string' && payload.text.trim()) {\\n return payload.text.trim();\\n }\\n\\n if (Array.isArray(payload?.content?.parts) && payload.content.parts.length > 0) {\\n const textos2 = payload.content.parts\\n .map(p => (typeof p?.text === 'string' ? p.text : ''))\\n .filter(Boolean);\\n if (textos2.length) return textos2.join('\\\\n').trim();\\n }\\n\\n // Último recurso: stringify recortado\\n try {\\n const s = JSON.stringify(payload);\\n if (s && s.length) return s.substring(0, 8000);\\n } catch {}\\n\\n return 'Lo siento, no pude procesar tu consulta.';\\n}\\n\\nconst respuestaGemini = extraerTextoGemini($json);\\n\\n// ---- 2) Recuperar chat_id desde varios nodos/ubicaciones ----\\nlet chatId = $json.chat_id;\\n\\nif (!chatId) {\\n // Tu prompt actual\\n try { chatId = $('Construir_Prompt_Calendario1').first()?.json?.chat_id; } catch {}\\n}\\nif (!chatId) {\\n // Nombre anterior\\n try { chatId = $('Construir_Prompt_Calendario').first()?.json?.chat_id; } catch {}\\n}\\nif (!chatId) {\\n try { chatId = $('Buscar_Eventos_Calendario').first()?.json?.chat_id; } catch {}\\n}\\nif (!chatId) {\\n try { chatId = $('Detector_Calendario_Pre').first()?.json?.chat_id; } catch {}\\n}\\nif (!chatId) {\\n // Telegram Trigger\\n try { chatId = $('Telegram Trigger - Inicio').first()?.json?.message?.chat?.id; } catch {}\\n}\\n\\n// ---- 3) Limpieza / saneamiento para enviar por Telegram con parse_mode HTML ----\\nfunction escapeHTML(s) {\\n // Evita que Telegram interprete etiquetas si usas parse_mode: \\\"HTML\\\"\\n return s.replace(/&/g, '&')\\n .replace(//g, '>');\\n}\\n\\nfunction limpiarRespuesta(texto) {\\n if (!texto) return 'Lo siento, no obtuve una respuesta válida.';\\n\\n // Eliminar bloques de código ```...``` (incluye variantes con lenguaje)\\n texto = texto.replace(/```[\\\\s\\\\S]*?```/g, '');\\n\\n // Eliminar comillas invertidas inline `\\n texto = texto.replace(/`+/g, '');\\n\\n // Convertir enlaces markdown [texto](url) → \\\"texto (url)\\\"\\n texto = texto.replace(/\\\\[([^\\\\]]+)\\\\]\\\\((https?:\\\\/\\\\/[^\\\\s)]+)\\\\)/g, '$1 ($2)');\\n\\n // Quitar markdown simple de estilo: **negritas**, *itálicas*, __subrayado__ _\\n texto = texto.replace(/\\\\*\\\\*(.*?)\\\\*\\\\*/g, '$1')\\n .replace(/\\\\*(.*?)\\\\*/g, '$1')\\n .replace(/__(.*?)__/g, '$1')\\n .replace(/_(.*?)_/g, '$1');\\n\\n // Quitar encabezados markdown (##, ###, etc.)\\n texto = texto.replace(/^\\\\s{0,3}#{1,6}\\\\s+/gm, '');\\n\\n // Normalizar saltos y espacios\\n texto = texto.replace(/\\\\r/g, '')\\n .replace(/\\\\n{3,}/g, '\\\\n\\\\n')\\n .replace(/[ \\\\t]+\\\\n/g, '\\\\n')\\n .trim();\\n\\n // Escapar HTML para Telegram (parse_mode: \\\"HTML\\\")\\n texto = escapeHTML(texto);\\n\\n // Límite prudente para Telegram (4096 es el duro). Dejamos margen.\\n const LIMITE = 3500;\\n if (texto.length > LIMITE) {\\n texto = texto.substring(0, LIMITE - 20).trimEnd() + '… (mensaje acortado)';\\n }\\n\\n return texto;\\n}\\n\\nconst textoLimpio = limpiarRespuesta(respuestaGemini);\\n\\n// ---- 4) Logs útiles ----\\nconsole.log(`========================================`);\\nconsole.log(`🧹 LIMPIEZA DE TEXTO`);\\nconsole.log(`Chat ID encontrado: ${chatId}`);\\nconsole.log(`Texto original (100): ${String(respuestaGemini).substring(0, 100)}...`);\\nconsole.log(`Texto limpio (100): ${textoLimpio.substring(0, 100)}...`);\\nconsole.log(`========================================`);\\n\\n// ---- 5) Salida ----\\nreturn [{\\n json: {\\n texto_limpio: textoLimpio,\\n chat_id: chatId,\\n respuesta_original: respuestaGemini\\n }\\n}];\"},\"typeVersion\":2},{\"id\":\"84c7ffb2-d72d-432a-ac54-9892d31ac5b9\",\"name\":\"Enviar Respuesta sobre calendario1\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-240,2160],\"webhookId\":\"c4b9e9ad-3d55-4653-b1eb-e4621c6425d8\",\"parameters\":{\"text\":\"={{ $json.texto_limpio }}\\n\\n💬 ¿Deseas revisar otra consulta o hacer una nueva pregunta?\",\"chatId\":\"={{ $json.chat_id }}\",\"replyMarkup\":\"inlineKeyboard\",\"inlineKeyboard\":{\"rows\":[{\"row\":{\"buttons\":[{\"text\":\"👍 Sí\",\"additionalFields\":{\"callback_data\":\"=feedback_yes\"}},{\"text\":\"👎 No\",\"additionalFields\":{\"callback_data\":\"=feedback_no\"}}]}}]},\"additionalFields\":{\"parse_mode\":\"HTML\",\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"144e290f-5f0a-400b-b82b-269d90d5f32a\",\"name\":\"Calendario Académico\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[-1520,2160],\"parameters\":{\"options\":{\"outputFormatting\":{\"values\":{\"date\":\"FORMATTED_STRING\",\"general\":\"UNFORMATTED_VALUE\"}},\"returnFirstMatch\":false},\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":1817620056,\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit#gid=1817620056\",\"cachedResultName\":\"CALENDAR\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit?usp=drivesdk\",\"cachedResultName\":\"BASE-DATOS-FAQ_ESPOL\"}},\"typeVersion\":4.7},{\"id\":\"21267be1-e42b-4362-aefc-42bf96705258\",\"name\":\"Buscar_Eventos_Calendario1\",\"type\":\"n8n-nodes-base.code\",\"position\":[-1264,2160],\"parameters\":{\"jsCode\":\"const detectorItems = $('Detector_Calendario_Pre').all();\\nconst detector =\\n Array.isArray(detectorItems) && detectorItems.length > 0\\n ? detectorItems[0].json\\n : {};\\nconst preguntaUsuario = detector.pregunta_usuario || '';\\nconst chatId = detector.chat_id ?? null;\\nconst filas = $input.all().map(it => it.json || {});\\n\\nconst HOY = new Date();\\nconst ANIO_ACTUAL = HOY.getFullYear();\\nconst ANIO_SIG = ANIO_ACTUAL + 1;\\n\\n// ---------- helpers ----------\\nfunction limpiarTexto(t) {\\n if (!t) return '';\\n return String(t)\\n .toLowerCase()\\n .normalize('NFD').replace(/[\\\\u0300-\\\\u036f]/g, '')\\n .replace(/[^a-z0-9ñ\\\\s]/gi, ' ')\\n .replace(/\\\\s+/g, ' ')\\n .trim();\\n}\\n\\nconst STOP = new Set([\\n \\\"de\\\",\\\"la\\\",\\\"que\\\",\\\"el\\\",\\\"en\\\",\\\"y\\\",\\\"a\\\",\\\"los\\\",\\\"del\\\",\\\"se\\\",\\\"las\\\",\\\"por\\\",\\\"un\\\",\\\"para\\\",\\\"con\\\",\\\"no\\\",\\\"una\\\",\\n \\\"su\\\",\\\"al\\\",\\\"lo\\\",\\\"como\\\",\\\"mas\\\",\\\"más\\\",\\\"pero\\\",\\\"sus\\\",\\\"le\\\",\\\"ya\\\",\\\"o\\\",\\\"fue\\\",\\\"ha\\\",\\\"si\\\",\\\"sí\\\",\\\"porque\\\",\\n \\\"muy\\\",\\\"sin\\\",\\\"sobre\\\",\\\"tambien\\\",\\\"también\\\",\\\"entre\\\",\\\"cuando\\\",\\\"todo\\\",\\\"esta\\\",\\\"está\\\",\\\"ser\\\",\\\"son\\\",\\n \\\"dos\\\",\\\"han\\\",\\\"hay\\\",\\\"donde\\\",\\\"quien\\\",\\\"quién\\\",\\\"desde\\\",\\\"cada\\\",\\\"cual\\\",\\\"cuál\\\",\\\"cuales\\\",\\\"cuáles\\\"\\n]);\\nfunction tokenizar(t) { return limpiarTexto(t).split(' ').filter(x => x && x.length > 2 && !STOP.has(x)); }\\n\\nfunction baseEs(w) {\\n w = limpiarTexto(w);\\n if (!w) return '';\\n w = w.replace(/\\\\b1(ra|era)\\\\b/g, 'primera')\\n .replace(/\\\\b2da\\\\b/g, 'segunda')\\n .replace(/\\\\b3ra\\\\b/g, 'tercera');\\n if (w.endsWith('es')) w = w.slice(0, -2);\\n else if (w.endsWith('s')) w = w.slice(0, -1);\\n w = w.replace(/evaluacione?$/,'evaluacion');\\n return w;\\n}\\nfunction matchToken(userTok, rowTok) {\\n const u = baseEs(userTok), r = baseEs(rowTok);\\n if (!u || !r) return false;\\n if (u === r) return true;\\n if (u.length >= 5 && (r.includes(u) || u.includes(r))) return true;\\n return false;\\n}\\n\\nfunction detectarIntencion(pregunta) {\\n const p = limpiarTexto(pregunta);\\n if (/(vacaciones|receso|feriado|descanso)/.test(p)) return \\\"vacaciones\\\";\\n if (/(evaluacion|evaluación|examen|parcial|prueba|evaluar|evaluaciones)/.test(p)) return \\\"evaluacion\\\";\\n if (/(inicio|empieza|matriculacion|matriculación|induccion|inducción|apertura|arranque)/.test(p)) return \\\"inicio\\\";\\n if (/(final|fin|cierre|termina|culmina|conclusion|conclusión)/.test(p)) return \\\"fin\\\";\\n if (/(eleccion|elección|votacion|votación)/.test(p)) return \\\"elecciones\\\";\\n return \\\"otro\\\";\\n}\\nfunction detectarOrdinal(p) {\\n const t = limpiarTexto(p);\\n if (/\\\\b(primera|1ra|1era)\\\\b/.test(t) || /\\\\bevaluacion\\\\s*i\\\\b/.test(t)) return 1;\\n if (/\\\\b(segunda|2da)\\\\b/.test(t) || /\\\\bevaluacion\\\\s*ii\\\\b/.test(t)) return 2;\\n if (/\\\\b(tercera|3ra)\\\\b/.test(t) || /\\\\bevaluacion\\\\s*iii\\\\b/.test(t)) return 3;\\n return 0;\\n}\\n\\nconst MESES = { ene:0, enero:0, feb:1, febrero:1, mar:2, marzo:2, abr:3, abril:3, may:4, mayo:4, jun:5, junio:5, jul:6, julio:6, ago:7, agosto:7, sep:8, sept:8, septiembre:8, oct:9, octubre:9, nov:10, noviembre:10, dic:11, diciembre:11 };\\n\\nfunction normalizarPeriodo(p) {\\n if (!p) return '';\\n return String(p).replace(/([0-9])([a-zA-Z])/g, '$1 $2').replace(/\\\\s*-\\\\s*/g, ' - ').replace(/\\\\s+/g, ' ').trim();\\n}\\nfunction parseFechaInicio(periodo) {\\n const txt = normalizarPeriodo(periodo).toLowerCase();\\n\\n // \\\"13 - 17 julio 2026\\\"\\n let m = /(\\\\d{1,2})\\\\s*-\\\\s*(\\\\d{1,2})\\\\s+([a-záéíóúñ]+)\\\\s+(\\\\d{4})/.exec(txt);\\n if (m) {\\n const d1 = parseInt(m[1], 10);\\n const mes = MESES[m[3].normalize('NFD').replace(/[\\\\u0300-\\\\u036f]/g, '')];\\n const year = parseInt(m[4], 10);\\n if (mes != null) return new Date(year, mes, d1, 0, 0, 0, 0).getTime();\\n }\\n\\n // \\\"30 marzo - 03 abril 2026\\\"\\n m = /(\\\\d{1,2})\\\\s+([a-záéíóúñ]+)\\\\s*-\\\\s*(\\\\d{1,2})\\\\s+([a-záéíóúñ]+)\\\\s+(\\\\d{4})/.exec(txt);\\n if (m) {\\n const d1 = parseInt(m[1], 10);\\n const mes1 = MESES[m[2].normalize('NFD').replace(/[\\\\u0300-\\\\u036f]/g, '')];\\n const year = parseInt(m[5], 10);\\n if (mes1 != null) return new Date(year, mes1, d1, 0, 0, 0, 0).getTime();\\n }\\n\\n // sin año → asume actual\\n m = /(\\\\d{1,2})\\\\s*-\\\\s*(\\\\d{1,2})\\\\s+([a-záéíóúñ]+)/.exec(txt);\\n if (m) {\\n const d1 = parseInt(m[1], 10);\\n const mes1 = MESES[m[3].normalize('NFD').replace(/[\\\\u0300-\\\\u036f]/g, '')];\\n if (mes1 != null) return new Date(ANIO_ACTUAL, mes1, d1, 0, 0, 0, 0).getTime();\\n }\\n m = /(\\\\d{1,2})\\\\s+([a-záéíóúñ]+)\\\\s*-\\\\s*(\\\\d{1,2})\\\\s+([a-záéíóúñ]+)/.exec(txt);\\n if (m) {\\n const d1 = parseInt(m[1], 10);\\n const mes1 = MESES[m[2].normalize('NFD').replace(/[\\\\u0300-\\\\u036f]/g, '')];\\n if (mes1 != null) return new Date(ANIO_ACTUAL, mes1, d1, 0, 0, 0, 0).getTime();\\n }\\n return null;\\n}\\nfunction extraerAniosTexto(texto) {\\n const t = String(texto || '');\\n const m = t.match(/\\\\b(20\\\\d{2})\\\\b/g);\\n if (!m) return new Set();\\n return new Set(m.map(x => parseInt(x, 10)));\\n}\\nfunction extraerAniosPregunta(p) { return extraerAniosTexto(p); }\\nfunction extraerMesesPregunta(p) {\\n const t = limpiarTexto(p);\\n const meses = new Set();\\n Object.keys(MESES).forEach(k => { if (new RegExp(`\\\\\\\\b${k}\\\\\\\\b`).test(t)) meses.add(MESES[k]); });\\n return meses;\\n}\\nfunction yearFromTs(ts) { if (ts == null) return null; try { return new Date(ts).getFullYear(); } catch { return null; } }\\n\\nconst intencion = detectarIntencion(preguntaUsuario);\\nconst ordinalBuscado = detectarOrdinal(preguntaUsuario);\\nconst tokensUsuario = tokenizar(preguntaUsuario);\\nconst setTokens = new Set(tokensUsuario);\\nconst aniosPregunta = extraerAniosPregunta(preguntaUsuario);\\nconst mesesPregunta = extraerMesesPregunta(preguntaUsuario);\\nconst HARD_FILTER_BY_YEAR = aniosPregunta.size > 0;\\n\\n// ---------- scoring ----------\\nconst PESOS = { PERIODO_FECHAS: 0.8, ACTIVIDADES_GRADO: 1.0, PROCESOS_GRADO: 0.6, ACTIVIDADES_FORMACION: 0.9 };\\nconst BONUS_INTENCION = 2.2;\\nconst BONUS_FRASE_EXACTA = 1.0;\\nconst BONUS_TIENE_EVALUACION = 0.7;\\nconst BONUS_ORDINAL_MATCH = 1.5;\\nconst PENALIZA_ORD_DISTINTO = 0.5;\\nconst PENALIZA_SIN_EVAL_CON_ORD = 0.35;\\n\\nconst BONUS_ANIO_ACTUAL_STRONG = 1.1;\\nconst PENALIZA_ANIO_NO_ACTUAL = 0.6;\\nconst BONUS_MATCH_ANIO_PREGUNTA = 1.2;\\nconst BONUS_MATCH_MES_ACTUAL = 0.6;\\nconst BONUS_ANIO_EXPLICITO = 0.3;\\n\\nconst UMBRAL_SCORE_MIN = 0;\\nconst UMBRAL_DEMASIADAS = 25; // ← si hay más que esto, sugerimos refinar\\n\\nif (!preguntaUsuario || !limpiarTexto(preguntaUsuario)) {\\n return [{ json: { ok:false, motivo:\\\"pregunta_vacia\\\", mensaje:\\\"No se recibió una pregunta (pregunta_usuario).\\\", chat_id:chatId } }];\\n}\\nif (!Array.isArray(filas) || filas.length === 0) {\\n return [{ json: { ok:false, motivo:\\\"sin_datos\\\", mensaje:\\\"No llegaron filas desde Google Sheets.\\\", chat_id:chatId } }];\\n}\\n\\nfunction filaTokens(row) {\\n const F = (k) => { const v = row[k]; return (v == null) ? '' : String(v); };\\n const actTecKey = 'ACTIVIDADES DE FORMACIÓN TÉCNICA Y TECNOLÓGICA';\\n const campos = {\\n row_number: row.row_number ?? null,\\n PERIODO_FECHAS: F('PERIODO_FECHAS'),\\n ACTIVIDADES_GRADO: F('ACTIVIDADES_GRADO'),\\n PROCESOS_GRADO: F('PROCESOS_GRADO'),\\n ACTIVIDADES_FORMACION: F(actTecKey) || F('ACTIVIDADES_FORMACION') || ''\\n };\\n const textoTotal = [campos.PERIODO_FECHAS, campos.ACTIVIDADES_GRADO, campos.PROCESOS_GRADO, campos.ACTIVIDADES_FORMACION].filter(Boolean).join(' | ');\\n const normTotal = limpiarTexto(textoTotal);\\n const toks = {\\n PERIODO_FECHAS: tokenizar(campos.PERIODO_FECHAS),\\n ACTIVIDADES_GRADO: tokenizar(campos.ACTIVIDADES_GRADO),\\n PROCESOS_GRADO: tokenizar(campos.PROCESOS_GRADO),\\n ACTIVIDADES_FORMACION: tokenizar(campos.ACTIVIDADES_FORMACION),\\n TOTAL: tokenizar(textoTotal)\\n };\\n const aniosTexto = extraerAniosTexto(textoTotal);\\n const tsInicio = parseFechaInicio(campos.PERIODO_FECHAS);\\n const anioTs = yearFromTs(tsInicio);\\n const aniosFila = new Set(aniosTexto);\\n if (anioTs != null) aniosFila.add(anioTs);\\n let mesInicio = null;\\n if (tsInicio != null) mesInicio = new Date(tsInicio).getMonth();\\n\\n return { campos, textoTotal, normTotal, toks, aniosFila, tsInicio, mesInicio };\\n}\\nfunction filaTieneOrdinalEvaluacion(norm) {\\n const hasEval = /\\\\bevaluacion\\\\b/.test(norm);\\n const primera = hasEval && (/\\\\bprimera\\\\b/.test(norm) || /\\\\bevaluacion\\\\s*i\\\\b/.test(norm) || /\\\\bi\\\\s*evaluacion\\\\b/.test(norm));\\n const segunda = hasEval && (/\\\\bsegunda\\\\b/.test(norm) || /\\\\bevaluacion\\\\s*ii\\\\b/.test(norm) || /\\\\bii\\\\s*evaluacion\\\\b/.test(norm));\\n const tercera = hasEval && (/\\\\btercera\\\\b/.test(norm) || /\\\\bevaluacion\\\\s*iii\\\\b/.test(norm) || /\\\\biii\\\\s*evaluacion\\\\b/.test(norm));\\n return { hasEval, primera, segunda, tercera };\\n}\\nfunction intersect(setA, setB) { for (const x of setA) if (setB.has(x)) return true; return false; }\\n\\nfunction puntuar(row) {\\n const { campos, textoTotal, normTotal, toks, aniosFila, tsInicio, mesInicio } = filaTokens(row);\\n if (!normTotal) return null;\\n\\n if (HARD_FILTER_BY_YEAR) {\\n if (aniosFila.size > 0 && !intersect(aniosFila, aniosPregunta)) return null;\\n // si no hay año en la fila, la dejamos pasar con score bajo (puedes excluirla retornando null)\\n }\\n\\n let score = 0, coincidencias = 0;\\n const matchPorCampo = { PERIODO_FECHAS: [], ACTIVIDADES_GRADO: [], PROCESOS_GRADO: [], ACTIVIDADES_FORMACION: [] };\\n const matchTokens = [];\\n\\n for (const t of setTokens) {\\n let hit = false;\\n for (const campo of Object.keys(PESOS)) {\\n const arr = toks[campo];\\n if (arr && arr.some(rt => matchToken(t, rt))) {\\n score += PESOS[campo];\\n matchPorCampo[campo].push(t);\\n hit = true;\\n }\\n }\\n if (hit) { coincidencias++; matchTokens.push(t); }\\n }\\n\\n const INTENT_TERMS = {\\n vacaciones: [\\\"vacaciones\\\",\\\"receso\\\",\\\"feriado\\\",\\\"descanso\\\",\\\"estudiantiles\\\"],\\n evaluacion: [\\\"evaluacion\\\",\\\"evaluaciones\\\",\\\"examen\\\",\\\"parcial\\\",\\\"prueba\\\",\\\"ciclo\\\",\\\"semana de evaluacion\\\"],\\n inicio: [\\\"inicio\\\",\\\"empieza\\\",\\\"apertura\\\",\\\"induccion\\\",\\\"matriculacion\\\",\\\"novatos\\\"],\\n fin: [\\\"final\\\",\\\"fin\\\",\\\"cierre\\\",\\\"termina\\\",\\\"culmina\\\",\\\"conclusion\\\",\\\"proceso final\\\"],\\n elecciones: [\\\"eleccion\\\",\\\"votacion\\\"]\\n };\\n if (intencion !== 'otro') {\\n const terms = INTENT_TERMS[intencion] || [];\\n if (terms.some(term => normTotal.includes(limpiarTexto(term)))) score += BONUS_INTENCION;\\n }\\n\\n const ord = filaTieneOrdinalEvaluacion(normTotal);\\n if (intencion === 'evaluacion' && ord.hasEval) score += BONUS_TIENE_EVALUACION;\\n if (ordinalBuscado) {\\n const ok = (ordinalBuscado === 1 && ord.primera) || (ordinalBuscado === 2 && ord.segunda) || (ordinalBuscado === 3 && ord.tercera);\\n if (ok) score += BONUS_ORDINAL_MATCH;\\n else {\\n if (ord.primera || ord.segunda || ord.tercera) score -= PENALIZA_ORD_DISTINTO;\\n if (!ord.hasEval) score -= PENALIZA_SIN_EVAL_CON_ORD;\\n }\\n }\\n\\n if (HARD_FILTER_BY_YEAR) {\\n if (aniosFila.size > 0 && intersect(aniosFila, aniosPregunta)) score += BONUS_MATCH_ANIO_PREGUNTA;\\n } else {\\n if (aniosFila.size > 0) {\\n if (aniosFila.has(ANIO_ACTUAL)) score += BONUS_ANIO_ACTUAL_STRONG;\\n else score -= PENALIZA_ANIO_NO_ACTUAL;\\n }\\n }\\n\\n if (mesesPregunta.size > 0 && mesInicio != null) {\\n if (mesesPregunta.has(mesInicio)) {\\n if (!HARD_FILTER_BY_YEAR && (aniosFila.size === 0 || aniosFila.has(ANIO_ACTUAL))) score += BONUS_MATCH_MES_ACTUAL;\\n else score += BONUS_MATCH_MES_ACTUAL * 0.6;\\n }\\n }\\n\\n if (/\\\\b20\\\\d{2}\\\\b/.test(normTotal)) score += BONUS_ANIO_EXPLICITO;\\n\\n const frase = limpiarTexto(preguntaUsuario);\\n if (frase && normTotal.includes(frase)) score += BONUS_FRASE_EXACTA;\\n\\n const len = normTotal.split(' ').length || 1;\\n score = score / Math.pow(len, 0.03);\\n\\n return {\\n row_number: campos.row_number,\\n PERIODO_FECHAS: campos.PERIODO_FECHAS,\\n ACTIVIDADES_GRADO: campos.ACTIVIDADES_GRADO,\\n PROCESOS_GRADO: campos.PROCESOS_GRADO,\\n ACTIVIDADES_FORMACION: campos.ACTIVIDADES_FORMACION,\\n preview: textoTotal,\\n score: Number(score.toFixed(4)),\\n coincidencias,\\n match_tokens: matchTokens,\\n match_por_campo: matchPorCampo,\\n fecha_inicio_ts: tsInicio,\\n mes_inicio: mesInicio,\\n anios_fila: [...aniosFila]\\n };\\n}\\n\\n// ---------- ejecutar y ordenar ----------\\nconst evaluadas = [];\\nfor (const row of filas) {\\n const r = puntuar(row);\\n if (!r) continue;\\n if (r.score > UMBRAL_SCORE_MIN || r.coincidencias > 0) evaluadas.push(r);\\n}\\n\\nevaluadas.sort((a, b) => {\\n if (b.score !== a.score) return b.score - a.score;\\n if (b.coincidencias !== a.coincidencias) return b.coincidencias - a.coincidencias;\\n const ta = a.fecha_inicio_ts ?? Number.POSITIVE_INFINITY;\\n const tb = b.fecha_inicio_ts ?? Number.POSITIVE_INFINITY;\\n return ta - tb;\\n});\\n\\n// chat_ids válidos (si existen en la data)\\nconst chatIds = $input.all()\\n .map(it => it.json?.CHAT_ID)\\n .filter(id => id !== undefined && id !== null && String(id).trim() !== '')\\n .map(id => String(id).trim());\\nconst chat_ids_validos = [...new Set(chatIds)];\\n\\n// ---------- sin resultados ----------\\nif (evaluadas.length === 0) {\\n const sugerencias = { email: \\\"admision@espol.edu.ec\\\", telefono: \\\"(04) 2269-269\\\", web: \\\"https://www.espol.edu.ec\\\" };\\n const yearInfo = aniosPregunta.size > 0 ? ` para el/los año(s): ${[...aniosPregunta].join(', ')}` : ` para el año ${ANIO_ACTUAL}`;\\n const mensaje = [\\n `😕 No encontré información específica${yearInfo}.`,\\n \\\"Puedes comunicarte por:\\\",\\n `📧 ${sugerencias.email}`,\\n `📞 ${sugerencias.telefono}`,\\n `🌐 ${sugerencias.web}`\\n ].join('\\\\n');\\n\\n return [{ json: {\\n ok: false,\\n consulta: preguntaUsuario,\\n intencion_detectada: intencion,\\n mensaje,\\n sugerencias_contacto: sugerencias,\\n chat_id: chatId,\\n chat_ids_validos\\n }}];\\n}\\n\\n// ---------- construir sugerencias si hay demasiadas coincidencias ----------\\nfunction nombreMes(idx) {\\n const nombres = ['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre'];\\n return (idx >=0 && idx <=11) ? nombres[idx] : null;\\n}\\nfunction recolectarFacetas(rows) {\\n const anios = new Set();\\n const meses = new Set();\\n const tiposEval = new Set(); // primera/segunda/tercera\\n const ciclos = new Set(); // Ciclo 1/2/3\\n\\n for (const r of rows) {\\n (r.anios_fila || []).forEach(y => anios.add(y));\\n if (typeof r.mes_inicio === 'number') meses.add(r.mes_inicio);\\n\\n const norm = limpiarTexto(`${r.PERIODO_FECHAS} ${r.ACTIVIDADES_GRADO} ${r.PROCESOS_GRADO} ${r.ACTIVIDADES_FORMACION}`);\\n if (/\\\\bprimera\\\\b/.test(norm) || /\\\\bevaluacion\\\\s*i\\\\b/.test(norm)) tiposEval.add('primera');\\n if (/\\\\bsegunda\\\\b/.test(norm) || /\\\\bevaluacion\\\\s*ii\\\\b/.test(norm)) tiposEval.add('segunda');\\n if (/\\\\btercera\\\\b/.test(norm) || /\\\\bevaluacion\\\\s*iii\\\\b/.test(norm)) tiposEval.add('tercera');\\n\\n const m = norm.match(/\\\\bciclo\\\\s*(1|2|3)\\\\b/);\\n if (m) ciclos.add(`Ciclo ${m[1]}`);\\n }\\n\\n return {\\n anios: [...anios].sort((a,b)=>a-b),\\n meses: [...meses].sort((a,b)=>a-b).map(nombreMes).filter(Boolean),\\n tiposEval: [...tiposEval],\\n ciclos: [...ciclos]\\n };\\n}\\n\\nlet sugerencia_reformulacion = null;\\nlet filtros_sugeridos = null;\\nconst DEMASIADAS = evaluadas.length > UMBRAL_DEMASIADAS;\\n\\nif (DEMASIADAS) {\\n const facetas = recolectarFacetas(evaluadas);\\n filtros_sugeridos = {\\n posibles_anios: facetas.anios,\\n posibles_meses: facetas.meses,\\n posibles_tipos_evaluacion: facetas.tiposEval,\\n posibles_ciclos: facetas.ciclos\\n };\\n\\n const tips = [];\\n if (facetas.anios.length > 0) tips.push(`• especifica año: **${facetas.anios.slice(-3).join(' / ')}**`);\\n if (facetas.meses.length > 0) tips.push(`• añade mes: **${facetas.meses.slice(0,4).join(' / ')}**`);\\n if (facetas.tiposEval.length > 0) tips.push(`• tipo de evaluación: **${facetas.tiposEval.join(' / ')}**`);\\n if (facetas.ciclos.length > 0) tips.push(`• ciclo: **${facetas.ciclos.join(' / ')}**`);\\n\\n // ejemplo guiado\\n const ejemplo = [];\\n if (intencion === 'evaluacion') {\\n const ejA = facetas.anios[0] ?? ANIO_ACTUAL;\\n const ejMes = facetas.meses[0] ?? 'julio';\\n ejemplo.push(`Ej.: \\\"¿Cuándo es la **primera evaluación** de **${ejMes} ${ejA}** en PAE?\\\"`);\\n } else if (facetas.meses.length > 0 || facetas.anios.length > 0) {\\n const ejA = facetas.anios[0] ?? ANIO_ACTUAL;\\n const ejMes = facetas.meses[0] ?? 'abril';\\n ejemplo.push(`Ej.: \\\"Actividades formativas de **${ejMes} ${ejA}**\\\"`);\\n }\\n\\n sugerencia_reformulacion =\\n `🔎 He encontrado **${evaluadas.length}** coincidencias. ` +\\n `Para llegar más rápido a lo que necesitas, prueba a refinar tu pregunta:\\\\n` +\\n (tips.length ? tips.join('\\\\n') + '\\\\n' : '') +\\n (ejemplo.length ? ejemplo.join('\\\\n') : '');\\n}\\n\\n// ---------- mensaje formateado (todas las coincidencias) ----------\\nconst encabezado = `📅 Encontré ${evaluadas.length} coincidencia(s) para:\\\\n“${preguntaUsuario}”`;\\nconst cuerpo = evaluadas.map((e, i) => {\\n const partes = [];\\n partes.push(`${i+1}. 📌 ${e.PERIODO_FECHAS || '(sin fecha)'}`);\\n if (e.ACTIVIDADES_GRADO?.trim()) partes.push(` 🎓 Actividades de Grado: ${e.ACTIVIDADES_GRADO}`);\\n if (e.PROCESOS_GRADO?.trim()) partes.push(` 📋 Procesos: ${e.PROCESOS_GRADO}`);\\n if (e.ACTIVIDADES_FORMACION?.trim()) partes.push(` 🔧 Formación Técnica: ${e.ACTIVIDADES_FORMACION}`);\\n return partes.join('\\\\n');\\n}).join('\\\\n\\\\n');\\n\\nconst mensaje_formateado = sugerencia_reformulacion\\n ? `${encabezado}\\\\n\\\\n${cuerpo}\\\\n\\\\n${sugerencia_reformulacion}`\\n : `${encabezado}\\\\n\\\\n${cuerpo}`;\\n\\nreturn [{\\n json: {\\n ok: true,\\n consulta: preguntaUsuario,\\n intencion_detectada: intencion,\\n ordinal_detectado: detectarOrdinal(preguntaUsuario) || null,\\n anios_detectados_en_pregunta: [...aniosPregunta],\\n meses_detectados_en_pregunta: [...mesesPregunta],\\n total_evaluadas: filas.length,\\n total_encontrados: evaluadas.length,\\n demasiadas_coincidencias: DEMASIADAS,\\n umbral_demasiadas: UMBRAL_DEMASIADAS,\\n filtros_sugeridos, // ← facetas para construir botones/quick-replies si quieres\\n resultados: evaluadas, // ← TODAS las coincidencias ordenadas\\n mensaje_formateado,\\n chat_id: chatId,\\n chat_ids_validos: chat_ids_validos\\n }\\n}];\"},\"typeVersion\":2},{\"id\":\"2f04c332-95f8-4251-a7d8-c3183c3bf341\",\"name\":\"Mensaje Help\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-880,608],\"webhookId\":\"cec2b109-dbe4-4246-a86e-ab226fd460a7\",\"parameters\":{\"text\":\"=🤖 Bienvenido al ChatBot ESPOL\\n\\n👋 ¡Hola! Soy ChatBot ESPOL, tu asistente virtual de la Escuela Superior Politécnica del Litoral.\\nEstoy aquí para responder tus preguntas sobre la universidad: matrículas, eventos, horarios, docentes, servicios estudiantiles y mucho más.\\n\\n💬 Solo escribe tu duda y te responderé al instante.\\nPor ejemplo:\\n\\n“¿Cuándo empiezan las matrículas?”\\n“¿Qué eventos hay esta semana?”\\n“¿Dónde puedo contactar a Bienestar Estudiantil?”\\n\\nTambién puedes usar estos comandos:\\n\\n/help – Ver los comandos disponibles\\n\\n/faqs – Acceder a la sección de consultas y preguntas frecuentes\\n\\n/contact – Mostrar contactos y canales oficiales\\n\\n/events – Ver próximos eventos\\n\\n/feedback – Enviar sugerencias o comentarios sobre el bot o los servicios\\n\\n🎓 Tu información, siempre a un mensaje de distancia.\\n¿Sobre qué te gustaría consultar hoy?\",\"chatId\":\"={{ $json.message.chat.id }}\",\"additionalFields\":{\"parse_mode\":\"Markdown\",\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"58882226-f879-4ae5-b653-025ae55e833f\",\"name\":\"BIENVENIDA\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-880,1504],\"webhookId\":\"67736a18-8268-4b0b-a904-77b356cf3059\",\"parameters\":{\"text\":\"=👋🏽 ¡Qué más, politécnico o futuro politécnico! \\n\\nBienvenido al bot oficial de ayuda para toda la comunidad de la ESPOL 🐢💛💙. \\n\\nAquí puedes preguntarme lo que necesites sobre tu vida politécnica o lo que se viene en la U: \\n📅 Fechas importantes del calendario académico. \\n🎓 Preguntas frecuentes de todas las facultades — tanto pregrado como postgrado. \\n🎟️ Info sobre becas, clubes, cursos, eventos, transporte, servicios y más. \\n\\nY pilas 👀, porque cada semana te voy a mandar un recordatorio con lo más relevante que se viene para que no se te pase nada — ni matrícula, ni retiro, ni feriado 😎. Así que tranqui, compa, pregunta nomás.\\n\\n¡Vamos con todo, politécnico! 🚀💪\",\"chatId\":\"={{ $json.message.chat.id }}\",\"additionalFields\":{\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"5f1bf72a-e7f4-405f-a1fc-549008b73747\",\"name\":\"Google Gemini Chat Model\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatGoogleGemini\",\"position\":[-672,1680],\"parameters\":{\"options\":{},\"modelName\":\"models/gemini-2.5-flash-lite\"},\"typeVersion\":1},{\"id\":\"bef601ae-58f3-4785-a49e-4a7225c34ed9\",\"name\":\"BD_ESPOL\",\"type\":\"n8n-nodes-base.googleSheetsTool\",\"position\":[-528,1712],\"parameters\":{\"options\":{},\"sheetName\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('Sheet', ``, 'string') }}\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit?usp=drivesdk\",\"cachedResultName\":\"BASE-DATOS-FAQ_ESPOL\"}},\"typeVersion\":4.7},{\"id\":\"c925a437-914c-4e86-8619-2a670ee53c40\",\"name\":\"PREGUNTAS AL AZAR DE GUIA\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[-672,1504],\"parameters\":{\"text\":\"=El usuario acaba de iniciar el bot con /start.\\nNo le muestres un mensaje de bienvenida.\\nSólo sugiérele 5 preguntas al azar (diferentes cada vez) que podría hacerle al bot, relacionadas con la información que está guardada en BD_ESPOL (preguntas frecuentes de facultades, calendario académico, becas, clubes, cursos, eventos, etc.).\\n\\nEjemplo de formato esperado:\\n\\n👋🏽 ¡Qué más, futuro politécnico! Bienvenido al bot de ayuda de la ESPOL 🐢💛💙\\nAquí puedes preguntar lo que necesites sobre tu vida universitaria o lo que se viene en el semestre.\\n\\nPuedes empezar con algo como:\\n• ¿Cuándo abren las matrículas?\\n• ¿Qué clubes hay en la ESPOL?\\n• ¿Dónde puedo ver las fechas de titulación?\\n• ¿Quien es el coordinador de la FIMCP?\\n• ¿Cuando empiezan las vacaciones del IIPAO 2025?\\n¡Dale nomás, pregunta lo que necesites que el bot te ayuda al instante! 😎\",\"options\":{\"systemMessage\":\"=Eres un asistente politécnico amigable y juvenil, que habla con tono guayaco, relajado y positivo. Estás conectado a una base de datos llamada BD_ESPOL, que contiene información sobre preguntas frecuentes, calendario académico, becas, clubes, cursos, eventos, servicios, vida universitaria, transporte, titulación y reglamentos.\\n\\nTu objetivo es ayudar a los estudiantes y futuros politécnicos a orientarse en la ESPOL.\\n\\nCada vez que un usuario nuevo inicia conversación, no debes volver a saludar, ya que el bot principal ya lo hizo. Solo debes explicarle brevemente cómo puede usar el bot y mostrarle 5 preguntas aleatorias distintas cada vez que podría intentar para descubrir las funciones del bot.\\n\\nEl mensaje debe sonar natural, como si fueras un compañero universitario de Guayaquil, usando expresiones relajadas pero respetuosas.\\nEvita usar asteriscos, puntos o cualquier formato Markdown. Usa guiones (-) para enumerar las preguntas.\\n\\nLas preguntas deben cubrir temas variados: calendario académico, becas, facultades, servicios, transporte, vida universitaria, titulación y eventos.\\nCada vez que respondas, cambia el orden o tipo de preguntas para que no sean las mismas.\\n\\nEjemplo de estilo y estructura:\\nAquí puedes preguntar sobre fechas, becas, clubes o eventos\\nMira, puedes probar con algo como\\n\\n- ¿Cuándo empiezan las clases?\\n\\n- ¿Qué becas hay disponibles?\\n\\n- ¿Dónde veo los cursos extracurriculares?\\n\\n- ¿Qué eventos hay esta semana?\\n\\n- ¿Cómo puedo unirme a un club estudiantil?\\n\\nTermina siempre con una frase motivadora tipo\\n\\n¡Dale, pregunta nomás!\\n\\n¡Pruébalo y ve lo bacán que está esto!\"},\"promptType\":\"define\"},\"typeVersion\":3},{\"id\":\"b74244ac-ed9a-4979-95ac-d15a620c7df4\",\"name\":\"Wait\",\"type\":\"n8n-nodes-base.wait\",\"position\":[-368,1504],\"webhookId\":\"d38e8f38-68a5-4b15-b8c3-4dce9f102f38\",\"parameters\":{},\"typeVersion\":1.1},{\"id\":\"3104667b-6c32-4a83-9627-23609865000e\",\"name\":\"GUIA DE COMO PREGUNTAR\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-208,1504],\"webhookId\":\"4e6cea20-85ce-4b9a-b931-8fa22d93b87b\",\"parameters\":{\"text\":\"={{ $json.output }}\",\"chatId\":\"={{ $('Telegram Trigger - Inicio').item.json.message.chat.id }}\",\"additionalFields\":{\"parse_mode\":\"HTML\",\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"dff25489-2b4d-49da-9398-9efa73bbe8f5\",\"name\":\"Google Gemini Chat Model1\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatGoogleGemini\",\"position\":[-3168,1840],\"parameters\":{\"options\":{}},\"typeVersion\":1},{\"id\":\"7e30adff-e90b-495b-af22-d82ab8a464a3\",\"name\":\"BD_CALENDARIO1\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[-3872,1664],\"parameters\":{\"options\":{},\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":1817620056,\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit#gid=1817620056\",\"cachedResultName\":\"CALENDAR\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit?usp=drivesdk\",\"cachedResultName\":\"BASE-DATOS-FAQ_ESPOL\"}},\"typeVersion\":4.7},{\"id\":\"6ee54764-d999-48bc-a498-d4ded389b2f9\",\"name\":\"GENERADOR DE ANUNCIOS1\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[-3168,1664],\"parameters\":{\"text\":\"=Convierte el siguiente texto en un mensaje casual ecuatoriano:\\n\\nPeriodo: {{ $json[\\\"RESULTADOS[0].PERIODO_FECHAS\\\"] }}\\nActividades: {{ $json[\\\"RESULTADOS[0].ACTIVIDADES_GRADO\\\"] }}\\nProcesos: {{ $json[\\\"RESULTADOS[0].PROCESOS_GRADO\\\"] }}\\nFormacion tecnica: {{ $json['RESULTADOS[0][\\\\'ACTIVIDADES DE FORMACIÓN TÉCNICA Y TECNOLÓGICA\\\\']'] }}\\n\",\"options\":{\"systemMessage\":\"=Eres un redactor ecuatoriano experto en comunicación universitaria. Tu tarea es convertir los datos de tres semanas (anterior, actual y siguiente) en un solo mensaje casual, fresco y cercano, como si lo dijera un estudiante politécnico. \\n\\nSigue estas reglas:\\n\\n1. **Prioriza la semana del medio (la actual)**. Es la principal. Describe sus actividades con entusiasmo, usando un tono motivador y natural.\\n2. Luego menciona brevemente lo ocurrido **la semana pasada (primer item)**, con frases tipo: \\n “Si te lo perdiste la semana pasada…” o “Por si no te enteraste…”.\\n3. Finalmente, habla de **la semana siguiente (último item)**, pero nunca digas “la próxima semana” a secas. \\n Siempre menciona explícitamente **la fecha del periodo**, por ejemplo: \\n “Y para la semana del 17 al 21 de noviembre…” \\n Usa frases como: “prepárate para”, “se viene”, “atentos que en la semana del…”.\\n4. Usa expresiones naturales de Ecuador como *pilas, ñaño, pana, de una, qué bestia, bacán, full, a romperla*.\\n5. Separa las secciones con saltos de línea y mantén un estilo cercano y fluido, tipo mensaje de Telegram o redes.\\n6. No inventes información fuera del JSON, solo reformula y organiza lo recibido.\\n7. El resultado final debe ser un **solo texto en español ecuatoriano**, sin etiquetas, ni formato JSON, ni comillas.\\n\\nEjemplo de estructura esperada:\\n\\n¡Qué más, mi gente politécnica! Esta semana del 10 al 14 de noviembre se viene con todo 💪. \\nSeguimos a full con las actividades formativas y los panas de Formación Técnica también están dándole duro. ¡Qué bestia la energía que se siente en el campus! \\n\\nSi te lo perdiste la semana pasada, hubo evaluaciones y descansos para recargar pilas. ¡Espero que hayas aprovechado! 😎 \\n\\nY atentos para la semana del 17 al 21 de noviembre, que llega la PRIMERA EVALUACIÓN del grado. ¡A romperla con todo el ñeque, panas! 📚🔥\\n\"},\"promptType\":\"define\"},\"typeVersion\":3},{\"id\":\"8c041a63-8828-4f90-b670-85e018f73157\",\"name\":\"ENVIO DE MENSAJE DE VOZ1\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-2400,1536],\"webhookId\":\"ae4eba6e-2e6a-4a50-a4ec-6c527850b3c7\",\"parameters\":{\"file\":\"={{ $('GENERADOR DE MENSAJE DE VOZ').item.json.URL }}\",\"chatId\":\"={{ $json.chatId }}\",\"operation\":\"sendAudio\",\"additionalFields\":{\"caption\":\"={{ \\n(() => {\\n const today = new Date();\\n const dayOfWeek = today.getDay(); // 0=domingo\\n const diffMonday = (dayOfWeek === 0 ? -6 : 1 - dayOfWeek) + 7; // +7 => próxima semana\\n const diffFriday = diffMonday + 4;\\n\\n const monday = new Date(today);\\n monday.setDate(today.getDate() + diffMonday);\\n\\n const friday = new Date(today);\\n friday.setDate(today.getDate() + diffFriday);\\n\\n const fmt = d => `${d.getDate().toString().padStart(2, '0')}/${(d.getMonth() + 1).toString().padStart(2, '0')}`;\\n\\n return `Anuncio Semanal - Semana del ${fmt(monday)} al ${fmt(friday)}`;\\n})()\\n}}\\n\"}},\"typeVersion\":1.2},{\"id\":\"9681b6de-a5db-443e-89a5-e6a927b92b89\",\"name\":\"ENVIO DE MENSAJE DE TEXTO1\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-2384,1824],\"webhookId\":\"fc1657ce-66de-4cae-940f-86f0afae3ae5\",\"parameters\":{\"text\":\"={{ $json.text }}\",\"chatId\":\"={{ $json.chatId }}\",\"additionalFields\":{\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"67e74e9f-13b3-4f5f-80f4-e35e75558704\",\"name\":\"OPTIMIZADOR\",\"type\":\"n8n-nodes-base.code\",\"position\":[-2800,1808],\"parameters\":{\"jsCode\":\"// Tu array de chat IDs\\nconst chatIds = $('ACTIVIDADES DE LA SEMANA1').first().json.CHAT_IDS_VALIDOS; // reemplaza con tus IDs\\n\\n// Mensaje a enviar\\nconst mensaje = $input.first().json.output;\\n\\n// Creamos un item por cada chat ID\\nreturn chatIds.map(id => ({\\n json: {\\n chatId: id,\\n text: mensaje\\n }\\n}));\\n\"},\"typeVersion\":2},{\"id\":\"23d73abe-5b2b-42c5-b50f-fea043f4cd1a\",\"name\":\"OPTIMIZADOR1\",\"type\":\"n8n-nodes-base.code\",\"position\":[-2640,1584],\"parameters\":{\"jsCode\":\"// Tu array de chat IDs\\nconst chatIds = $('ACTIVIDADES DE LA SEMANA1').first().json.CHAT_IDS_VALIDOS; // reemplaza con tus IDs\\n\\n// Mensaje a enviar\\nconst mensaje = $input.first().json.output;\\n\\n// Creamos un item por cada chat ID\\nreturn chatIds.map(id => ({\\n json: {\\n chatId: id,\\n text: mensaje\\n }\\n}));\\n\"},\"typeVersion\":2},{\"id\":\"5dfc42b7-8684-4e92-95ca-7e1154345402\",\"name\":\"GENERADOR DE MENSAJE DE VOZ\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-2800,1584],\"parameters\":{\"url\":\"https://ttsmp3.com/makemp3_new.php\",\"method\":\"POST\",\"options\":{\"response\":{\"response\":{\"responseFormat\":\"json\"}}},\"sendBody\":true,\"contentType\":\"form-urlencoded\",\"bodyParameters\":{\"parameters\":[{\"name\":\"msg\",\"value\":\"={{ $json.output }}\"},{\"name\":\"lang\",\"value\":\"Mia\"},{\"name\":\"source\",\"value\":\"ttsmp3\"}]}},\"typeVersion\":4.2},{\"id\":\"7008a1aa-c9fb-4777-aac2-63f51cb88d49\",\"name\":\"OBTENER_ID1\",\"type\":\"n8n-nodes-base.set\",\"position\":[-880,1712],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"fc9b6408-8e37-4395-935f-33985719dae3\",\"name\":\"chat_id\",\"type\":\"number\",\"value\":\"={{ $json.message.chat.id }}\"}]}},\"typeVersion\":3.4},{\"id\":\"0310e05e-bc18-48de-952d-2c7e5163ab1f\",\"name\":\"AGREGA ID_UNICAS1\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[-624,1856],\"parameters\":{\"columns\":{\"value\":{\"CHAT_ID\":\"={{ $json.chat_id }}\"},\"schema\":[{\"id\":\"PERIODO_FECHAS\",\"type\":\"string\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"PERIODO_FECHAS\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"ACTIVIDADES_GRADO\",\"type\":\"string\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"ACTIVIDADES_GRADO\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"PROCESOS_GRADO\",\"type\":\"string\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"PROCESOS_GRADO\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"ACTIVIDADES DE FORMACIÓN TÉCNICA Y TECNOLÓGICA\",\"type\":\"string\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"ACTIVIDADES DE FORMACIÓN TÉCNICA Y TECNOLÓGICA\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"CHAT_ID\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"CHAT_ID\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[\"CHAT_ID\"],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{},\"operation\":\"append\",\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":1817620056,\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit#gid=1817620056\",\"cachedResultName\":\"CALENDAR\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit?usp=drivesdk\",\"cachedResultName\":\"BASE-DATOS-FAQ_ESPOL\"}},\"typeVersion\":4.7},{\"id\":\"6f2891fd-2874-4273-aeeb-5092191df6ec\",\"name\":\"Split Out\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-3056,560],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"PERIODOS-FECHAS, ACTIVIDADES_GRADO, PROCESOS_GRADO, ACTIVIDADES_TECNICAS-TECNOLÓGICAS\"},\"typeVersion\":1},{\"id\":\"525e2001-f72e-4f12-b0b8-1773498e9298\",\"name\":\"HTML\",\"type\":\"n8n-nodes-base.html\",\"position\":[-3248,560],\"parameters\":{\"options\":{},\"operation\":\"extractHtmlContent\",\"extractionValues\":{\"values\":[{\"key\":\"PERIODOS-FECHAS\",\"cssSelector\":\"table tbody tr td:first-child\",\"returnArray\":true},{\"key\":\"ACTIVIDADES_GRADO\",\"cssSelector\":\"table tbody tr td:nth-child(2)\",\"returnArray\":true},{\"key\":\"PROCESOS_GRADO\",\"cssSelector\":\"table tbody tr td:nth-child(3)\",\"returnArray\":true},{\"key\":\"ACTIVIDADES_TECNICAS-TECNOLÓGICAS\",\"cssSelector\":\"table tbody tr td:nth-child(4)\",\"returnArray\":true}]}},\"typeVersion\":1.2},{\"id\":\"4fc9dc13-c0a9-424e-8fab-873ae62f7c09\",\"name\":\"BD-CALENDARIO\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[-2656,560],\"parameters\":{\"columns\":{\"value\":{\"PERIODO_FECHAS\":\"={{ $json[\\\"PERIODOS-FECHAS\\\"] }}\",\"PROCESOS_GRADO\":\"={{ $json.PROCESOS_GRADO }}\",\"ACTIVIDADES_GRADO\":\"={{ $json.ACTIVIDADES_GRADO }}\",\"ACTIVIDADES DE FORMACIÓN TÉCNICA Y TECNOLÓGICA\":\"={{ $json[\\\"ACTIVIDADES_TECNICAS-TECNOLÓGICAS\\\"] }}\"},\"schema\":[{\"id\":\"PERIODO_FECHAS\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"PERIODO_FECHAS\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"ACTIVIDADES_GRADO\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"ACTIVIDADES_GRADO\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"PROCESOS_GRADO\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"PROCESOS_GRADO\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"ACTIVIDADES DE FORMACIÓN TÉCNICA Y TECNOLÓGICA\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"ACTIVIDADES DE FORMACIÓN TÉCNICA Y TECNOLÓGICA\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"CHAT_ID\",\"type\":\"string\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"CHAT_ID\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[\"PERIODO_FECHAS\"],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{},\"operation\":\"appendOrUpdate\",\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":1817620056,\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit#gid=1817620056\",\"cachedResultName\":\"CALENDAR\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo\",\"cachedResultUrl\":\"https://docs.google.com/spreadsheets/d/1WWE-eLP0g5M9Q2CeGpQZat56OhJrQyeYZJShjtETCgo/edit?usp=drivesdk\",\"cachedResultName\":\"BASE-DATOS-FAQ_ESPOL\"}},\"typeVersion\":4.7},{\"id\":\"db4dfee5-023e-4736-8b12-4f62879a3907\",\"name\":\"SCRRAPPING\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-3488,560],\"parameters\":{\"url\":\"https://www.espol.edu.ec/es/vida-politecnica/calendario-grado\",\"options\":{\"timeout\":60000},\"sendHeaders\":true,\"headerParameters\":{\"parameters\":[{\"name\":\"User-Agent\",\"value\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36\"}]}},\"typeVersion\":4.2},{\"id\":\"d23cb762-8460-41b9-b291-179baa9985d2\",\"name\":\"CORRECTOR DE FECHAS\",\"type\":\"n8n-nodes-base.code\",\"position\":[-2880,560],\"parameters\":{\"jsCode\":\"// Recibir items\\nconst itemsIn = $input.all();\\nlet currentYear = '';\\nconst results = [];\\n\\nfunction detectMonth(text) {\\n // Detecta el mes en el texto (minúsculas para evitar errores)\\n const months = {\\n enero: 1, febrero: 2, marzo: 3, abril: 4, mayo: 5, junio: 6,\\n julio: 7, agosto: 8, septiembre: 9, octubre: 10, noviembre: 11, diciembre: 12\\n };\\n const lower = text.toLowerCase();\\n for (const [month, num] of Object.entries(months)) {\\n if (lower.includes(month)) return num;\\n }\\n return null;\\n}\\n\\nfor (const item of itemsIn) {\\n const data = item.json;\\n let period = data[\\\"PERIODOS-FECHAS\\\"] ? String(data[\\\"PERIODOS-FECHAS\\\"]).trim() : \\\"\\\";\\n\\n // Detectar si hay un año explícito\\n const yearMatch = period.match(/\\\\b(20\\\\d{2})\\\\b/);\\n if (yearMatch) {\\n currentYear = parseInt(yearMatch[1]);\\n }\\n\\n // Si es encabezado, mantener igual\\n if (/^(VACACIONES|PAE|PAO)/i.test(period)) {\\n results.push({ json: { ...data } });\\n continue;\\n }\\n\\n // Detectar meses del período\\n const firstMonth = detectMonth(period.split('-')[0] || '');\\n const secondMonth = detectMonth(period.split('-')[1] || '');\\n\\n // Si tenemos dos meses y el segundo es menor que el primero → cambio de año\\n if (firstMonth && secondMonth && secondMonth < firstMonth) {\\n currentYear++;\\n }\\n\\n // Si no hay año en el texto, agregar el actual\\n if (!/\\\\b20\\\\d{2}\\\\b/.test(period) && currentYear) {\\n period = `${period} ${currentYear}`;\\n }\\n\\n results.push({\\n json: {\\n ...data,\\n \\\"PERIODOS-FECHAS\\\": period\\n }\\n });\\n}\\n\\nreturn results;\\n\"},\"typeVersion\":2},{\"id\":\"797b1458-c900-40af-89fb-866cf15e0ee8\",\"name\":\"Switch\",\"type\":\"n8n-nodes-base.switch\",\"position\":[-1712,1712],\"parameters\":{\"rules\":{\"values\":[{\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":false,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"0e1c1bb4-3315-4632-a9dc-5f917baf41da\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json.callback_query !== undefined }}\",\"rightValue\":\"0\"}]}},{\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":false,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"23c2e3a0-e7c8-46de-b504-2cabd445ed54\",\"operator\":{\"type\":\"string\",\"operation\":\"contains\"},\"leftValue\":\"={{ ($json.message?.reply_to_message?.text || '') }}\",\"rightValue\":\"Lamento que la información no te haya sido útil\"}]}},{\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":false,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"318d7097-ff17-4636-b7bf-958de3da6788\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json.message?.text?.startsWith('/') }}\",\"rightValue\":\"\"}]}}]},\"options\":{\"ignoreCase\":true,\"fallbackOutput\":\"extra\"},\"looseTypeValidation\":true},\"typeVersion\":3.3},{\"id\":\"207caeb2-0dad-4a90-8cb7-f943663ecfc6\",\"name\":\"Code in JavaScript1\",\"type\":\"n8n-nodes-base.code\",\"position\":[-3360,1664],\"parameters\":{\"jsCode\":\"const semanas = $input.all();\\n\\n// Inicializamos un objeto vacío\\nconst combinado = {};\\n\\n// Recorremos todas las semanas y sus claves\\nfor (const semana of semanas) {\\n const datos = semana.json;\\n for (const [clave, valor] of Object.entries(datos)) {\\n if (!combinado[clave]) combinado[clave] = [];\\n if (valor !== undefined && valor !== null && valor !== \\\"\\\")\\n combinado[clave].push(String(valor).trim());\\n }\\n}\\n\\n// Unimos los valores repetidos en un solo string, separados por comas\\nfor (const clave of Object.keys(combinado)) {\\n combinado[clave] = [...new Set(combinado[clave])].join(\\\", \\\");\\n}\\n\\n// Devolvemos un solo item con todo unido\\nreturn [{ json: combinado }];\\n\"},\"typeVersion\":2},{\"id\":\"2760029c-b039-4aab-95bd-005caeead0b6\",\"name\":\"Split Out2\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-3504,1664],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"RESULTADOS[0].PERIODO_FECHAS, RESULTADOS[0].ACTIVIDADES_GRADO, RESULTADOS[0].PROCESOS_GRADO, RESULTADOS[0]['ACTIVIDADES DE FORMACIÓN TÉCNICA Y TECNOLÓGICA']\"},\"typeVersion\":1},{\"id\":\"9dff1b64-2d74-4de5-8dee-cfcebfcd3977\",\"name\":\"ACTIVIDADES DE LA SEMANA1\",\"type\":\"n8n-nodes-base.code\",\"position\":[-3664,1664],\"parameters\":{\"jsCode\":\"// 🗓️ FECHA ACTUAL Y AÑO\\nconst hoy = new Date();\\nconst anioActual = hoy.getFullYear();\\n\\n// ✅ FUNCIÓN PARA CALCULAR EL LUNES DE UNA SEMANA RELATIVA\\nfunction obtenerLunes(base, desplazamientoSemanas = 0) {\\n const dia = base.getDay(); // 0=domingo, 1=lunes...\\n const lunes = new Date(base);\\n const diff = (1 - dia + 7) % 7; // hasta lunes\\n lunes.setDate(base.getDate() + diff + desplazamientoSemanas * 7);\\n return lunes;\\n}\\n\\n// 📆 CALCULAR LAS TRES SEMANAS CLAVE\\nconst lunesSemanaAnterior = obtenerLunes(hoy, -1);\\nconst lunesProximaSemana = obtenerLunes(hoy, 0);\\nconst lunesSemanaPosterior = obtenerLunes(hoy, 1);\\n\\n// 🧠 FUNCIÓN PARA INTERPRETAR RANGOS TIPO “09 - 13 NOVIEMBRE” O “9-13nov”\\nfunction parsearRango(rango) {\\n if (!rango || typeof rango !== \\\"string\\\") return null;\\n\\n rango = rango\\n .replace(/([0-9])([a-zA-ZñÑ])/g, \\\"$1 $2\\\")\\n .replace(/\\\\s+/g, \\\" \\\")\\n .trim()\\n .toLowerCase();\\n\\n const match = rango.match(/(\\\\d{1,2})\\\\s*-\\\\s*(\\\\d{1,2})\\\\s*([a-zñ]+)/);\\n if (!match) return null;\\n\\n const [, inicioStr, finStr, mesStr] = match;\\n const inicio = parseInt(inicioStr);\\n const fin = parseInt(finStr);\\n\\n const meses = {\\n ene: 0, enero: 0,\\n feb: 1, febrero: 1,\\n mar: 2, marzo: 2,\\n abr: 3, abril: 3,\\n may: 4, mayo: 4,\\n jun: 5, junio: 5,\\n jul: 6, julio: 6,\\n ago: 7, agosto: 7,\\n sep: 8, sept: 8, septiembre: 8,\\n oct: 9, octubre: 9,\\n nov: 10, noviembre: 10,\\n dic: 11, diciembre: 11\\n };\\n\\n const mesNum = meses[mesStr];\\n if (mesNum === undefined) return null;\\n\\n let anioRango = anioActual;\\n if (mesNum === 0 && hoy.getMonth() === 11) {\\n anioRango = anioActual + 1;\\n }\\n\\n const inicioFecha = new Date(anioRango, mesNum, inicio);\\n const finFecha = new Date(anioRango, mesNum, fin);\\n return { inicio: inicioFecha, fin: finFecha };\\n}\\n\\n// 🔍 FUNCIÓN PARA BUSCAR COINCIDENCIA DE SEMANA\\nfunction filtrarPorSemana(items, lunesReferencia) {\\n const resultados = [];\\n for (const item of items) {\\n const rango = parsearRango(item.json.PERIODO_FECHAS);\\n if (!rango) continue;\\n\\n const mismoInicio =\\n rango.inicio.getFullYear() === lunesReferencia.getFullYear() &&\\n rango.inicio.getDate() === lunesReferencia.getDate() &&\\n rango.inicio.getMonth() === lunesReferencia.getMonth();\\n\\n if (mismoInicio) resultados.push(item);\\n }\\n return resultados;\\n}\\n\\n// 📊 OBTENER RESULTADOS PARA CADA SEMANA\\nconst resultadosAnterior = filtrarPorSemana(items, lunesSemanaAnterior);\\nconst resultadosActual = filtrarPorSemana(items, lunesProximaSemana);\\nconst resultadosPosterior = filtrarPorSemana(items, lunesSemanaPosterior);\\n\\n// 🧹 CHAT_IDS VÁLIDOS (ÚNICOS)\\nconst chatIds = items\\n .map(item => item.json.CHAT_ID)\\n .filter(id => id !== undefined && id !== null && String(id).trim() !== \\\"\\\")\\n .map(id => String(id).trim());\\n\\nconst uniqueChatIds = [...new Set(chatIds)];\\n\\n// 🏁 SALIDA FINAL\\nreturn [\\n {\\n json: {\\n SEMANA: \\\"ANTERIOR\\\",\\n LUNES_SEMANA: lunesSemanaAnterior.toISOString().split(\\\"T\\\")[0],\\n RESULTADOS: resultadosAnterior.map(i => i.json),\\n CHAT_IDS_VALIDOS: uniqueChatIds\\n }\\n },\\n {\\n json: {\\n SEMANA: \\\"ACTUAL / PRÓXIMA\\\",\\n LUNES_SEMANA: lunesProximaSemana.toISOString().split(\\\"T\\\")[0],\\n RESULTADOS: resultadosActual.map(i => i.json),\\n CHAT_IDS_VALIDOS: uniqueChatIds\\n }\\n },\\n {\\n json: {\\n SEMANA: \\\"POSTERIOR\\\",\\n LUNES_SEMANA: lunesSemanaPosterior.toISOString().split(\\\"T\\\")[0],\\n RESULTADOS: resultadosPosterior.map(i => i.json),\\n CHAT_IDS_VALIDOS: uniqueChatIds\\n }\\n }\\n];\\n\"},\"typeVersion\":2},{\"id\":\"03a100d6-1492-4834-a638-653ff0a235ca\",\"name\":\"ANUNCIO SEMANAL\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"position\":[-4096,1680],\"parameters\":{\"rule\":{\"interval\":[{\"field\":\"weeks\",\"triggerAtHour\":19}]}},\"typeVersion\":1.2},{\"id\":\"af582ce7-df08-42dc-b4e6-e04bbc086c21\",\"name\":\"ACTUALIZAR CALENDARIO\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"position\":[-3728,560],\"parameters\":{\"rule\":{\"interval\":[{\"daysInterval\":7}]}},\"typeVersion\":1.2}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"HTML\":{\"main\":[[{\"node\":\"Split Out\",\"type\":\"main\",\"index\":0}]]},\"Wait\":{\"main\":[[{\"node\":\"GUIA DE COMO PREGUNTAR\",\"type\":\"main\",\"index\":0}]]},\"Switch\":{\"main\":[[{\"node\":\"Respuesta Usuario1\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Guardado en cvs Feedback\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Comandos1\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Detector_Calendario_Pre\",\"type\":\"main\",\"index\":0}]]},\"BD_ESPOL\":{\"ai_tool\":[[{\"node\":\"PREGUNTAS AL AZAR DE GUIA\",\"type\":\"ai_tool\",\"index\":0}]]},\"Comandos1\":{\"main\":[[{\"node\":\"Mensaje Help\",\"type\":\"main\",\"index\":0}],[{\"node\":\"FAQs\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Respuesta Contact\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Respuesta Events\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Inicio - Feedback\",\"type\":\"main\",\"index\":0}],[{\"node\":\"BIENVENIDA\",\"type\":\"main\",\"index\":0},{\"node\":\"OBTENER_ID1\",\"type\":\"main\",\"index\":0}]]},\"Split Out\":{\"main\":[[{\"node\":\"CORRECTOR DE FECHAS\",\"type\":\"main\",\"index\":0}]]},\"BIENVENIDA\":{\"main\":[[{\"node\":\"PREGUNTAS AL AZAR DE GUIA\",\"type\":\"main\",\"index\":0}]]},\"Get a chat\":{\"main\":[[{\"node\":\"Sí - Agradecimiento1\",\"type\":\"main\",\"index\":0}]]},\"SCRRAPPING\":{\"main\":[[{\"node\":\"HTML\",\"type\":\"main\",\"index\":0}]]},\"Split Out2\":{\"main\":[[{\"node\":\"Code in JavaScript1\",\"type\":\"main\",\"index\":0}]]},\"OBTENER_ID1\":{\"main\":[[{\"node\":\"AGREGA ID_UNICAS1\",\"type\":\"main\",\"index\":0}]]},\"OPTIMIZADOR\":{\"main\":[[{\"node\":\"ENVIO DE MENSAJE DE TEXTO1\",\"type\":\"main\",\"index\":0}]]},\"OPTIMIZADOR1\":{\"main\":[[{\"node\":\"ENVIO DE MENSAJE DE VOZ1\",\"type\":\"main\",\"index\":0}]]},\"BD_CALENDARIO1\":{\"main\":[[{\"node\":\"ACTIVIDADES DE LA SEMANA1\",\"type\":\"main\",\"index\":0}]]},\"ANUNCIO SEMANAL\":{\"main\":[[{\"node\":\"BD_CALENDARIO1\",\"type\":\"main\",\"index\":0}]]},\"Message a model1\":{\"main\":[[{\"node\":\"Limpiar_Texto_Gemini1\",\"type\":\"main\",\"index\":0}]]},\"Inicio - Feedback\":{\"main\":[[]]},\"Mensaje de Gemini\":{\"main\":[[{\"node\":\"Limpiar texto Gemini\",\"type\":\"main\",\"index\":0}]]},\"Respuesta Usuario1\":{\"main\":[[{\"node\":\"Get a chat\",\"type\":\"main\",\"index\":0}],[{\"node\":\"No - Mensaje Feedback1\",\"type\":\"main\",\"index\":0}]]},\"Switch_Que_BD_Leer\":{\"main\":[[{\"node\":\"Calendario Académico\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Leer FAQs de MongoDB\",\"type\":\"main\",\"index\":0}]]},\"CORRECTOR DE FECHAS\":{\"main\":[[{\"node\":\"BD-CALENDARIO\",\"type\":\"main\",\"index\":0}]]},\"Code in JavaScript1\":{\"main\":[[{\"node\":\"GENERADOR DE ANUNCIOS1\",\"type\":\"main\",\"index\":0}]]},\"Leer FAQs de MongoDB\":{\"main\":[[{\"node\":\"Buscar_FAQs_Relevantes\",\"type\":\"main\",\"index\":0}]]},\"Limpiar texto Gemini\":{\"main\":[[{\"node\":\"Enviar Respuesta sobre faqs\",\"type\":\"main\",\"index\":0}]]},\"ACTUALIZAR CALENDARIO\":{\"main\":[[{\"node\":\"SCRRAPPING\",\"type\":\"main\",\"index\":0}]]},\"Calendario Académico\":{\"main\":[[{\"node\":\"Buscar_Eventos_Calendario1\",\"type\":\"main\",\"index\":0}]]},\"Limpiar_Texto_Gemini1\":{\"main\":[[{\"node\":\"Enviar Respuesta sobre calendario1\",\"type\":\"main\",\"index\":0}]]},\"Buscar_FAQs_Relevantes\":{\"main\":[[{\"node\":\"Construir_Prompt_Gemini1\",\"type\":\"main\",\"index\":0}]]},\"GENERADOR DE ANUNCIOS1\":{\"main\":[[{\"node\":\"OPTIMIZADOR\",\"type\":\"main\",\"index\":0}]]},\"No - Mensaje Feedback1\":{\"main\":[[]]},\"Detector_Calendario_Pre\":{\"main\":[[{\"node\":\"Switch_Que_BD_Leer\",\"type\":\"main\",\"index\":0}]]},\"Construir_Prompt_Gemini1\":{\"main\":[[{\"node\":\"Mensaje de Gemini\",\"type\":\"main\",\"index\":0}]]},\"Google Gemini Chat Model\":{\"ai_languageModel\":[[{\"node\":\"PREGUNTAS AL AZAR DE GUIA\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Guardado en cvs Feedback\":{\"main\":[[]]},\"ACTIVIDADES DE LA SEMANA1\":{\"main\":[[{\"node\":\"Split Out2\",\"type\":\"main\",\"index\":0}]]},\"Google Gemini Chat Model1\":{\"ai_languageModel\":[[{\"node\":\"GENERADOR DE ANUNCIOS1\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"PREGUNTAS AL AZAR DE GUIA\":{\"main\":[[{\"node\":\"Wait\",\"type\":\"main\",\"index\":0}]]},\"Telegram Trigger - Inicio\":{\"main\":[[{\"node\":\"Switch\",\"type\":\"main\",\"index\":0}]]},\"Buscar_Eventos_Calendario1\":{\"main\":[[{\"node\":\"Construir_Prompt_Calendario1\",\"type\":\"main\",\"index\":0}]]},\"Enviar Respuesta sobre faqs\":{\"main\":[[]]},\"GENERADOR DE MENSAJE DE VOZ\":{\"main\":[[{\"node\":\"OPTIMIZADOR1\",\"type\":\"main\",\"index\":0}]]},\"Construir_Prompt_Calendario1\":{\"main\":[[{\"node\":\"Message a model1\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 53, "node_types": {"code": 12, "switch": 4, "telegram": 14, "mongoDb": 1, "telegramTrigger": 1, "googleGemini": 2, "googleSheets": 5, "lmChatGoogleGemini": 2, "googleSheetsTool": 1, "agent": 2, "wait": 1, "httpRequest": 2, "set": 1, "splitOut": 2, "html": 1, "scheduleTrigger": 2}, "services": ["ai", "google", "http"], "complexity": "complex", "has_conditions": false, "has_loops": true, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: How it works This automated workflow discovers trending Instagram posts and creates similar AI-generated content. Here's the high-level process: 1. Content Discovery & Analysis Scrapes trending posts from specific hashtags Analyzes visual elements using AI Filters out videos and duplicates 2. AI Content Generation Creates unique images based on trending content Generates engaging captions with relevant hashtags Maintains brand consistency while being original 3. Automated Publishing Posts content directly to Instagram Monitors publication status Sends notifications via Telegram Set up steps Setting up this workflow takes approximately 15-20 minutes: 1. API Configuration (7-10 minutes) Instagram Business Account setup Telegram Bot creation API key generation (OpenAI, Replicate, Rapid Api) 2"}, {"role": "assistant", "content": "\n**Analyse du besoin**: How it works\n\nThis automated workflow discovers trending Instagram posts and creates similar AI-generated content. Here's the high-level process:\n\n1. Content Discovery & Analysis\nScrapes trending post...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 27 nodes utilisant database, ai, http.\nStructure: logique conditionnelle, traitement par lots, code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"H7porcmXYj7StO23\",\"meta\":{\"instanceId\":\"35409808e3cc9dd8ecfa6f7b93ae931f074920a2f681e667da8974c0ecf81c52\",\"templateId\":\"2537\",\"templateCredsSetupCompleted\":true},\"name\":\"Generate Instagram Content from Top Trends with AI Image Generation\",\"tags\":[],\"nodes\":[{\"id\":\"8c49be2b-6320-4eb0-8303-6448ced34636\",\"name\":\"If media status is finished\",\"type\":\"n8n-nodes-base.if\",\"position\":[1420,260],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"0304efee-33b2-499e-bad1-9238c1fc2999\",\"operator\":{\"name\":\"filter.operator.equals\",\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.status_code }}\",\"rightValue\":\"FINISHED\"}]}},\"typeVersion\":2.2},{\"id\":\"f0cc0be5-6d35-4334-a124-139fa8676d07\",\"name\":\"If media status is finished1\",\"type\":\"n8n-nodes-base.if\",\"position\":[2000,260],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"0304efee-33b2-499e-bad1-9238c1fc2999\",\"operator\":{\"name\":\"filter.operator.equals\",\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.status_code }}\",\"rightValue\":\"PUBLISHED\"}]}},\"typeVersion\":2.2},{\"id\":\"c8d8d8cd-8501-4d1b-ac28-8cb3fa74d9d7\",\"name\":\"Telegram\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[1580,440],\"parameters\":{\"text\":\"Video upload edilmeden önce bir problem oldu\",\"chatId\":\"={{ $('Telegram Params').item.json.telegram_chat_id }}\",\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"ae91a5e0-4f70-4a1c-afa5-41f5449facab\",\"name\":\"Telegram1\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[2160,100],\"parameters\":{\"text\":\"Instagram Content is shared\",\"chatId\":\"={{ $('Telegram Params').item.json.telegram_chat_id }}\",\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"b8b38440-14a7-43f6-ac49-6ca9502ff54d\",\"name\":\"Telegram2\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[2160,440],\"parameters\":{\"text\":\"There was a problem when execution a upload content to instagram\",\"chatId\":\"={{ $('Telegram Params').item.json.telegram_chat_id }}\",\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"82e0e5d0-bf50-4b2e-8693-2612dffe53e2\",\"name\":\"Loop Over Items\",\"type\":\"n8n-nodes-base.splitInBatches\",\"position\":[-1000,220],\"parameters\":{\"options\":{}},\"typeVersion\":3},{\"id\":\"fb72beb1-1a6a-4148-9ee4-cdc564c4dc5c\",\"name\":\"Schedule Trigger1\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"position\":[-3080,300],\"parameters\":{\"rule\":{\"interval\":[{\"field\":\"cronExpression\",\"expression\":\"5 13,19 * * *\"}]}},\"typeVersion\":1.2},{\"id\":\"470f3406-19d2-420c-8f33-7031237d882c\",\"name\":\"Telegram Params\",\"type\":\"n8n-nodes-base.set\",\"position\":[-2320,300],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"d18cdca7-d301-4c70-a4d0-8d6e7ecfc2d1\",\"name\":\"telegram_chat_id\",\"type\":\"string\",\"value\":\"\"}]}},\"typeVersion\":3.4},{\"id\":\"12971505-7061-4d32-8921-d2e731eae9db\",\"name\":\"Instagram params\",\"type\":\"n8n-nodes-base.set\",\"position\":[-2560,300],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"1e380c14-e908-4eeb-90e0-957a422829d0\",\"name\":\"instagram_business_account_id\",\"type\":\"string\",\"value\":\"\"}]}},\"typeVersion\":3.4},{\"id\":\"2bc617b8-835c-48ba-8de6-341a6c87b853\",\"name\":\"Rapid Api params\",\"type\":\"n8n-nodes-base.set\",\"notes\":\"test\",\"position\":[-2080,300],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"48a33ec7-2b4f-496a-ad77-e4d5f1907ee4\",\"name\":\"x-rapid-api-key\",\"type\":\"string\",\"value\":\"\"}]}},\"notesInFlow\":false,\"typeVersion\":3.4},{\"id\":\"23bad41e-40ac-4488-8b2f-0d54d22a927a\",\"name\":\"filter the image content\",\"type\":\"n8n-nodes-base.code\",\"position\":[-1480,380],\"parameters\":{\"jsCode\":\"const filteredData = $input.first().json.data.items.filter(item=> !item.is_video)\\nreturn filteredData.map((item)=>{\\n return {\\n id: item.id,\\n prompt: item.caption.text,\\n content_code: item.code,\\n thumbnail_url: item.thumbnail_url,\\n tag: $input.first().json.data.additional_data.name\\n }\\n}) \\n\\n\"},\"typeVersion\":2},{\"id\":\"a65690cd-4d30-4541-b80d-aae872326a77\",\"name\":\"get top trends on instagram #blender3d\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-1720,180],\"parameters\":{\"url\":\"https://instagram-scraper-api2.p.rapidapi.com/v1/hashtag\",\"options\":{},\"sendQuery\":true,\"sendHeaders\":true,\"queryParameters\":{\"parameters\":[{\"name\":\"hashtag\",\"value\":\"blender3d\"},{\"name\":\"feed_type\",\"value\":\"top\"}]},\"headerParameters\":{\"parameters\":[{\"name\":\"x-rapidapi-host\",\"value\":\"instagram-scraper-api2.p.rapidapi.com\"},{\"name\":\"x-rapidapi-key\",\"value\":\"={{ $json['x-rapid-api-key'] }}\"}]}},\"typeVersion\":4.2},{\"id\":\"8707c475-7e28-4d80-92b8-ba24033c4632\",\"name\":\"get top trends on instagram #isometric\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-1720,380],\"parameters\":{\"url\":\"https://instagram-scraper-api2.p.rapidapi.com/v1/hashtag\",\"options\":{},\"sendQuery\":true,\"sendHeaders\":true,\"queryParameters\":{\"parameters\":[{\"name\":\"hashtag\",\"value\":\"isometric\"},{\"name\":\"feed_type\",\"value\":\"top\"}]},\"headerParameters\":{\"parameters\":[{\"name\":\"x-rapidapi-host\",\"value\":\"instagram-scraper-api2.p.rapidapi.com\"},{\"name\":\"x-rapidapi-key\",\"value\":\"={{ $json['x-rapid-api-key'] }}\"}]}},\"typeVersion\":4.2},{\"id\":\"1c1bfd8f-b086-4147-ba08-578877f2a315\",\"name\":\"merge the array content\",\"type\":\"n8n-nodes-base.merge\",\"position\":[-1280,280],\"parameters\":{},\"typeVersion\":3},{\"id\":\"6beb79ef-8205-4882-9bb0-6a2e1a33f1d4\",\"name\":\"Check Data on Database Is Exist\",\"type\":\"n8n-nodes-base.postgres\",\"onError\":\"continueErrorOutput\",\"position\":[-760,220],\"parameters\":{\"table\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"top_trends\",\"cachedResultName\":\"top_trends\"},\"where\":{\"values\":[{\"value\":\"={{$json.content_code}}\",\"column\":\"code\"}]},\"schema\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"public\",\"cachedResultName\":\"public\"},\"options\":{},\"operation\":\"select\"},\"typeVersion\":2.5,\"alwaysOutputData\":true},{\"id\":\"5b0c05a8-3eb7-4ad8-88e8-ceef81fe7a61\",\"name\":\"If Data is Exist\",\"type\":\"n8n-nodes-base.if\",\"position\":[-540,240],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"9dc20983-ae4d-40db-b969-7d43fa8b0c3e\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ !$json.isEmpty() }}\",\"rightValue\":\"we\"},{\"id\":\"0e1b9264-be56-4d0c-a83e-d9ca0b05b265\",\"operator\":{\"name\":\"filter.operator.equals\",\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"\",\"rightValue\":\"\"}]},\"looseTypeValidation\":true},\"executeOnce\":false,\"typeVersion\":2.2,\"alwaysOutputData\":false},{\"id\":\"9b510f11-9a44-4d54-b162-3ffb55d66677\",\"name\":\"send error message to telegram\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-1000,440],\"parameters\":{\"text\":\"There was a problem execution a postgresql content\",\"chatId\":\"={{ $('Telegram Params').item.json.telegram_chat_id}}\",\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"48bc61de-d416-4673-9e9b-8331ea841891\",\"name\":\"insert data on db\",\"type\":\"n8n-nodes-base.postgres\",\"position\":[-260,240],\"parameters\":{\"table\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"top_trends\",\"cachedResultName\":\"top_trends\"},\"schema\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"public\"},\"columns\":{\"value\":{\"tag\":\"={{$('Loop Over Items').item.json.tag}}\",\"code\":\"={{$('Loop Over Items').item.json.content_code}}\",\"prompt\":\"={{$('Loop Over Items').item.json.prompt}}\",\"isposted\":false,\"thumbnail_url\":\"={{$('Loop Over Items').item.json.thumbnail_url}}\"},\"schema\":[{\"id\":\"id\",\"type\":\"number\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"id\",\"defaultMatch\":true,\"canBeUsedToMatch\":true},{\"id\":\"prompt\",\"type\":\"string\",\"display\":true,\"required\":true,\"displayName\":\"prompt\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"isposted\",\"type\":\"boolean\",\"display\":true,\"required\":false,\"displayName\":\"isposted\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"createdat\",\"type\":\"dateTime\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"createdat\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"updatedat\",\"type\":\"dateTime\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"updatedat\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"deletedat\",\"type\":\"dateTime\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"deletedat\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"code\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"code\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"tag\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"tag\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"thumbnail_url\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"thumbnail_url\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[\"id\"],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{}},\"typeVersion\":2.5},{\"id\":\"15e7d69d-a10f-48a1-b240-046e9950d077\",\"name\":\"Analyze Image and give the content\",\"type\":\"@n8n/n8n-nodes-langchain.openAi\",\"position\":[80,240],\"parameters\":{\"text\":\"Create a clear and concise description of the object in the image, focusing on its physical and general features. Avoid detailed environmental aspects like background, lighting, or colors. Describe the shape, texture, size, and any unique characteristics of the object. Mention any notable features that make the object stand out, such as its surface details, materials, and design. The description should be focused on the object itself, not its surroundings.\\n\\nFor example, describe the following image:\\n\",\"modelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4o-mini\",\"cachedResultName\":\"GPT-4O-MINI\"},\"options\":{},\"resource\":\"image\",\"imageUrls\":\"={{ $('Loop Over Items').item.json.thumbnail_url }}\",\"operation\":\"analyze\"},\"typeVersion\":1.8},{\"id\":\"93e253b1-da7d-4193-b899-a38e6fd9f4e4\",\"name\":\"Analyze Content And Generate Instagram Caption\",\"type\":\"@n8n/n8n-nodes-langchain.openAi\",\"position\":[280,240],\"parameters\":{\"modelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4o-mini\",\"cachedResultName\":\"GPT-4O-MINI\"},\"options\":{},\"messages\":{\"values\":[{\"content\":\"=\\nSummarize the following content description into a short, engaging Instagram caption under 150 words. The caption should focus on the content of the image, not the app. Keep it appealing to social media users, and highlight the visual details of the image. Include hashtags relevant to 3D modeling and design, such as #Blender3D, #3DArt, #DigitalArt, #3DModeling, and #ArtCommunity. Ensure the tone is friendly and inviting.\\n\\n\\nContent description to summarize:\\n{{ $json.content }}\\n\\nMake sure to craft the caption around the content's features, such as the color contrast, reflective surface, and artistic nature of the image.\\n\\n\"}]}},\"typeVersion\":1.8},{\"id\":\"2259f6df-dca9-4a7e-babb-e63375f7207f\",\"name\":\"Prepare data on Instagram\",\"type\":\"n8n-nodes-base.facebookGraphApi\",\"position\":[980,260],\"parameters\":{\"edge\":\"media\",\"node\":\"={{ $('Instagram params').item.json.instagram_business_account_id }}\",\"options\":{\"queryParameters\":{\"parameter\":[{\"name\":\"image_url\",\"value\":\"={{ $json.output[0] }}\"},{\"name\":\"caption\",\"value\":\"={{ $('Analyze Content And Generate Instagram Caption').item.json.message.content }}\"}]}},\"graphApiVersion\":\"v20.0\",\"httpRequestMethod\":\"POST\"},\"typeVersion\":1},{\"id\":\"bcbb6058-1966-4bb5-915a-1e65b9131117\",\"name\":\"Check Status Of Media Before Uploaded\",\"type\":\"n8n-nodes-base.facebookGraphApi\",\"position\":[1200,260],\"parameters\":{\"node\":\"={{ $json.id }}\",\"options\":{\"fields\":{\"field\":[{\"name\":\"id\"},{\"name\":\"status\"},{\"name\":\"status_code\"}]}},\"graphApiVersion\":\"v20.0\"},\"typeVersion\":1},{\"id\":\"518d87ff-7808-4c06-b137-4e97d8f2ca28\",\"name\":\"Publish Media on Instagram\",\"type\":\"n8n-nodes-base.facebookGraphApi\",\"position\":[1600,100],\"parameters\":{\"edge\":\"media_publish\",\"node\":\"={{ $('Instagram params').item.json.instagram_business_account_id }}\",\"options\":{\"queryParameters\":{\"parameter\":[{\"name\":\"creation_id\",\"value\":\"={{ $json.id }}\"}]}},\"graphApiVersion\":\"v20.0\",\"httpRequestMethod\":\"POST\"},\"typeVersion\":1},{\"id\":\"a033d12b-524f-40e8-9208-5300bbc823d3\",\"name\":\"Check status of post \",\"type\":\"n8n-nodes-base.facebookGraphApi\",\"position\":[1800,260],\"parameters\":{\"node\":\"={{ $('Check Status Of Media Before Uploaded').item.json.id }}\",\"options\":{\"fields\":{\"field\":[{\"name\":\"id\"},{\"name\":\"status\"},{\"name\":\"status_code\"}]}},\"graphApiVersion\":\"v20.0\"},\"typeVersion\":1},{\"id\":\"02416fbb-4250-4278-af23-1f9189787123\",\"name\":\"filter the image content-2\",\"type\":\"n8n-nodes-base.code\",\"position\":[-1480,180],\"parameters\":{\"jsCode\":\"const filteredData = $input.first().json.data.items.filter(item=> !item.is_video)\\nreturn filteredData.map((item)=>{\\n return {\\n id: item.id,\\n prompt: item.caption.text,\\n content_code: item.code,\\n thumbnail_url: item.thumbnail_url,\\n tag: $input.first().json.data.additional_data.name\\n }\\n}) \\n\\n\"},\"typeVersion\":2},{\"id\":\"c8b933af-356e-49ae-92d3-42eaf4ee3e9f\",\"name\":\"Replicate params\",\"type\":\"n8n-nodes-base.set\",\"position\":[-2780,300],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"1e380c14-e908-4eeb-90e0-957a422829d0\",\"name\":\"replicate_token\",\"type\":\"string\",\"value\":\"\"}]}},\"typeVersion\":3.4},{\"id\":\"2c73cc9c-d436-459b-9b3c-bd870810b9b4\",\"name\":\"Generate image on flux\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[680,260],\"parameters\":{\"url\":\"https://api.replicate.com/v1/models/black-forest-labs/flux-schnell/predictions\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"input\\\": {\\n \\\"prompt\\\": \\\"A highly detailed 3D isometric model of {{$('Analyze Image and give the content').item.json.content .replace(/\\\\\\\\n/g, ' ') \\n.replace(/\\\\\\\\t/g, ' ') \\n.replace(/\\\\s+/g, ' ')\\n.trim(); }} rendered in a stylized miniature toy aesthetic. Materials: Matte plastic/painted metal/weathered stone texture with no self-shadowing. Lighting: - Completely shadowless rendering - Ultra bright and perfectly even illumination from all angles - Pure ambient lighting without directional shadows - Flat, consistent lighting across all surfaces - No ambient occlusion. Style specifications: - Clean, defined edges and surfaces - Slightly exaggerated proportions - Miniature/toy-like scale - Subtle wear and texturing - Rich color palette with muted tones - Isometric 3/4 view angle - Crisp details and micro-elements. Technical details: - 4K resolution - PBR materials without shadows - No depth of field - High-quality anti-aliasing - Perfect uniform lighting. Environment: Pure white background with zero shadows or gradients. Post-processing: High key lighting, maximum brightness, shadow removal.\\\",\\n \\\"output_format\\\": \\\"jpg\\\",\\n \\\"output_quality\\\": 100,\\n \\\"go_fast\\\":false\\n }\\n}\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"=json\",\"bodyParameters\":{\"parameters\":[{}]},\"headerParameters\":{\"parameters\":[{\"name\":\"Authorization\",\"value\":\"=Bearer {{ $('Replicate params').item.json.replicate_token}}\"},{\"name\":\"Prefer\",\"value\":\"wait\"}]}},\"typeVersion\":4.2}],\"active\":false,\"settings\":{\"timezone\":\"Europe/Istanbul\",\"callerPolicy\":\"workflowsFromSameOwner\",\"executionOrder\":\"v1\"},\"connections\":{\"Telegram\":{\"main\":[[]]},\"Loop Over Items\":{\"main\":[[],[{\"node\":\"Check Data on Database Is Exist\",\"type\":\"main\",\"index\":0}]]},\"Telegram Params\":{\"main\":[[{\"node\":\"Rapid Api params\",\"type\":\"main\",\"index\":0}]]},\"If Data is Exist\":{\"main\":[[{\"node\":\"Loop Over Items\",\"type\":\"main\",\"index\":0}],[{\"node\":\"insert data on db\",\"type\":\"main\",\"index\":0}]]},\"Instagram params\":{\"main\":[[{\"node\":\"Telegram Params\",\"type\":\"main\",\"index\":0}]]},\"Rapid Api params\":{\"main\":[[{\"node\":\"get top trends on instagram #isometric\",\"type\":\"main\",\"index\":0},{\"node\":\"get top trends on instagram #blender3d\",\"type\":\"main\",\"index\":0}]]},\"Replicate params\":{\"main\":[[{\"node\":\"Instagram params\",\"type\":\"main\",\"index\":0}]]},\"Schedule Trigger1\":{\"main\":[[{\"node\":\"Replicate params\",\"type\":\"main\",\"index\":0}]]},\"insert data on db\":{\"main\":[[{\"node\":\"Analyze Image and give the content\",\"type\":\"main\",\"index\":0}]]},\"Check status of post \":{\"main\":[[{\"node\":\"If media status is finished1\",\"type\":\"main\",\"index\":0}]]},\"Generate image on flux\":{\"main\":[[{\"node\":\"Prepare data on Instagram\",\"type\":\"main\",\"index\":0}]]},\"merge the array content\":{\"main\":[[{\"node\":\"Loop Over Items\",\"type\":\"main\",\"index\":0}]]},\"filter the image content\":{\"main\":[[{\"node\":\"merge the array content\",\"type\":\"main\",\"index\":1}]]},\"Prepare data on Instagram\":{\"main\":[[{\"node\":\"Check Status Of Media Before Uploaded\",\"type\":\"main\",\"index\":0}]]},\"Publish Media on Instagram\":{\"main\":[[{\"node\":\"Check status of post \",\"type\":\"main\",\"index\":0}]]},\"filter the image content-2\":{\"main\":[[{\"node\":\"merge the array content\",\"type\":\"main\",\"index\":0}]]},\"If media status is finished\":{\"main\":[[{\"node\":\"Publish Media on Instagram\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Telegram\",\"type\":\"main\",\"index\":0}]]},\"If media status is finished1\":{\"main\":[[{\"node\":\"Telegram1\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Telegram2\",\"type\":\"main\",\"index\":0}]]},\"Check Data on Database Is Exist\":{\"main\":[[{\"node\":\"If Data is Exist\",\"type\":\"main\",\"index\":0}],[{\"node\":\"send error message to telegram\",\"type\":\"main\",\"index\":0}]]},\"Analyze Image and give the content\":{\"main\":[[{\"node\":\"Analyze Content And Generate Instagram Caption\",\"type\":\"main\",\"index\":0}]]},\"Check Status Of Media Before Uploaded\":{\"main\":[[{\"node\":\"If media status is finished\",\"type\":\"main\",\"index\":0}]]},\"get top trends on instagram #isometric\":{\"main\":[[{\"node\":\"filter the image content\",\"type\":\"main\",\"index\":0}]]},\"get top trends on instagram #blender3d\":{\"main\":[[{\"node\":\"filter the image content-2\",\"type\":\"main\",\"index\":0}]]},\"Analyze Content And Generate Instagram Caption\":{\"main\":[[{\"node\":\"Generate image on flux\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 27, "node_types": {"if": 3, "telegram": 4, "splitInBatches": 1, "scheduleTrigger": 1, "set": 4, "code": 2, "httpRequest": 3, "merge": 1, "postgres": 2, "openAi": 2, "facebookGraphApi": 4}, "services": ["database", "ai", "http"], "complexity": "complex", "has_conditions": true, "has_loops": true, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Generate Instagram Content from Top Trends with AI Image Generation"}, {"role": "assistant", "content": "\n**Analyse du besoin**: How it works\n\nThis automated workflow discovers trending Instagram posts and creates similar AI-generated content. Here's the high-level process:\n\n1. Content Discovery & Analysis\nScrapes trending post...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 27 nodes utilisant database, ai, http.\nStructure: logique conditionnelle, traitement par lots, code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"H7porcmXYj7StO23\",\"meta\":{\"instanceId\":\"35409808e3cc9dd8ecfa6f7b93ae931f074920a2f681e667da8974c0ecf81c52\",\"templateId\":\"2537\",\"templateCredsSetupCompleted\":true},\"name\":\"Generate Instagram Content from Top Trends with AI Image Generation\",\"tags\":[],\"nodes\":[{\"id\":\"8c49be2b-6320-4eb0-8303-6448ced34636\",\"name\":\"If media status is finished\",\"type\":\"n8n-nodes-base.if\",\"position\":[1420,260],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"0304efee-33b2-499e-bad1-9238c1fc2999\",\"operator\":{\"name\":\"filter.operator.equals\",\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.status_code }}\",\"rightValue\":\"FINISHED\"}]}},\"typeVersion\":2.2},{\"id\":\"f0cc0be5-6d35-4334-a124-139fa8676d07\",\"name\":\"If media status is finished1\",\"type\":\"n8n-nodes-base.if\",\"position\":[2000,260],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"0304efee-33b2-499e-bad1-9238c1fc2999\",\"operator\":{\"name\":\"filter.operator.equals\",\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.status_code }}\",\"rightValue\":\"PUBLISHED\"}]}},\"typeVersion\":2.2},{\"id\":\"c8d8d8cd-8501-4d1b-ac28-8cb3fa74d9d7\",\"name\":\"Telegram\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[1580,440],\"parameters\":{\"text\":\"Video upload edilmeden önce bir problem oldu\",\"chatId\":\"={{ $('Telegram Params').item.json.telegram_chat_id }}\",\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"ae91a5e0-4f70-4a1c-afa5-41f5449facab\",\"name\":\"Telegram1\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[2160,100],\"parameters\":{\"text\":\"Instagram Content is shared\",\"chatId\":\"={{ $('Telegram Params').item.json.telegram_chat_id }}\",\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"b8b38440-14a7-43f6-ac49-6ca9502ff54d\",\"name\":\"Telegram2\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[2160,440],\"parameters\":{\"text\":\"There was a problem when execution a upload content to instagram\",\"chatId\":\"={{ $('Telegram Params').item.json.telegram_chat_id }}\",\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"82e0e5d0-bf50-4b2e-8693-2612dffe53e2\",\"name\":\"Loop Over Items\",\"type\":\"n8n-nodes-base.splitInBatches\",\"position\":[-1000,220],\"parameters\":{\"options\":{}},\"typeVersion\":3},{\"id\":\"fb72beb1-1a6a-4148-9ee4-cdc564c4dc5c\",\"name\":\"Schedule Trigger1\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"position\":[-3080,300],\"parameters\":{\"rule\":{\"interval\":[{\"field\":\"cronExpression\",\"expression\":\"5 13,19 * * *\"}]}},\"typeVersion\":1.2},{\"id\":\"470f3406-19d2-420c-8f33-7031237d882c\",\"name\":\"Telegram Params\",\"type\":\"n8n-nodes-base.set\",\"position\":[-2320,300],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"d18cdca7-d301-4c70-a4d0-8d6e7ecfc2d1\",\"name\":\"telegram_chat_id\",\"type\":\"string\",\"value\":\"\"}]}},\"typeVersion\":3.4},{\"id\":\"12971505-7061-4d32-8921-d2e731eae9db\",\"name\":\"Instagram params\",\"type\":\"n8n-nodes-base.set\",\"position\":[-2560,300],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"1e380c14-e908-4eeb-90e0-957a422829d0\",\"name\":\"instagram_business_account_id\",\"type\":\"string\",\"value\":\"\"}]}},\"typeVersion\":3.4},{\"id\":\"2bc617b8-835c-48ba-8de6-341a6c87b853\",\"name\":\"Rapid Api params\",\"type\":\"n8n-nodes-base.set\",\"notes\":\"test\",\"position\":[-2080,300],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"48a33ec7-2b4f-496a-ad77-e4d5f1907ee4\",\"name\":\"x-rapid-api-key\",\"type\":\"string\",\"value\":\"\"}]}},\"notesInFlow\":false,\"typeVersion\":3.4},{\"id\":\"23bad41e-40ac-4488-8b2f-0d54d22a927a\",\"name\":\"filter the image content\",\"type\":\"n8n-nodes-base.code\",\"position\":[-1480,380],\"parameters\":{\"jsCode\":\"const filteredData = $input.first().json.data.items.filter(item=> !item.is_video)\\nreturn filteredData.map((item)=>{\\n return {\\n id: item.id,\\n prompt: item.caption.text,\\n content_code: item.code,\\n thumbnail_url: item.thumbnail_url,\\n tag: $input.first().json.data.additional_data.name\\n }\\n}) \\n\\n\"},\"typeVersion\":2},{\"id\":\"a65690cd-4d30-4541-b80d-aae872326a77\",\"name\":\"get top trends on instagram #blender3d\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-1720,180],\"parameters\":{\"url\":\"https://instagram-scraper-api2.p.rapidapi.com/v1/hashtag\",\"options\":{},\"sendQuery\":true,\"sendHeaders\":true,\"queryParameters\":{\"parameters\":[{\"name\":\"hashtag\",\"value\":\"blender3d\"},{\"name\":\"feed_type\",\"value\":\"top\"}]},\"headerParameters\":{\"parameters\":[{\"name\":\"x-rapidapi-host\",\"value\":\"instagram-scraper-api2.p.rapidapi.com\"},{\"name\":\"x-rapidapi-key\",\"value\":\"={{ $json['x-rapid-api-key'] }}\"}]}},\"typeVersion\":4.2},{\"id\":\"8707c475-7e28-4d80-92b8-ba24033c4632\",\"name\":\"get top trends on instagram #isometric\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-1720,380],\"parameters\":{\"url\":\"https://instagram-scraper-api2.p.rapidapi.com/v1/hashtag\",\"options\":{},\"sendQuery\":true,\"sendHeaders\":true,\"queryParameters\":{\"parameters\":[{\"name\":\"hashtag\",\"value\":\"isometric\"},{\"name\":\"feed_type\",\"value\":\"top\"}]},\"headerParameters\":{\"parameters\":[{\"name\":\"x-rapidapi-host\",\"value\":\"instagram-scraper-api2.p.rapidapi.com\"},{\"name\":\"x-rapidapi-key\",\"value\":\"={{ $json['x-rapid-api-key'] }}\"}]}},\"typeVersion\":4.2},{\"id\":\"1c1bfd8f-b086-4147-ba08-578877f2a315\",\"name\":\"merge the array content\",\"type\":\"n8n-nodes-base.merge\",\"position\":[-1280,280],\"parameters\":{},\"typeVersion\":3},{\"id\":\"6beb79ef-8205-4882-9bb0-6a2e1a33f1d4\",\"name\":\"Check Data on Database Is Exist\",\"type\":\"n8n-nodes-base.postgres\",\"onError\":\"continueErrorOutput\",\"position\":[-760,220],\"parameters\":{\"table\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"top_trends\",\"cachedResultName\":\"top_trends\"},\"where\":{\"values\":[{\"value\":\"={{$json.content_code}}\",\"column\":\"code\"}]},\"schema\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"public\",\"cachedResultName\":\"public\"},\"options\":{},\"operation\":\"select\"},\"typeVersion\":2.5,\"alwaysOutputData\":true},{\"id\":\"5b0c05a8-3eb7-4ad8-88e8-ceef81fe7a61\",\"name\":\"If Data is Exist\",\"type\":\"n8n-nodes-base.if\",\"position\":[-540,240],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"loose\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"9dc20983-ae4d-40db-b969-7d43fa8b0c3e\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ !$json.isEmpty() }}\",\"rightValue\":\"we\"},{\"id\":\"0e1b9264-be56-4d0c-a83e-d9ca0b05b265\",\"operator\":{\"name\":\"filter.operator.equals\",\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"\",\"rightValue\":\"\"}]},\"looseTypeValidation\":true},\"executeOnce\":false,\"typeVersion\":2.2,\"alwaysOutputData\":false},{\"id\":\"9b510f11-9a44-4d54-b162-3ffb55d66677\",\"name\":\"send error message to telegram\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[-1000,440],\"parameters\":{\"text\":\"There was a problem execution a postgresql content\",\"chatId\":\"={{ $('Telegram Params').item.json.telegram_chat_id}}\",\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"48bc61de-d416-4673-9e9b-8331ea841891\",\"name\":\"insert data on db\",\"type\":\"n8n-nodes-base.postgres\",\"position\":[-260,240],\"parameters\":{\"table\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"top_trends\",\"cachedResultName\":\"top_trends\"},\"schema\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"public\"},\"columns\":{\"value\":{\"tag\":\"={{$('Loop Over Items').item.json.tag}}\",\"code\":\"={{$('Loop Over Items').item.json.content_code}}\",\"prompt\":\"={{$('Loop Over Items').item.json.prompt}}\",\"isposted\":false,\"thumbnail_url\":\"={{$('Loop Over Items').item.json.thumbnail_url}}\"},\"schema\":[{\"id\":\"id\",\"type\":\"number\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"id\",\"defaultMatch\":true,\"canBeUsedToMatch\":true},{\"id\":\"prompt\",\"type\":\"string\",\"display\":true,\"required\":true,\"displayName\":\"prompt\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"isposted\",\"type\":\"boolean\",\"display\":true,\"required\":false,\"displayName\":\"isposted\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"createdat\",\"type\":\"dateTime\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"createdat\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"updatedat\",\"type\":\"dateTime\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"updatedat\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"deletedat\",\"type\":\"dateTime\",\"display\":true,\"removed\":true,\"required\":false,\"displayName\":\"deletedat\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"code\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"code\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"tag\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"tag\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"thumbnail_url\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"thumbnail_url\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[\"id\"],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{}},\"typeVersion\":2.5},{\"id\":\"15e7d69d-a10f-48a1-b240-046e9950d077\",\"name\":\"Analyze Image and give the content\",\"type\":\"@n8n/n8n-nodes-langchain.openAi\",\"position\":[80,240],\"parameters\":{\"text\":\"Create a clear and concise description of the object in the image, focusing on its physical and general features. Avoid detailed environmental aspects like background, lighting, or colors. Describe the shape, texture, size, and any unique characteristics of the object. Mention any notable features that make the object stand out, such as its surface details, materials, and design. The description should be focused on the object itself, not its surroundings.\\n\\nFor example, describe the following image:\\n\",\"modelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4o-mini\",\"cachedResultName\":\"GPT-4O-MINI\"},\"options\":{},\"resource\":\"image\",\"imageUrls\":\"={{ $('Loop Over Items').item.json.thumbnail_url }}\",\"operation\":\"analyze\"},\"typeVersion\":1.8},{\"id\":\"93e253b1-da7d-4193-b899-a38e6fd9f4e4\",\"name\":\"Analyze Content And Generate Instagram Caption\",\"type\":\"@n8n/n8n-nodes-langchain.openAi\",\"position\":[280,240],\"parameters\":{\"modelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4o-mini\",\"cachedResultName\":\"GPT-4O-MINI\"},\"options\":{},\"messages\":{\"values\":[{\"content\":\"=\\nSummarize the following content description into a short, engaging Instagram caption under 150 words. The caption should focus on the content of the image, not the app. Keep it appealing to social media users, and highlight the visual details of the image. Include hashtags relevant to 3D modeling and design, such as #Blender3D, #3DArt, #DigitalArt, #3DModeling, and #ArtCommunity. Ensure the tone is friendly and inviting.\\n\\n\\nContent description to summarize:\\n{{ $json.content }}\\n\\nMake sure to craft the caption around the content's features, such as the color contrast, reflective surface, and artistic nature of the image.\\n\\n\"}]}},\"typeVersion\":1.8},{\"id\":\"2259f6df-dca9-4a7e-babb-e63375f7207f\",\"name\":\"Prepare data on Instagram\",\"type\":\"n8n-nodes-base.facebookGraphApi\",\"position\":[980,260],\"parameters\":{\"edge\":\"media\",\"node\":\"={{ $('Instagram params').item.json.instagram_business_account_id }}\",\"options\":{\"queryParameters\":{\"parameter\":[{\"name\":\"image_url\",\"value\":\"={{ $json.output[0] }}\"},{\"name\":\"caption\",\"value\":\"={{ $('Analyze Content And Generate Instagram Caption').item.json.message.content }}\"}]}},\"graphApiVersion\":\"v20.0\",\"httpRequestMethod\":\"POST\"},\"typeVersion\":1},{\"id\":\"bcbb6058-1966-4bb5-915a-1e65b9131117\",\"name\":\"Check Status Of Media Before Uploaded\",\"type\":\"n8n-nodes-base.facebookGraphApi\",\"position\":[1200,260],\"parameters\":{\"node\":\"={{ $json.id }}\",\"options\":{\"fields\":{\"field\":[{\"name\":\"id\"},{\"name\":\"status\"},{\"name\":\"status_code\"}]}},\"graphApiVersion\":\"v20.0\"},\"typeVersion\":1},{\"id\":\"518d87ff-7808-4c06-b137-4e97d8f2ca28\",\"name\":\"Publish Media on Instagram\",\"type\":\"n8n-nodes-base.facebookGraphApi\",\"position\":[1600,100],\"parameters\":{\"edge\":\"media_publish\",\"node\":\"={{ $('Instagram params').item.json.instagram_business_account_id }}\",\"options\":{\"queryParameters\":{\"parameter\":[{\"name\":\"creation_id\",\"value\":\"={{ $json.id }}\"}]}},\"graphApiVersion\":\"v20.0\",\"httpRequestMethod\":\"POST\"},\"typeVersion\":1},{\"id\":\"a033d12b-524f-40e8-9208-5300bbc823d3\",\"name\":\"Check status of post \",\"type\":\"n8n-nodes-base.facebookGraphApi\",\"position\":[1800,260],\"parameters\":{\"node\":\"={{ $('Check Status Of Media Before Uploaded').item.json.id }}\",\"options\":{\"fields\":{\"field\":[{\"name\":\"id\"},{\"name\":\"status\"},{\"name\":\"status_code\"}]}},\"graphApiVersion\":\"v20.0\"},\"typeVersion\":1},{\"id\":\"02416fbb-4250-4278-af23-1f9189787123\",\"name\":\"filter the image content-2\",\"type\":\"n8n-nodes-base.code\",\"position\":[-1480,180],\"parameters\":{\"jsCode\":\"const filteredData = $input.first().json.data.items.filter(item=> !item.is_video)\\nreturn filteredData.map((item)=>{\\n return {\\n id: item.id,\\n prompt: item.caption.text,\\n content_code: item.code,\\n thumbnail_url: item.thumbnail_url,\\n tag: $input.first().json.data.additional_data.name\\n }\\n}) \\n\\n\"},\"typeVersion\":2},{\"id\":\"c8b933af-356e-49ae-92d3-42eaf4ee3e9f\",\"name\":\"Replicate params\",\"type\":\"n8n-nodes-base.set\",\"position\":[-2780,300],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"1e380c14-e908-4eeb-90e0-957a422829d0\",\"name\":\"replicate_token\",\"type\":\"string\",\"value\":\"\"}]}},\"typeVersion\":3.4},{\"id\":\"2c73cc9c-d436-459b-9b3c-bd870810b9b4\",\"name\":\"Generate image on flux\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[680,260],\"parameters\":{\"url\":\"https://api.replicate.com/v1/models/black-forest-labs/flux-schnell/predictions\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"input\\\": {\\n \\\"prompt\\\": \\\"A highly detailed 3D isometric model of {{$('Analyze Image and give the content').item.json.content .replace(/\\\\\\\\n/g, ' ') \\n.replace(/\\\\\\\\t/g, ' ') \\n.replace(/\\\\s+/g, ' ')\\n.trim(); }} rendered in a stylized miniature toy aesthetic. Materials: Matte plastic/painted metal/weathered stone texture with no self-shadowing. Lighting: - Completely shadowless rendering - Ultra bright and perfectly even illumination from all angles - Pure ambient lighting without directional shadows - Flat, consistent lighting across all surfaces - No ambient occlusion. Style specifications: - Clean, defined edges and surfaces - Slightly exaggerated proportions - Miniature/toy-like scale - Subtle wear and texturing - Rich color palette with muted tones - Isometric 3/4 view angle - Crisp details and micro-elements. Technical details: - 4K resolution - PBR materials without shadows - No depth of field - High-quality anti-aliasing - Perfect uniform lighting. Environment: Pure white background with zero shadows or gradients. Post-processing: High key lighting, maximum brightness, shadow removal.\\\",\\n \\\"output_format\\\": \\\"jpg\\\",\\n \\\"output_quality\\\": 100,\\n \\\"go_fast\\\":false\\n }\\n}\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"=json\",\"bodyParameters\":{\"parameters\":[{}]},\"headerParameters\":{\"parameters\":[{\"name\":\"Authorization\",\"value\":\"=Bearer {{ $('Replicate params').item.json.replicate_token}}\"},{\"name\":\"Prefer\",\"value\":\"wait\"}]}},\"typeVersion\":4.2}],\"active\":false,\"settings\":{\"timezone\":\"Europe/Istanbul\",\"callerPolicy\":\"workflowsFromSameOwner\",\"executionOrder\":\"v1\"},\"connections\":{\"Telegram\":{\"main\":[[]]},\"Loop Over Items\":{\"main\":[[],[{\"node\":\"Check Data on Database Is Exist\",\"type\":\"main\",\"index\":0}]]},\"Telegram Params\":{\"main\":[[{\"node\":\"Rapid Api params\",\"type\":\"main\",\"index\":0}]]},\"If Data is Exist\":{\"main\":[[{\"node\":\"Loop Over Items\",\"type\":\"main\",\"index\":0}],[{\"node\":\"insert data on db\",\"type\":\"main\",\"index\":0}]]},\"Instagram params\":{\"main\":[[{\"node\":\"Telegram Params\",\"type\":\"main\",\"index\":0}]]},\"Rapid Api params\":{\"main\":[[{\"node\":\"get top trends on instagram #isometric\",\"type\":\"main\",\"index\":0},{\"node\":\"get top trends on instagram #blender3d\",\"type\":\"main\",\"index\":0}]]},\"Replicate params\":{\"main\":[[{\"node\":\"Instagram params\",\"type\":\"main\",\"index\":0}]]},\"Schedule Trigger1\":{\"main\":[[{\"node\":\"Replicate params\",\"type\":\"main\",\"index\":0}]]},\"insert data on db\":{\"main\":[[{\"node\":\"Analyze Image and give the content\",\"type\":\"main\",\"index\":0}]]},\"Check status of post \":{\"main\":[[{\"node\":\"If media status is finished1\",\"type\":\"main\",\"index\":0}]]},\"Generate image on flux\":{\"main\":[[{\"node\":\"Prepare data on Instagram\",\"type\":\"main\",\"index\":0}]]},\"merge the array content\":{\"main\":[[{\"node\":\"Loop Over Items\",\"type\":\"main\",\"index\":0}]]},\"filter the image content\":{\"main\":[[{\"node\":\"merge the array content\",\"type\":\"main\",\"index\":1}]]},\"Prepare data on Instagram\":{\"main\":[[{\"node\":\"Check Status Of Media Before Uploaded\",\"type\":\"main\",\"index\":0}]]},\"Publish Media on Instagram\":{\"main\":[[{\"node\":\"Check status of post \",\"type\":\"main\",\"index\":0}]]},\"filter the image content-2\":{\"main\":[[{\"node\":\"merge the array content\",\"type\":\"main\",\"index\":0}]]},\"If media status is finished\":{\"main\":[[{\"node\":\"Publish Media on Instagram\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Telegram\",\"type\":\"main\",\"index\":0}]]},\"If media status is finished1\":{\"main\":[[{\"node\":\"Telegram1\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Telegram2\",\"type\":\"main\",\"index\":0}]]},\"Check Data on Database Is Exist\":{\"main\":[[{\"node\":\"If Data is Exist\",\"type\":\"main\",\"index\":0}],[{\"node\":\"send error message to telegram\",\"type\":\"main\",\"index\":0}]]},\"Analyze Image and give the content\":{\"main\":[[{\"node\":\"Analyze Content And Generate Instagram Caption\",\"type\":\"main\",\"index\":0}]]},\"Check Status Of Media Before Uploaded\":{\"main\":[[{\"node\":\"If media status is finished\",\"type\":\"main\",\"index\":0}]]},\"get top trends on instagram #isometric\":{\"main\":[[{\"node\":\"filter the image content\",\"type\":\"main\",\"index\":0}]]},\"get top trends on instagram #blender3d\":{\"main\":[[{\"node\":\"filter the image content-2\",\"type\":\"main\",\"index\":0}]]},\"Analyze Content And Generate Instagram Caption\":{\"main\":[[{\"node\":\"Generate image on flux\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 27, "node_types": {"if": 3, "telegram": 4, "splitInBatches": 1, "scheduleTrigger": 1, "set": 4, "code": 2, "httpRequest": 3, "merge": 1, "postgres": 2, "openAi": 2, "facebookGraphApi": 4}, "services": ["database", "ai", "http"], "complexity": "complex", "has_conditions": true, "has_loops": true, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: 📌 Overview Description: This powerful workflow automates your sales quotation process by connecting Pipedrive with DottedSign. When a deal is moved to a specific stage in Pipedrive, this template automatically generates a professional PDF quotation, uploads it back to the deal, and sends it out for e-signature via DottedSign service, saving your sales team valuable time and eliminating manual work. What it does When a Pipedrive deal moves to a designated stage (e.g., \"Quotation Stage\"), this workflow triggers and performs the following actions: Gathers Data: It collects all relevant information, including deal details, client contacts, organization info, and associated products from Pipedrive. Generates PDF Quote: It populates a customizable HTML template with the collected data and uses a"}, {"role": "assistant", "content": "\n**Analyse du besoin**: 📌 Overview\n\nDescription:\n\nThis powerful workflow automates your sales quotation process by connecting Pipedrive with DottedSign. When a deal is moved to a specific stage in Pipedrive, this template au...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 0 nodes utilisant nodes natifs.\nStructure: flux standard.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"8LJ5mlndFypZh1VS\",\"meta\":{\"instanceId\":\"cf9804b12ee62314911ec55daa0c998a73f201da1917bd31262722d206bf0f27\",\"templateCredsSetupCompleted\":true},\"name\":\"QuotationAutomation template\",\"tags\":[],\"nodes\":[{\"id\":\"2e87b077-c9bf-49c9-9d03-955bdc6615c3\",\"name\":\"Pipedrive Trigger\",\"type\":\"n8n-nodes-base.pipedriveTrigger\",\"position\":[-16,176],\"webhookId\":\"988adb20-acfa-4668-858e-f89825b8bf6a\",\"parameters\":{\"action\":\"change\",\"entity\":\"deal\"},\"credentials\":{\"pipedriveApi\":{\"id\":\"M0Osgaz0uW0e047E\",\"name\":\"Pipedrive account Sandbox\"}},\"typeVersion\":1.1},{\"id\":\"a0076d48-fc1b-4b1c-937e-9dacb05fa9a9\",\"name\":\"Get a deal\",\"type\":\"n8n-nodes-base.pipedrive\",\"position\":[1104,-112],\"parameters\":{\"dealId\":\"={{ $json.data.id }}\",\"operation\":\"get\"},\"credentials\":{\"pipedriveApi\":{\"id\":\"M0Osgaz0uW0e047E\",\"name\":\"Pipedrive account Sandbox\"}},\"typeVersion\":1},{\"id\":\"351d5e24-33ba-4d98-82c4-e76c8ea7edce\",\"name\":\"editFlag=True\",\"type\":\"n8n-nodes-base.filter\",\"position\":[880,-304],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"01e341f6-05e7-4521-8b8e-dcba0a5e818c\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json.edit_flag }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2},{\"id\":\"b9f38e9c-428e-4ea2-a503-c927419bcf2d\",\"name\":\"Get many deal products\",\"type\":\"n8n-nodes-base.pipedrive\",\"position\":[880,80],\"parameters\":{\"dealId\":\"={{ $json.meta.entity_id }}\",\"resource\":\"dealProduct\",\"operation\":\"getAll\",\"returnAll\":true},\"credentials\":{\"pipedriveApi\":{\"id\":\"M0Osgaz0uW0e047E\",\"name\":\"Pipedrive account Sandbox\"}},\"typeVersion\":1},{\"id\":\"609f3763-2ce6-479c-b35d-a67da0edda07\",\"name\":\"setProductRows\",\"type\":\"n8n-nodes-base.code\",\"position\":[2000,176],\"parameters\":{\"jsCode\":\"// n8n Code Node (or similar Javascript environment)\\n\\nconst items = $input.first().json.deal_products;\\nlet htmlRows = '';\\n\\nfor (const item of items) {\\n // 修正後的版本:100% 匹配您的原版範本的結構和 CSS Class\\n let singleRowHtml = `\\n \\n \\n

          \\n ${item.name}\\n

          \\n \\n \\n

          \\n ${item.quantity}\\n

          \\n \\n \\n

          \\n ${item.currency} ${parseFloat(item.item_price).toFixed(2)}\\n

          \\n \\n \\n

          \\n ${item.discount}%\\n

          \\n \\n \\n

          \\n ${item.currency} ${parseFloat(item.sum).toFixed(2)}\\n

          \\n \\n \\n `;\\n // 清理換行和多餘空格,確保 HTML 乾淨\\n htmlRows += singleRowHtml.replace(/\\\\n\\\\s*/g, '');\\n}\\n\\nreturn { table_rows_html: htmlRows };\"},\"typeVersion\":2},{\"id\":\"8667563a-03d9-4d64-aff0-8d76deb7c853\",\"name\":\"Get a person\",\"type\":\"n8n-nodes-base.pipedrive\",\"position\":[1104,272],\"parameters\":{\"personId\":\"={{ $json.data.person_id }}\",\"resource\":\"person\",\"operation\":\"get\"},\"credentials\":{\"pipedriveApi\":{\"id\":\"M0Osgaz0uW0e047E\",\"name\":\"Pipedrive account Sandbox\"}},\"typeVersion\":1},{\"id\":\"ee372227-55b8-40cc-800a-d9e5aa1d3d37\",\"name\":\"field_mappings\",\"type\":\"n8n-nodes-base.set\",\"position\":[1328,-304],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"6b1137c7-df7e-41be-8555-9860db142e74\",\"name\":\"field_mappings\",\"type\":\"object\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"0cd3669f-1e1f-4d8e-a9a2-35b39f61d132\",\"name\":\"deal_details\",\"type\":\"n8n-nodes-base.set\",\"position\":[1328,-112],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"72ee9f3f-178c-457b-981a-09ae60fca3ea\",\"name\":\"deal_details\",\"type\":\"object\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"8b6c48fa-451e-45d6-b86f-4a15782d60af\",\"name\":\"person_details\",\"type\":\"n8n-nodes-base.set\",\"position\":[1328,272],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"b779769c-f9b4-48a1-8bfe-7827baf990b1\",\"name\":\"person_details\",\"type\":\"object\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"1c0268a7-490b-4b3f-a7db-458bace5c6d1\",\"name\":\"deal_products\",\"type\":\"n8n-nodes-base.set\",\"position\":[1328,80],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"13d41759-702c-4639-a184-615096f89a02\",\"name\":\"deal_products\",\"type\":\"object\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"e37cb8c9-fc54-4cad-973c-921fd1f7392c\",\"name\":\"Aggregate\",\"type\":\"n8n-nodes-base.aggregate\",\"position\":[1104,-304],\"parameters\":{\"options\":{},\"aggregate\":\"aggregateAllItemData\"},\"typeVersion\":1},{\"id\":\"74ff239d-aff4-462f-96b6-57ebf65df4c4\",\"name\":\"Aggregate1\",\"type\":\"n8n-nodes-base.aggregate\",\"position\":[1104,80],\"parameters\":{\"options\":{},\"aggregate\":\"aggregateAllItemData\"},\"typeVersion\":1},{\"id\":\"9465410d-f738-4d0d-bbf5-7132a440c21e\",\"name\":\"Get an organization\",\"type\":\"n8n-nodes-base.pipedrive\",\"position\":[1104,464],\"parameters\":{\"resource\":\"organization\",\"operation\":\"get\",\"organizationId\":\"={{ $json.data.org_id }}\"},\"credentials\":{\"pipedriveApi\":{\"id\":\"M0Osgaz0uW0e047E\",\"name\":\"Pipedrive account Sandbox\"}},\"typeVersion\":1},{\"id\":\"a11a4440-9c19-4d22-bdc9-09cc26a7ab74\",\"name\":\"org_details\",\"type\":\"n8n-nodes-base.set\",\"position\":[1328,464],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"baad2fc7-b3e8-45af-a45f-1bebf88dbf79\",\"name\":\"org_details\",\"type\":\"object\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"14ba18cc-36cd-41f8-8c2d-42c263c7364a\",\"name\":\"Convert to HTML\",\"type\":\"n8n-nodes-base.convertToFile\",\"position\":[2448,176],\"parameters\":{\"options\":{\"encoding\":\"utf8\",\"fileName\":\"index.html\",\"mimeType\":\"text/html\",\"dataIsBase64\":false},\"operation\":\"toBinary\",\"sourceProperty\":\"html\"},\"typeVersion\":1},{\"id\":\"b1005793-6c53-429c-afac-c957994391f5\",\"name\":\"Create a file\",\"type\":\"n8n-nodes-base.pipedrive\",\"position\":[3120,272],\"parameters\":{\"resource\":\"file\",\"additionalFields\":{\"deal_id\":\"={{ $('Clean & Map Data').item.json.id }}\",\"activity_id\":\"={{ $('Create an activity').item.json.id }}\"},\"binaryPropertyName\":\"=data\"},\"credentials\":{\"pipedriveApi\":{\"id\":\"M0Osgaz0uW0e047E\",\"name\":\"Pipedrive account Sandbox\"}},\"typeVersion\":1},{\"id\":\"25e7bbe7-3bd6-4968-aff5-92e1a2c48876\",\"name\":\"Create an activity\",\"type\":\"n8n-nodes-base.pipedrive\",\"position\":[1104,656],\"parameters\":{\"type\":\"Quoatation\",\"subject\":\"=Quotation/ {{ $json.data.id }}/{{ $json.data.update_time.toDateTime().format('yyyyMMdd') }}\",\"resource\":\"activity\",\"additionalFields\":{\"deal_id\":\"={{ $json.data.id }}\"}},\"credentials\":{\"pipedriveApi\":{\"id\":\"M0Osgaz0uW0e047E\",\"name\":\"Pipedrive account Sandbox\"}},\"typeVersion\":1},{\"id\":\"276e0728-344b-4ef3-bf31-16b6aeacc898\",\"name\":\"activity_details\",\"type\":\"n8n-nodes-base.set\",\"position\":[1328,656],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"baad2fc7-b3e8-45af-a45f-1bebf88dbf79\",\"name\":\"activity_details\",\"type\":\"object\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"ab6a37ee-a249-46ea-b335-3b9c20bcc8ab\",\"name\":\"DottedSign-CreateTask\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[3792,176],\"parameters\":{\"url\":\"https://api.sandbox.dottedsign.com/v1/sign_tasks\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"has_order\\\": false,\\n \\\"start\\\": true,\\n \\\"stages\\\": [\\n {\\n \\\"field_settings\\\": [\\n {\\n \\\"field_type\\\": \\\"signature\\\",\\n \\\"coord\\\": [92.0, 237.0, 353.0, 274.0],\\n \\\"options\\\": { \\\"placeholder\\\": \\\"signhere\\\" },\\n \\\"page\\\": 1\\n }\\n ],\\n \\\"stage_setting\\\": {\\n \\\"informable\\\": true,\\n \\\"reviewed_skip_confirm\\\": true\\n },\\n \\\"name\\\": \\\"{{ $('Clean & Map Data').item.json.person_details.name }}\\\",\\n \\\"email\\\": \\\"{{ $('Clean & Map Data').item.json.person_details.email[0].value }}\\\",\\n \\\"stage_type\\\": \\\"sign\\\"\\n }\\n ],\\n \\\"task_setting\\\": {\\n \\\"cc_infos\\\": [\\n {\\n \\\"email\\\": \\\"{{ $('Clean & Map Data').item.json.person_details.owner_id.email }}\\\",\\n \\\"name\\\": \\\"{{ $('Clean & Map Data').item.json.person_details.owner_id.name }}\\\" }],\\n \\\"receiver_lang\\\": \\\"en\\\",\\n \\\"owner_informable\\\": true\\n },\\n \\\"base64_file\\\": \\\"{{ $json.data }}\\\",\\n \\\"file_name\\\": \\\"{{ $('Clean & Map Data').item.json.title.replace(/[\\\\\\\"*:<>\\\\?\\\\/\\\\\\\\|~#%&{}]/g, '_') }}.pdf\\\"\\n}\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"accept\",\"value\":\"application/json\"},{\"name\":\"Authorization\",\"value\":\"=Bearer {{ $json.access_token }}\"},{\"name\":\"content-type\",\"value\":\"application/json\"}]}},\"typeVersion\":4.2},{\"id\":\"60cc6b34-70f4-4900-a7cb-0a16ee987344\",\"name\":\"Extract from File\",\"type\":\"n8n-nodes-base.extractFromFile\",\"position\":[3344,80],\"parameters\":{\"options\":{},\"operation\":\"binaryToPropery\"},\"typeVersion\":1,\"alwaysOutputData\":true},{\"id\":\"de55a7d7-c151-4270-b356-ff6600ced25a\",\"name\":\"Sticky Note\",\"type\":\"n8n-nodes-base.stickyNote\",\"position\":[-1200,-560],\"parameters\":{\"width\":1056,\"height\":752,\"content\":\"## 📌 Overview\\n**Title:** `Automate Quotation Generation from Pipedrive to DottedSign`\\n**Description:**\\nThis powerful workflow automates your sales quotation process by connecting Pipedrive with DottedSign. When a deal is moved to a specific stage in Pipedrive, this template automatically generates a professional PDF quotation, uploads it back to the deal, and sends it out for e-signature via DottedSign service, saving your sales team valuable time and eliminating manual work.\\n## What it does\\nWhen a Pipedrive deal moves to a designated stage (e.g., \\\"Quotation Stage\\\"), this workflow triggers and performs the following actions:\\n1. **Gathers Data:** It collects all relevant information, including deal details, client contacts, organization info, and associated products from Pipedrive.\\n2. **Generates PDF Quote:** It populates a customizable HTML template with the collected data and uses a PDF generation service (Gotenberg) to create a polished PDF document.\\n3. **Uploads to Pipedrive:** The generated PDF quote is automatically uploaded to the \\\"Files\\\" section of the corresponding Pipedrive deal for record-keeping.\\n4. **Sends for E-Signature:** It creates a new signing task in DottedSign, sending the quotation to the client for their electronic signature.\\n## Requirements\\n- A Pipedrive account with admin permissions.\\n- A DottedSign developer account to obtain API credentials.\\n- A self-hosted instance of [Gotenberg](https://gotenberg.dev/docs/getting-started/installation) for HTML to PDF conversion.\\n## How to set up\\n1. **Pipedrive Trigger Stage:** In the `If` node, change the stage ID `7` to the ID of the pipeline stage you want to use as the trigger.\\n2. **PDF Conversion Service:** In the `Gotenberg to PDF` (HTTP Request) node, replace the placeholder URL with the endpoint of your running Gotenberg instance.\\n3. **DottedSign Credentials:** In the `Get DottedSign Access Token` node, enter your `client_id` and `client_secret` in the request body.\\n4. **DottedSign Signature Field:** In the `Create DottedSign Task` node, you **must** adjust the `page` and `coord` values under `field_settings` to match the desired signature location on your PDF template.\\n## How to customize the workflow\\n- **Quotation Template:** Edit the `Generate Quotation HTML` node to modify the quote's appearance, text, company logo, and terms. The `{{ ... }}` expressions are placeholders that are filled with Pipedrive data.\\n- **Trigger:** Replace the Pipedrive Trigger with another trigger, such as a webhook or a form submission, to adapt the workflow to different needs.\\n- **Notifications:** Add a Slack or email node at the end of the workflow to notify the sales team once the quotation has been sent.\"},\"typeVersion\":1},{\"id\":\"cc8f8665-c85f-4e05-bdba-fcd560a7aba0\",\"name\":\"Sticky Note2\",\"type\":\"n8n-nodes-base.stickyNote\",\"position\":[-48,-560],\"parameters\":{\"color\":3,\"width\":1504,\"height\":1504,\"content\":\"## **STEP 1: Trigger & Data Collection**\\n\\n* **Pipedrive Trigger**: Watches for any change in a Pipedrive deal.\\n* **If**: Checks if the deal was moved to Specific Stage . The workflow will start execute.\\n* **Data Collection**: If the condition is true, it fetches all necessary data: Deal details, Person, Organization, Products, and Custom Field definitions (Optional).\"},\"typeVersion\":1},{\"id\":\"ffe36349-2631-4001-94cb-33068ef48be8\",\"name\":\"Sticky Note3\",\"type\":\"n8n-nodes-base.stickyNote\",\"position\":[1520,-144],\"parameters\":{\"width\":640,\"height\":752,\"content\":\"## **STEP 2: Data Processing** \\n\\n* **Set Nodes**: Rename different data streams for clarity (e.g., `deal_details`, `person_details`).\\n* **Merge**: Combines all the separate data into a single object.\\n* **Code (Main)** It cleans up the data and converts technical customfieldIDs mapping with string text.\"},\"typeVersion\":1},{\"id\":\"bfb48e6f-0b00-438b-a5e1-ec79d703508f\",\"name\":\"Sticky Note4\",\"type\":\"n8n-nodes-base.stickyNote\",\"position\":[2176,-32],\"parameters\":{\"color\":4,\"width\":848,\"height\":464,\"content\":\"## **STEP 3: PDF Generation**\\n\\n* **setProductRows**: This Code node dynamically creates the HTML table rows for the product list.\\n* **HTML**: This is the main template. It takes the processed data and fills it into the HTML layout.\\n* **Convert to HTML -> convert to PDF**: Turns the final HTML into a binary file, then sends it to the Gotenberg service to create the PDF.\"},\"typeVersion\":1},{\"id\":\"02b99292-f1df-4343-a2d6-e29b7d96b147\",\"name\":\"Sticky Note5\",\"type\":\"n8n-nodes-base.stickyNote\",\"position\":[3072,-128],\"parameters\":{\"width\":944,\"height\":688,\"content\":\"## **STEP 4: Final Actions**\\n\\n* **Create a file**: Uploads the newly created PDF to the Pipedrive deal's \\\"Files\\\" section.\\n* **Extract from File**: Converts the PDF into Base64 format, which is required by the DottedSign API.\\n* **DottedSign-GetAccessToken**: Gets a temporary API token from DottedSign.\\n* **DottedSign-CreateTask**: Sends the PDF and signer info to DottedSign to start the e-signature process.\"},\"typeVersion\":1},{\"id\":\"891f3d99-0b53-468c-a95e-ea84fa420ef9\",\"name\":\"MergeAllData\",\"type\":\"n8n-nodes-base.merge\",\"position\":[1552,112],\"parameters\":{\"mode\":\"combine\",\"options\":{\"includeUnpaired\":true},\"combineBy\":\"combineByPosition\",\"numberInputs\":6},\"typeVersion\":3.2},{\"id\":\"6a653173-a497-4fa0-88ae-ffdee6cb14ed\",\"name\":\"MergeForDS\",\"type\":\"n8n-nodes-base.merge\",\"position\":[3568,176],\"parameters\":{\"mode\":\"combine\",\"options\":{},\"combineBy\":\"combineByPosition\"},\"typeVersion\":3.2,\"alwaysOutputData\":true},{\"id\":\"647168e9-bd89-4cfb-b314-2375f9123d18\",\"name\":\"Clean & Map Data\",\"type\":\"n8n-nodes-base.code\",\"position\":[1776,176],\"parameters\":{\"jsCode\":\"\\nconst inputData = $input.item.json;\\n\\n\\nconst dealData = inputData.deal_details;\\nconst personData = inputData.person_details;\\nconst orgData = inputData.org_details;\\n// 從聚合後的物件中提取陣列\\nconst dealProducts = inputData.deal_products?.data || [];\\nconst fieldMappingsArray = inputData.field_mappings?.data || [];\\n\\n\\nif (!dealData) {\\n throw new Error(\\\"Deal data (deal_details) is missing from the input. Check the Merge node and its inputs.\\\");\\n}\\n\\n\\nconst fieldMapping = {};\\nfor (const field of fieldMappingsArray) {\\n if (field.key && field.name) {\\n fieldMapping[field.key] = field.name;\\n\\n if ((field.field_type === 'enum' || field.field_type === 'set') && field.options) {\\n fieldMapping[field.key + '_options'] = field.options;\\n }\\n }\\n}\\n\\n\\nconst cleanedDeal = {};\\n\\n\\nfor (const key in dealData) {\\n if (dealData.hasOwnProperty(key)) {\\n let value = dealData[key];\\n\\n\\n if (fieldMapping[key]) {\\n const fieldName = fieldMapping[key];\\n const options = fieldMapping[key + '_options'];\\n\\n\\n if (options && (typeof value === 'string' || typeof value === 'number')) {\\n const valueArray = String(value).split(',').map(s => s.trim());\\n const labels = valueArray.map(val => {\\n const option = options.find(opt => String(opt.id) === val);\\n return option ? option.label : val; \\n });\\n cleanedDeal[fieldName] = (valueArray.length > 1) ? labels : labels[0];\\n } else if (value && typeof value === 'object' && value !== null && value.name !== undefined) {\\n cleanedDeal[fieldName] = value.name;\\n } else if (value && typeof value === 'object' && value !== null && value.value !== undefined) {\\n cleanedDeal[fieldName] = value.value;\\n } else {\\n cleanedDeal[fieldName] = value;\\n }\\n\\n } else if (key.endsWith('_id') && typeof value === 'object' && value !== null && value.name !== undefined) {\\n cleanedDeal[key.replace('_id', '_name')] = value.name;\\n\\n } else {\\n cleanedDeal[key] = value;\\n }\\n }\\n}\\n\\n\\nif (personData) {\\n cleanedDeal.person_details = personData;\\n}\\nif (orgData) {\\n cleanedDeal.org_details = orgData;\\n}\\nif (dealProducts.length > 0) {\\n cleanedDeal.deal_products = dealProducts;\\n}\\n\\n\\nreturn [{\\n json: cleanedDeal\\n}];\"},\"typeVersion\":2},{\"id\":\"c7724bac-4f45-4d31-96ab-78e09e9604e5\",\"name\":\"Generate Quote HTML\",\"type\":\"n8n-nodes-base.html\",\"position\":[2224,176],\"parameters\":{\"html\":\"

          YOUR COMPANY NAME.

          YOUR COMPANY ADDRESS,

          YOUR COMPANY ADDRESS

          Phone: YOUR COMPANY PHONE

          YOUR COMPANY WEBSITE  

          Contact Person: n8n-user_name:{{ $('Clean & Map Data').item.json.user_name }}

          QUOTATION

          QUO-NO # n8n-deal_id:{{ $('Clean & Map Data').item.json.id }}

          DATE: n8n-date:{{ $('Clean & Map Data').item.json.update_time.toDateTime().format('yyyy-MM-dd') }}

          Quote To:_____n8n-org_name:{{ $('Clean & Map Data').item.json.org_name }}______(“You”or “Your”)

          {{ $('setProductRows').item.json.table_rows_html }}

          Description

          Quantity

          Unit Price

          Discount

          Amount

          Sub Total

          {{ $('Clean & Map Data').item.json.currency }} {{ $('Clean & Map Data').item.json.value }}

          Shipping

          {{ $('Clean & Map Data').item.json.currency }}

          Tax (5%)

          {{ $('Clean & Map Data').item.json.currency }}

          Total

          {{ $('Clean & Map Data').item.json.currency }} {{ $('Clean & Map Data').item.json.value }}

          Note:

          1. This quotation takes effect when You have completed the signing and return the electronic files (including scanned files or PDFs) of the quotation by facsimile or electronic transmission or other means to Kdan Mobile Software Ltd (“we”,”us”, or”our”). Upon the effective date of this quotation, if You would like to postpone the activation date of the service license(s) or adjust the number of activated licenses within the licensed quantity due to Your internal considerations or other reasons not attributable to us, You shall notify us in writing or by email and obtain our consent. However, You understand and agree that under such circumstances, the Licensed Period stipulated in this Quotation shall remain unaffected. If there are any licenses that remain unactivated upon the expiration of the Licensed Period, You acknowledge and agree that we shall no longer activate such remaining licenses and shall not provide any refund or extension. You shall not assert any claim against us in this regard. The foregoing shall not affect Your payment obligations under this Quotation, and You shall still make full payment in accordance with the relevant provisions herein.
          2. If neither party raises any objections 30 days prior to the expiration of DottedSign licensing period, this quotation will be automatically renewed for one year under the same terms and conditions.\"
          3. When You use DottedSign, You agree to comply with the “Terms of Use” (https://www.dottedsign.com/terms_of_service) in our official website.
          4. Unless otherwise specified in this quotation, you have the right to terminate the quotation without any reason within the period, which starting fromMM/DD/YYYY to 30 days after the date of account activation by us (the “Termination Period”). Once You terminate the quotation within the Termination Period, You should provide notice in writing or electronically to us and You must pay equal to 20% of the total License Fee to us(the “Termination Fee”); however, if You terminate the quotation before the date of account activation, the Termination Fee would be deducted to equal to 15% of the total License Fee. After the Termination Period, You are not entitled to terminate the quotation.
          5. The quotation terminate from the date we receive Your termination notice (the” termination day”). We have the right to deduct the Termination fee, the subscription fee incurred by You in accessing our service before the termination date(Less than one day, shall be calculate as one day), and any other damages from the refund. All refunds are not eligible for interest.
          6. Payment instructions: we must received full amount of the payment, You agree to pay all charges incurred by the transaction.
          7. Within thirty(30) days after You sign and return the quotation to us, You must pay the total amount to the payment link designated by us by credit card. Under the condition that \"to pay the service fee within a specified period after the issuance of the invoice,\" if the payment is not made within the agreed period, we reserves the right to calculate late payment interest at an annual rate of 5%, temporarily suspend the provision of services, and, if deemed necessary, unilaterally terminate this quotation. Under the other condition that \"to prepay the service fee before the issuance of the invoice,\" if the payment is not made within the agreed period, we reserves the right to withhold the account activation and unilaterally terminate this quotation.
          8. You hereby grant to us as well as the subsidiaries and affiliates of us( hereinafter collectively referred to as “Kdan Group Companies”) a royalty-free and perpetual license to use Your corporation mark (including trademarks, trade names, and logos ) in marketing, sales, and public relations material to identify You as a Kdan Group Companies’ partner.
          9. Both parties agree that this quotation shall be presented in electronic records. And this quotation could be signed using an electronic signature.
          10. In the event of any conflict or inconsistency between the terms and conditions of this quotation and the terms of contracts agreed by both parties someday, the provisions of those contracts shall prevail.
          11. During the performance of the quotation, both parties agree to enter into written supplementary agreement for any matter not covered by this quotation.
          12. If You do not sign and return the quotation within one month after we send it to You, the quotation will lapse automatically.
          13. This quotation shall be construed in accordance with the laws of the Republic of China (Taiwan). The Parties agree that the conditions set forth hereunder shall be performed in the utmost spirit of goodwill and good faith. In the event of a dispute, the Parties agree that the Taiwan Taipei District Court shall be the court of first instance.
          14. We are committed to protecting the security of Your personal data and information. Any personal data provided by You, as well as any information obtained through the use of our website or services, is managed and protected in accordance with our Privacy Policy and Security Policy. You acknowledge and agree that any information You obtain about others through the use of our website or services will also be subject to the regulations of our Privacy Policy and Security Policy. For more details, please refer to the following link:

          Privacy Policy:https://dottedsign.com/privacy_policy

          Security Policy:https://dottedsign.com/security

          1. Both parties shall conduct their business activities based on the principles of integrity. Both parties agree that during the process of signing and fulfilling the purpose of this quotation, neither party nor its directors, managers, employees, agents, or persons with substantial control (collectively referred to as \"Personnel\") shall directly or indirectly offer, promise, give, request, or accept any improper money, gifts, loans, commissions, positions, services, advantages, sponsorships, rewards, bribes, travel fees, hospitality, or any form of benefit. If either party is aware that any Personnel may violate the principles of integrity, they shall immediately notify the other party in writing or by email, provide relevant evidence, and cooperate with the investigation. If either party or its Personnel violates this clause, the other party may unconditionally terminate this quotation at any time and request compensation for damages. The amount of damages may be deducted from any amounts payable under this quotation. If the quotation is terminated under this clause, the provisions of Clause 5 shall not apply.


          The service license(s) granted under this quotation shall be effective from【DD/MM/YYYY】to【DD/MM/YYYY】(“Licensed Period”). By singing below, You acknowledge that You have read and agree to be bound by these terms and conditions.

                            DATE:________/_________/_________

          Authorized Signatory: n8n-person_name:{{ $('Clean & Map Data').item.json.person_details.name }}

          Title: n8n-job title:{{ $('Clean & Map Data').item.json.person_details?.job_title || '' }}

          GUI No. [ ]

          Address: n8n-address:{{ $('Clean & Map Data').item.json.org_details.address || '' }}

          Contact Person: n8n-person_name:{{ $('Clean & Map Data').item.json.person_details.name || '' }}

          Tel: n8n-tel:{{ $('Clean & Map Data').item.json.person_details.phone[0].value || ''}}

          \"},\"typeVersion\":1.2},{\"id\":\"1c66eeae-b758-4500-8324-d2a6f15f1003\",\"name\":\"Gotenberg to PDF\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[2672,176],\"parameters\":{\"url\":\"http://gotenberggotenberg.yourhost/forms/chromium/convert/html\",\"method\":\"POST\",\"options\":{\"response\":{\"response\":{\"responseFormat\":\"file\"}}},\"sendBody\":true,\"contentType\":\"multipart-form-data\",\"bodyParameters\":{\"parameters\":[{\"name\":\"files\",\"parameterType\":\"formBinaryData\",\"inputDataFieldName\":\"data\"}]}},\"typeVersion\":4.2},{\"id\":\"0c56eade-f38e-48f8-87b7-e4f8386803df\",\"name\":\"Rename PDF\",\"type\":\"n8n-nodes-base.code\",\"position\":[2896,176],\"parameters\":{\"jsCode\":\"$input.item.binary.data.fileName = 'result.pdf'\\n return $input.item;\"},\"typeVersion\":2},{\"id\":\"b7da5d6e-6a44-4b4c-b9e2-bb3aeed78de9\",\"name\":\"Get Pipedrive Custom Fields\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[432,-304],\"parameters\":{\"url\":\"https://kdanmobile.pipedrive.com/api/v1/dealFields\",\"options\":{},\"jsonHeaders\":\"{\\n \\\"Content-Type\\\": \\\"application/json\\\"\\n}\",\"sendHeaders\":true,\"authentication\":\"genericCredentialType\",\"specifyHeaders\":\"json\",\"genericAuthType\":\"httpQueryAuth\"},\"credentials\":{\"httpQueryAuth\":{\"id\":\"fQptBLiBdOmeIEzd\",\"name\":\"Pipedrive API token\"}},\"typeVersion\":4.2},{\"id\":\"9fc8335e-a975-4326-a416-345669ca90d5\",\"name\":\"Split Out Custom Fields\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[656,-304],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"data\"},\"typeVersion\":1},{\"id\":\"e1e9f24e-9093-45ce-a928-bbd73d43ad82\",\"name\":\"If Stage is 'Quotation'\",\"type\":\"n8n-nodes-base.if\",\"position\":[208,176],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"f6710bca-9bff-4c8d-8cea-ab9b8a517437\",\"operator\":{\"type\":\"number\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.data.stage_id }}\",\"rightValue\":7},{\"id\":\"6a9b26ee-fd35-441f-9826-665fe8373992\",\"operator\":{\"type\":\"number\",\"operation\":\"lt\"},\"leftValue\":\"={{ $json.previous.stage_id }}\",\"rightValue\":7}]}},\"typeVersion\":2.2},{\"id\":\"5d15907b-19f3-4d45-9320-b5404685c541\",\"name\":\"Get DottedSign Access Token\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[3344,272],\"parameters\":{\"url\":\"https://api.sandbox.dottedsign.com/v1/oauth/token\",\"method\":\"POST\",\"options\":{},\"sendBody\":true,\"sendQuery\":true,\"sendHeaders\":true,\"bodyParameters\":{\"parameters\":[{\"name\":\"grant_type\",\"value\":\"client_credentials\"},{\"name\":\"client_id\"},{\"name\":\"client_secret\"},{\"name\":\"code\"}]},\"queryParameters\":{\"parameters\":[{}]},\"headerParameters\":{\"parameters\":[{\"name\":\"accept\",\"value\":\"application/json\"},{\"name\":\"content-type\",\"value\":\"application/json\"}]}},\"typeVersion\":4.2}],\"active\":false,\"pinData\":{\"Pipedrive Trigger\":[{\"json\":{\"data\":{\"id\":1102,\"title\":\"Deal 1\",\"value\":1950,\"org_id\":1214,\"origin\":\"ManuallyCreated\",\"status\":\"open\",\"channel\":null,\"add_time\":\"2025-10-20T06:21:54Z\",\"currency\":\"TWD\",\"owner_id\":5674782,\"stage_id\":7,\"won_time\":null,\"label_ids\":[],\"lost_time\":null,\"origin_id\":null,\"person_id\":1222,\"channel_id\":null,\"close_time\":null,\"visible_to\":\"3\",\"is_archived\":false,\"lost_reason\":null,\"pipeline_id\":1,\"probability\":null,\"update_time\":\"2025-10-21T02:29:56Z\",\"archive_time\":null,\"custom_fields\":{\"085376a710a76b86622293222b048cc9c8b5809f\":null,\"10b0419f6153971fb927c1bc1e33004d37248377\":null,\"1631567a12a8c9848f7a38039ea59058711c9c81\":{\"id\":21,\"type\":\"enum\"},\"36444d22ff7c91a05ad6b13002169d7552bbce68\":null,\"3a1c7b49c503c0a07cd4bbc1cce0832259b1848d\":{\"type\":\"double\",\"value\":20},\"3ecef3e85ac838325cacbbce9a6b3543101bb638\":null,\"4957db5a993971ca8ebdc5a18a4bfbdb95c631bf\":{\"type\":\"set\",\"values\":[{\"id\":32},{\"id\":35},{\"id\":36},{\"id\":37},{\"id\":57}]},\"503bc5554fbcf7456ab01388ee8d922d72652b74\":null,\"631dce0ea3082a5f163572a006f5c5f0f2039b64\":{\"id\":42,\"type\":\"enum\"},\"85f55b6fcd3367a917675f8d4a33bb27b9d8213c\":null,\"a1c0492d8e2c34f14bc26e19c1ec9147d195130a\":null,\"ada6959920cefc4cea5439642d74199a7dc9ddee\":{\"id\":14,\"type\":\"enum\"},\"e0a4944818826f6ffd2ee931b698d02ff3b755bf\":{\"type\":\"set\",\"values\":[{\"id\":31}]},\"e1047f3eaffd194e52ae51ff4a9a45247821b2d6\":null,\"e24d56403c4134cb88b116145de99745e3488c25\":null,\"ee54481d542236715af422ce8517559d60c814b5\":{\"id\":47,\"type\":\"enum\"},\"f1a31a7081c7e11be09f04ca262bf10d73970942\":null},\"first_won_time\":null,\"creator_user_id\":5674782,\"stage_change_time\":\"2025-10-21T02:29:56Z\",\"expected_close_date\":null},\"meta\":{\"id\":\"3758a221-51e4-4d90-8a75-341ab1cbf550\",\"host\":\"kdanmobilesoftwareltd-sandbox.pipedrive.com\",\"type\":\"general\",\"action\":\"change\",\"entity\":\"deal\",\"attempt\":1,\"user_id\":\"5674782\",\"version\":\"2.0\",\"entity_id\":\"1102\",\"timestamp\":\"2025-10-21T02:29:56.276Z\",\"company_id\":\"7827175\",\"webhook_id\":\"2104704\",\"is_bulk_edit\":false,\"change_source\":\"app\",\"correlation_id\":\"5d8eaa57-65a7-4a11-8e7f-843500fbd7c4\",\"webhook_owner_id\":\"23549028\",\"permitted_user_ids\":[\"5674782\",\"11584359\",\"11775123\",\"16932806\",\"22135506\",\"23549028\"]},\"previous\":{\"stage_id\":6}}}]},\"settings\":{\"executionOrder\":\"v1\"},\"versionId\":\"4e0adb96-9b29-428b-a0e4-4d45a1b430f3\",\"connections\":{\"Aggregate\":{\"main\":[[{\"node\":\"field_mappings\",\"type\":\"main\",\"index\":0}]]},\"Aggregate1\":{\"main\":[[{\"node\":\"deal_products\",\"type\":\"main\",\"index\":0}]]},\"Get a deal\":{\"main\":[[{\"node\":\"deal_details\",\"type\":\"main\",\"index\":0}]]},\"MergeForDS\":{\"main\":[[{\"node\":\"DottedSign-CreateTask\",\"type\":\"main\",\"index\":0}]]},\"Rename PDF\":{\"main\":[[{\"node\":\"Create a file\",\"type\":\"main\",\"index\":0},{\"node\":\"Extract from File\",\"type\":\"main\",\"index\":0}]]},\"org_details\":{\"main\":[[{\"node\":\"MergeAllData\",\"type\":\"main\",\"index\":4}]]},\"Get a person\":{\"main\":[[{\"node\":\"person_details\",\"type\":\"main\",\"index\":0}]]},\"MergeAllData\":{\"main\":[[{\"node\":\"Clean & Map Data\",\"type\":\"main\",\"index\":0}]]},\"deal_details\":{\"main\":[[{\"node\":\"MergeAllData\",\"type\":\"main\",\"index\":1}]]},\"Create a file\":{\"main\":[[{\"node\":\"Get DottedSign Access Token\",\"type\":\"main\",\"index\":0}]]},\"deal_products\":{\"main\":[[{\"node\":\"MergeAllData\",\"type\":\"main\",\"index\":2}]]},\"editFlag=True\":{\"main\":[[{\"node\":\"Aggregate\",\"type\":\"main\",\"index\":0}]]},\"field_mappings\":{\"main\":[[{\"node\":\"MergeAllData\",\"type\":\"main\",\"index\":0}]]},\"person_details\":{\"main\":[[{\"node\":\"MergeAllData\",\"type\":\"main\",\"index\":3}]]},\"setProductRows\":{\"main\":[[{\"node\":\"Generate Quote HTML\",\"type\":\"main\",\"index\":0}]]},\"Convert to HTML\":{\"main\":[[{\"node\":\"Gotenberg to PDF\",\"type\":\"main\",\"index\":0}]]},\"Clean & Map Data\":{\"main\":[[{\"node\":\"setProductRows\",\"type\":\"main\",\"index\":0}]]},\"Gotenberg to PDF\":{\"main\":[[{\"node\":\"Rename PDF\",\"type\":\"main\",\"index\":0}]]},\"activity_details\":{\"main\":[[{\"node\":\"MergeAllData\",\"type\":\"main\",\"index\":5}]]},\"Extract from File\":{\"main\":[[{\"node\":\"MergeForDS\",\"type\":\"main\",\"index\":0}]]},\"Pipedrive Trigger\":{\"main\":[[{\"node\":\"If Stage is 'Quotation'\",\"type\":\"main\",\"index\":0}]]},\"Create an activity\":{\"main\":[[{\"node\":\"activity_details\",\"type\":\"main\",\"index\":0}]]},\"Generate Quote HTML\":{\"main\":[[{\"node\":\"Convert to HTML\",\"type\":\"main\",\"index\":0}]]},\"Get an organization\":{\"main\":[[{\"node\":\"org_details\",\"type\":\"main\",\"index\":0}]]},\"DottedSign-CreateTask\":{\"main\":[[]]},\"Get many deal products\":{\"main\":[[{\"node\":\"Aggregate1\",\"type\":\"main\",\"index\":0}]]},\"If Stage is 'Quotation'\":{\"main\":[[{\"node\":\"Get Pipedrive Custom Fields\",\"type\":\"main\",\"index\":0},{\"node\":\"Get a deal\",\"type\":\"main\",\"index\":0},{\"node\":\"Get many deal products\",\"type\":\"main\",\"index\":0},{\"node\":\"Get a person\",\"type\":\"main\",\"index\":0},{\"node\":\"Get an organization\",\"type\":\"main\",\"index\":0},{\"node\":\"Create an activity\",\"type\":\"main\",\"index\":0}]]},\"Split Out Custom Fields\":{\"main\":[[{\"node\":\"editFlag=True\",\"type\":\"main\",\"index\":0}]]},\"Get DottedSign Access Token\":{\"main\":[[{\"node\":\"MergeForDS\",\"type\":\"main\",\"index\":1}]]},\"Get Pipedrive Custom Fields\":{\"main\":[[{\"node\":\"Split Out Custom Fields\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 0, "complexity": "unknown", "services": [], "node_types": {}, "has_conditions": false, "has_loops": false, "has_code": false, "has_ai": false}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Generate & Send Quotation PDFs from Pipedrive to DottedSign for E-Signature"}, {"role": "assistant", "content": "\n**Analyse du besoin**: 📌 Overview\n\nDescription:\n\nThis powerful workflow automates your sales quotation process by connecting Pipedrive with DottedSign. When a deal is moved to a specific stage in Pipedrive, this template au...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 0 nodes utilisant nodes natifs.\nStructure: flux standard.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"8LJ5mlndFypZh1VS\",\"meta\":{\"instanceId\":\"cf9804b12ee62314911ec55daa0c998a73f201da1917bd31262722d206bf0f27\",\"templateCredsSetupCompleted\":true},\"name\":\"QuotationAutomation template\",\"tags\":[],\"nodes\":[{\"id\":\"2e87b077-c9bf-49c9-9d03-955bdc6615c3\",\"name\":\"Pipedrive Trigger\",\"type\":\"n8n-nodes-base.pipedriveTrigger\",\"position\":[-16,176],\"webhookId\":\"988adb20-acfa-4668-858e-f89825b8bf6a\",\"parameters\":{\"action\":\"change\",\"entity\":\"deal\"},\"credentials\":{\"pipedriveApi\":{\"id\":\"M0Osgaz0uW0e047E\",\"name\":\"Pipedrive account Sandbox\"}},\"typeVersion\":1.1},{\"id\":\"a0076d48-fc1b-4b1c-937e-9dacb05fa9a9\",\"name\":\"Get a deal\",\"type\":\"n8n-nodes-base.pipedrive\",\"position\":[1104,-112],\"parameters\":{\"dealId\":\"={{ $json.data.id }}\",\"operation\":\"get\"},\"credentials\":{\"pipedriveApi\":{\"id\":\"M0Osgaz0uW0e047E\",\"name\":\"Pipedrive account Sandbox\"}},\"typeVersion\":1},{\"id\":\"351d5e24-33ba-4d98-82c4-e76c8ea7edce\",\"name\":\"editFlag=True\",\"type\":\"n8n-nodes-base.filter\",\"position\":[880,-304],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"01e341f6-05e7-4521-8b8e-dcba0a5e818c\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json.edit_flag }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2},{\"id\":\"b9f38e9c-428e-4ea2-a503-c927419bcf2d\",\"name\":\"Get many deal products\",\"type\":\"n8n-nodes-base.pipedrive\",\"position\":[880,80],\"parameters\":{\"dealId\":\"={{ $json.meta.entity_id }}\",\"resource\":\"dealProduct\",\"operation\":\"getAll\",\"returnAll\":true},\"credentials\":{\"pipedriveApi\":{\"id\":\"M0Osgaz0uW0e047E\",\"name\":\"Pipedrive account Sandbox\"}},\"typeVersion\":1},{\"id\":\"609f3763-2ce6-479c-b35d-a67da0edda07\",\"name\":\"setProductRows\",\"type\":\"n8n-nodes-base.code\",\"position\":[2000,176],\"parameters\":{\"jsCode\":\"// n8n Code Node (or similar Javascript environment)\\n\\nconst items = $input.first().json.deal_products;\\nlet htmlRows = '';\\n\\nfor (const item of items) {\\n // 修正後的版本:100% 匹配您的原版範本的結構和 CSS Class\\n let singleRowHtml = `\\n \\n \\n

          \\n ${item.name}\\n

          \\n \\n \\n

          \\n ${item.quantity}\\n

          \\n \\n \\n

          \\n ${item.currency} ${parseFloat(item.item_price).toFixed(2)}\\n

          \\n \\n \\n

          \\n ${item.discount}%\\n

          \\n \\n \\n

          \\n ${item.currency} ${parseFloat(item.sum).toFixed(2)}\\n

          \\n \\n \\n `;\\n // 清理換行和多餘空格,確保 HTML 乾淨\\n htmlRows += singleRowHtml.replace(/\\\\n\\\\s*/g, '');\\n}\\n\\nreturn { table_rows_html: htmlRows };\"},\"typeVersion\":2},{\"id\":\"8667563a-03d9-4d64-aff0-8d76deb7c853\",\"name\":\"Get a person\",\"type\":\"n8n-nodes-base.pipedrive\",\"position\":[1104,272],\"parameters\":{\"personId\":\"={{ $json.data.person_id }}\",\"resource\":\"person\",\"operation\":\"get\"},\"credentials\":{\"pipedriveApi\":{\"id\":\"M0Osgaz0uW0e047E\",\"name\":\"Pipedrive account Sandbox\"}},\"typeVersion\":1},{\"id\":\"ee372227-55b8-40cc-800a-d9e5aa1d3d37\",\"name\":\"field_mappings\",\"type\":\"n8n-nodes-base.set\",\"position\":[1328,-304],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"6b1137c7-df7e-41be-8555-9860db142e74\",\"name\":\"field_mappings\",\"type\":\"object\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"0cd3669f-1e1f-4d8e-a9a2-35b39f61d132\",\"name\":\"deal_details\",\"type\":\"n8n-nodes-base.set\",\"position\":[1328,-112],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"72ee9f3f-178c-457b-981a-09ae60fca3ea\",\"name\":\"deal_details\",\"type\":\"object\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"8b6c48fa-451e-45d6-b86f-4a15782d60af\",\"name\":\"person_details\",\"type\":\"n8n-nodes-base.set\",\"position\":[1328,272],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"b779769c-f9b4-48a1-8bfe-7827baf990b1\",\"name\":\"person_details\",\"type\":\"object\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"1c0268a7-490b-4b3f-a7db-458bace5c6d1\",\"name\":\"deal_products\",\"type\":\"n8n-nodes-base.set\",\"position\":[1328,80],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"13d41759-702c-4639-a184-615096f89a02\",\"name\":\"deal_products\",\"type\":\"object\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"e37cb8c9-fc54-4cad-973c-921fd1f7392c\",\"name\":\"Aggregate\",\"type\":\"n8n-nodes-base.aggregate\",\"position\":[1104,-304],\"parameters\":{\"options\":{},\"aggregate\":\"aggregateAllItemData\"},\"typeVersion\":1},{\"id\":\"74ff239d-aff4-462f-96b6-57ebf65df4c4\",\"name\":\"Aggregate1\",\"type\":\"n8n-nodes-base.aggregate\",\"position\":[1104,80],\"parameters\":{\"options\":{},\"aggregate\":\"aggregateAllItemData\"},\"typeVersion\":1},{\"id\":\"9465410d-f738-4d0d-bbf5-7132a440c21e\",\"name\":\"Get an organization\",\"type\":\"n8n-nodes-base.pipedrive\",\"position\":[1104,464],\"parameters\":{\"resource\":\"organization\",\"operation\":\"get\",\"organizationId\":\"={{ $json.data.org_id }}\"},\"credentials\":{\"pipedriveApi\":{\"id\":\"M0Osgaz0uW0e047E\",\"name\":\"Pipedrive account Sandbox\"}},\"typeVersion\":1},{\"id\":\"a11a4440-9c19-4d22-bdc9-09cc26a7ab74\",\"name\":\"org_details\",\"type\":\"n8n-nodes-base.set\",\"position\":[1328,464],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"baad2fc7-b3e8-45af-a45f-1bebf88dbf79\",\"name\":\"org_details\",\"type\":\"object\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"14ba18cc-36cd-41f8-8c2d-42c263c7364a\",\"name\":\"Convert to HTML\",\"type\":\"n8n-nodes-base.convertToFile\",\"position\":[2448,176],\"parameters\":{\"options\":{\"encoding\":\"utf8\",\"fileName\":\"index.html\",\"mimeType\":\"text/html\",\"dataIsBase64\":false},\"operation\":\"toBinary\",\"sourceProperty\":\"html\"},\"typeVersion\":1},{\"id\":\"b1005793-6c53-429c-afac-c957994391f5\",\"name\":\"Create a file\",\"type\":\"n8n-nodes-base.pipedrive\",\"position\":[3120,272],\"parameters\":{\"resource\":\"file\",\"additionalFields\":{\"deal_id\":\"={{ $('Clean & Map Data').item.json.id }}\",\"activity_id\":\"={{ $('Create an activity').item.json.id }}\"},\"binaryPropertyName\":\"=data\"},\"credentials\":{\"pipedriveApi\":{\"id\":\"M0Osgaz0uW0e047E\",\"name\":\"Pipedrive account Sandbox\"}},\"typeVersion\":1},{\"id\":\"25e7bbe7-3bd6-4968-aff5-92e1a2c48876\",\"name\":\"Create an activity\",\"type\":\"n8n-nodes-base.pipedrive\",\"position\":[1104,656],\"parameters\":{\"type\":\"Quoatation\",\"subject\":\"=Quotation/ {{ $json.data.id }}/{{ $json.data.update_time.toDateTime().format('yyyyMMdd') }}\",\"resource\":\"activity\",\"additionalFields\":{\"deal_id\":\"={{ $json.data.id }}\"}},\"credentials\":{\"pipedriveApi\":{\"id\":\"M0Osgaz0uW0e047E\",\"name\":\"Pipedrive account Sandbox\"}},\"typeVersion\":1},{\"id\":\"276e0728-344b-4ef3-bf31-16b6aeacc898\",\"name\":\"activity_details\",\"type\":\"n8n-nodes-base.set\",\"position\":[1328,656],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"baad2fc7-b3e8-45af-a45f-1bebf88dbf79\",\"name\":\"activity_details\",\"type\":\"object\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"ab6a37ee-a249-46ea-b335-3b9c20bcc8ab\",\"name\":\"DottedSign-CreateTask\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[3792,176],\"parameters\":{\"url\":\"https://api.sandbox.dottedsign.com/v1/sign_tasks\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"has_order\\\": false,\\n \\\"start\\\": true,\\n \\\"stages\\\": [\\n {\\n \\\"field_settings\\\": [\\n {\\n \\\"field_type\\\": \\\"signature\\\",\\n \\\"coord\\\": [92.0, 237.0, 353.0, 274.0],\\n \\\"options\\\": { \\\"placeholder\\\": \\\"signhere\\\" },\\n \\\"page\\\": 1\\n }\\n ],\\n \\\"stage_setting\\\": {\\n \\\"informable\\\": true,\\n \\\"reviewed_skip_confirm\\\": true\\n },\\n \\\"name\\\": \\\"{{ $('Clean & Map Data').item.json.person_details.name }}\\\",\\n \\\"email\\\": \\\"{{ $('Clean & Map Data').item.json.person_details.email[0].value }}\\\",\\n \\\"stage_type\\\": \\\"sign\\\"\\n }\\n ],\\n \\\"task_setting\\\": {\\n \\\"cc_infos\\\": [\\n {\\n \\\"email\\\": \\\"{{ $('Clean & Map Data').item.json.person_details.owner_id.email }}\\\",\\n \\\"name\\\": \\\"{{ $('Clean & Map Data').item.json.person_details.owner_id.name }}\\\" }],\\n \\\"receiver_lang\\\": \\\"en\\\",\\n \\\"owner_informable\\\": true\\n },\\n \\\"base64_file\\\": \\\"{{ $json.data }}\\\",\\n \\\"file_name\\\": \\\"{{ $('Clean & Map Data').item.json.title.replace(/[\\\\\\\"*:<>\\\\?\\\\/\\\\\\\\|~#%&{}]/g, '_') }}.pdf\\\"\\n}\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"accept\",\"value\":\"application/json\"},{\"name\":\"Authorization\",\"value\":\"=Bearer {{ $json.access_token }}\"},{\"name\":\"content-type\",\"value\":\"application/json\"}]}},\"typeVersion\":4.2},{\"id\":\"60cc6b34-70f4-4900-a7cb-0a16ee987344\",\"name\":\"Extract from File\",\"type\":\"n8n-nodes-base.extractFromFile\",\"position\":[3344,80],\"parameters\":{\"options\":{},\"operation\":\"binaryToPropery\"},\"typeVersion\":1,\"alwaysOutputData\":true},{\"id\":\"de55a7d7-c151-4270-b356-ff6600ced25a\",\"name\":\"Sticky Note\",\"type\":\"n8n-nodes-base.stickyNote\",\"position\":[-1200,-560],\"parameters\":{\"width\":1056,\"height\":752,\"content\":\"## 📌 Overview\\n**Title:** `Automate Quotation Generation from Pipedrive to DottedSign`\\n**Description:**\\nThis powerful workflow automates your sales quotation process by connecting Pipedrive with DottedSign. When a deal is moved to a specific stage in Pipedrive, this template automatically generates a professional PDF quotation, uploads it back to the deal, and sends it out for e-signature via DottedSign service, saving your sales team valuable time and eliminating manual work.\\n## What it does\\nWhen a Pipedrive deal moves to a designated stage (e.g., \\\"Quotation Stage\\\"), this workflow triggers and performs the following actions:\\n1. **Gathers Data:** It collects all relevant information, including deal details, client contacts, organization info, and associated products from Pipedrive.\\n2. **Generates PDF Quote:** It populates a customizable HTML template with the collected data and uses a PDF generation service (Gotenberg) to create a polished PDF document.\\n3. **Uploads to Pipedrive:** The generated PDF quote is automatically uploaded to the \\\"Files\\\" section of the corresponding Pipedrive deal for record-keeping.\\n4. **Sends for E-Signature:** It creates a new signing task in DottedSign, sending the quotation to the client for their electronic signature.\\n## Requirements\\n- A Pipedrive account with admin permissions.\\n- A DottedSign developer account to obtain API credentials.\\n- A self-hosted instance of [Gotenberg](https://gotenberg.dev/docs/getting-started/installation) for HTML to PDF conversion.\\n## How to set up\\n1. **Pipedrive Trigger Stage:** In the `If` node, change the stage ID `7` to the ID of the pipeline stage you want to use as the trigger.\\n2. **PDF Conversion Service:** In the `Gotenberg to PDF` (HTTP Request) node, replace the placeholder URL with the endpoint of your running Gotenberg instance.\\n3. **DottedSign Credentials:** In the `Get DottedSign Access Token` node, enter your `client_id` and `client_secret` in the request body.\\n4. **DottedSign Signature Field:** In the `Create DottedSign Task` node, you **must** adjust the `page` and `coord` values under `field_settings` to match the desired signature location on your PDF template.\\n## How to customize the workflow\\n- **Quotation Template:** Edit the `Generate Quotation HTML` node to modify the quote's appearance, text, company logo, and terms. The `{{ ... }}` expressions are placeholders that are filled with Pipedrive data.\\n- **Trigger:** Replace the Pipedrive Trigger with another trigger, such as a webhook or a form submission, to adapt the workflow to different needs.\\n- **Notifications:** Add a Slack or email node at the end of the workflow to notify the sales team once the quotation has been sent.\"},\"typeVersion\":1},{\"id\":\"cc8f8665-c85f-4e05-bdba-fcd560a7aba0\",\"name\":\"Sticky Note2\",\"type\":\"n8n-nodes-base.stickyNote\",\"position\":[-48,-560],\"parameters\":{\"color\":3,\"width\":1504,\"height\":1504,\"content\":\"## **STEP 1: Trigger & Data Collection**\\n\\n* **Pipedrive Trigger**: Watches for any change in a Pipedrive deal.\\n* **If**: Checks if the deal was moved to Specific Stage . The workflow will start execute.\\n* **Data Collection**: If the condition is true, it fetches all necessary data: Deal details, Person, Organization, Products, and Custom Field definitions (Optional).\"},\"typeVersion\":1},{\"id\":\"ffe36349-2631-4001-94cb-33068ef48be8\",\"name\":\"Sticky Note3\",\"type\":\"n8n-nodes-base.stickyNote\",\"position\":[1520,-144],\"parameters\":{\"width\":640,\"height\":752,\"content\":\"## **STEP 2: Data Processing** \\n\\n* **Set Nodes**: Rename different data streams for clarity (e.g., `deal_details`, `person_details`).\\n* **Merge**: Combines all the separate data into a single object.\\n* **Code (Main)** It cleans up the data and converts technical customfieldIDs mapping with string text.\"},\"typeVersion\":1},{\"id\":\"bfb48e6f-0b00-438b-a5e1-ec79d703508f\",\"name\":\"Sticky Note4\",\"type\":\"n8n-nodes-base.stickyNote\",\"position\":[2176,-32],\"parameters\":{\"color\":4,\"width\":848,\"height\":464,\"content\":\"## **STEP 3: PDF Generation**\\n\\n* **setProductRows**: This Code node dynamically creates the HTML table rows for the product list.\\n* **HTML**: This is the main template. It takes the processed data and fills it into the HTML layout.\\n* **Convert to HTML -> convert to PDF**: Turns the final HTML into a binary file, then sends it to the Gotenberg service to create the PDF.\"},\"typeVersion\":1},{\"id\":\"02b99292-f1df-4343-a2d6-e29b7d96b147\",\"name\":\"Sticky Note5\",\"type\":\"n8n-nodes-base.stickyNote\",\"position\":[3072,-128],\"parameters\":{\"width\":944,\"height\":688,\"content\":\"## **STEP 4: Final Actions**\\n\\n* **Create a file**: Uploads the newly created PDF to the Pipedrive deal's \\\"Files\\\" section.\\n* **Extract from File**: Converts the PDF into Base64 format, which is required by the DottedSign API.\\n* **DottedSign-GetAccessToken**: Gets a temporary API token from DottedSign.\\n* **DottedSign-CreateTask**: Sends the PDF and signer info to DottedSign to start the e-signature process.\"},\"typeVersion\":1},{\"id\":\"891f3d99-0b53-468c-a95e-ea84fa420ef9\",\"name\":\"MergeAllData\",\"type\":\"n8n-nodes-base.merge\",\"position\":[1552,112],\"parameters\":{\"mode\":\"combine\",\"options\":{\"includeUnpaired\":true},\"combineBy\":\"combineByPosition\",\"numberInputs\":6},\"typeVersion\":3.2},{\"id\":\"6a653173-a497-4fa0-88ae-ffdee6cb14ed\",\"name\":\"MergeForDS\",\"type\":\"n8n-nodes-base.merge\",\"position\":[3568,176],\"parameters\":{\"mode\":\"combine\",\"options\":{},\"combineBy\":\"combineByPosition\"},\"typeVersion\":3.2,\"alwaysOutputData\":true},{\"id\":\"647168e9-bd89-4cfb-b314-2375f9123d18\",\"name\":\"Clean & Map Data\",\"type\":\"n8n-nodes-base.code\",\"position\":[1776,176],\"parameters\":{\"jsCode\":\"\\nconst inputData = $input.item.json;\\n\\n\\nconst dealData = inputData.deal_details;\\nconst personData = inputData.person_details;\\nconst orgData = inputData.org_details;\\n// 從聚合後的物件中提取陣列\\nconst dealProducts = inputData.deal_products?.data || [];\\nconst fieldMappingsArray = inputData.field_mappings?.data || [];\\n\\n\\nif (!dealData) {\\n throw new Error(\\\"Deal data (deal_details) is missing from the input. Check the Merge node and its inputs.\\\");\\n}\\n\\n\\nconst fieldMapping = {};\\nfor (const field of fieldMappingsArray) {\\n if (field.key && field.name) {\\n fieldMapping[field.key] = field.name;\\n\\n if ((field.field_type === 'enum' || field.field_type === 'set') && field.options) {\\n fieldMapping[field.key + '_options'] = field.options;\\n }\\n }\\n}\\n\\n\\nconst cleanedDeal = {};\\n\\n\\nfor (const key in dealData) {\\n if (dealData.hasOwnProperty(key)) {\\n let value = dealData[key];\\n\\n\\n if (fieldMapping[key]) {\\n const fieldName = fieldMapping[key];\\n const options = fieldMapping[key + '_options'];\\n\\n\\n if (options && (typeof value === 'string' || typeof value === 'number')) {\\n const valueArray = String(value).split(',').map(s => s.trim());\\n const labels = valueArray.map(val => {\\n const option = options.find(opt => String(opt.id) === val);\\n return option ? option.label : val; \\n });\\n cleanedDeal[fieldName] = (valueArray.length > 1) ? labels : labels[0];\\n } else if (value && typeof value === 'object' && value !== null && value.name !== undefined) {\\n cleanedDeal[fieldName] = value.name;\\n } else if (value && typeof value === 'object' && value !== null && value.value !== undefined) {\\n cleanedDeal[fieldName] = value.value;\\n } else {\\n cleanedDeal[fieldName] = value;\\n }\\n\\n } else if (key.endsWith('_id') && typeof value === 'object' && value !== null && value.name !== undefined) {\\n cleanedDeal[key.replace('_id', '_name')] = value.name;\\n\\n } else {\\n cleanedDeal[key] = value;\\n }\\n }\\n}\\n\\n\\nif (personData) {\\n cleanedDeal.person_details = personData;\\n}\\nif (orgData) {\\n cleanedDeal.org_details = orgData;\\n}\\nif (dealProducts.length > 0) {\\n cleanedDeal.deal_products = dealProducts;\\n}\\n\\n\\nreturn [{\\n json: cleanedDeal\\n}];\"},\"typeVersion\":2},{\"id\":\"c7724bac-4f45-4d31-96ab-78e09e9604e5\",\"name\":\"Generate Quote HTML\",\"type\":\"n8n-nodes-base.html\",\"position\":[2224,176],\"parameters\":{\"html\":\"

          YOUR COMPANY NAME.

          YOUR COMPANY ADDRESS,

          YOUR COMPANY ADDRESS

          Phone: YOUR COMPANY PHONE

          YOUR COMPANY WEBSITE  

          Contact Person: n8n-user_name:{{ $('Clean & Map Data').item.json.user_name }}

          QUOTATION

          QUO-NO # n8n-deal_id:{{ $('Clean & Map Data').item.json.id }}

          DATE: n8n-date:{{ $('Clean & Map Data').item.json.update_time.toDateTime().format('yyyy-MM-dd') }}

          Quote To:_____n8n-org_name:{{ $('Clean & Map Data').item.json.org_name }}______(“You”or “Your”)

          {{ $('setProductRows').item.json.table_rows_html }}

          Description

          Quantity

          Unit Price

          Discount

          Amount

          Sub Total

          {{ $('Clean & Map Data').item.json.currency }} {{ $('Clean & Map Data').item.json.value }}

          Shipping

          {{ $('Clean & Map Data').item.json.currency }}

          Tax (5%)

          {{ $('Clean & Map Data').item.json.currency }}

          Total

          {{ $('Clean & Map Data').item.json.currency }} {{ $('Clean & Map Data').item.json.value }}

          Note:

          1. This quotation takes effect when You have completed the signing and return the electronic files (including scanned files or PDFs) of the quotation by facsimile or electronic transmission or other means to Kdan Mobile Software Ltd (“we”,”us”, or”our”). Upon the effective date of this quotation, if You would like to postpone the activation date of the service license(s) or adjust the number of activated licenses within the licensed quantity due to Your internal considerations or other reasons not attributable to us, You shall notify us in writing or by email and obtain our consent. However, You understand and agree that under such circumstances, the Licensed Period stipulated in this Quotation shall remain unaffected. If there are any licenses that remain unactivated upon the expiration of the Licensed Period, You acknowledge and agree that we shall no longer activate such remaining licenses and shall not provide any refund or extension. You shall not assert any claim against us in this regard. The foregoing shall not affect Your payment obligations under this Quotation, and You shall still make full payment in accordance with the relevant provisions herein.
          2. If neither party raises any objections 30 days prior to the expiration of DottedSign licensing period, this quotation will be automatically renewed for one year under the same terms and conditions.\"
          3. When You use DottedSign, You agree to comply with the “Terms of Use” (https://www.dottedsign.com/terms_of_service) in our official website.
          4. Unless otherwise specified in this quotation, you have the right to terminate the quotation without any reason within the period, which starting fromMM/DD/YYYY to 30 days after the date of account activation by us (the “Termination Period”). Once You terminate the quotation within the Termination Period, You should provide notice in writing or electronically to us and You must pay equal to 20% of the total License Fee to us(the “Termination Fee”); however, if You terminate the quotation before the date of account activation, the Termination Fee would be deducted to equal to 15% of the total License Fee. After the Termination Period, You are not entitled to terminate the quotation.
          5. The quotation terminate from the date we receive Your termination notice (the” termination day”). We have the right to deduct the Termination fee, the subscription fee incurred by You in accessing our service before the termination date(Less than one day, shall be calculate as one day), and any other damages from the refund. All refunds are not eligible for interest.
          6. Payment instructions: we must received full amount of the payment, You agree to pay all charges incurred by the transaction.
          7. Within thirty(30) days after You sign and return the quotation to us, You must pay the total amount to the payment link designated by us by credit card. Under the condition that \"to pay the service fee within a specified period after the issuance of the invoice,\" if the payment is not made within the agreed period, we reserves the right to calculate late payment interest at an annual rate of 5%, temporarily suspend the provision of services, and, if deemed necessary, unilaterally terminate this quotation. Under the other condition that \"to prepay the service fee before the issuance of the invoice,\" if the payment is not made within the agreed period, we reserves the right to withhold the account activation and unilaterally terminate this quotation.
          8. You hereby grant to us as well as the subsidiaries and affiliates of us( hereinafter collectively referred to as “Kdan Group Companies”) a royalty-free and perpetual license to use Your corporation mark (including trademarks, trade names, and logos ) in marketing, sales, and public relations material to identify You as a Kdan Group Companies’ partner.
          9. Both parties agree that this quotation shall be presented in electronic records. And this quotation could be signed using an electronic signature.
          10. In the event of any conflict or inconsistency between the terms and conditions of this quotation and the terms of contracts agreed by both parties someday, the provisions of those contracts shall prevail.
          11. During the performance of the quotation, both parties agree to enter into written supplementary agreement for any matter not covered by this quotation.
          12. If You do not sign and return the quotation within one month after we send it to You, the quotation will lapse automatically.
          13. This quotation shall be construed in accordance with the laws of the Republic of China (Taiwan). The Parties agree that the conditions set forth hereunder shall be performed in the utmost spirit of goodwill and good faith. In the event of a dispute, the Parties agree that the Taiwan Taipei District Court shall be the court of first instance.
          14. We are committed to protecting the security of Your personal data and information. Any personal data provided by You, as well as any information obtained through the use of our website or services, is managed and protected in accordance with our Privacy Policy and Security Policy. You acknowledge and agree that any information You obtain about others through the use of our website or services will also be subject to the regulations of our Privacy Policy and Security Policy. For more details, please refer to the following link:

          Privacy Policy:https://dottedsign.com/privacy_policy

          Security Policy:https://dottedsign.com/security

          1. Both parties shall conduct their business activities based on the principles of integrity. Both parties agree that during the process of signing and fulfilling the purpose of this quotation, neither party nor its directors, managers, employees, agents, or persons with substantial control (collectively referred to as \"Personnel\") shall directly or indirectly offer, promise, give, request, or accept any improper money, gifts, loans, commissions, positions, services, advantages, sponsorships, rewards, bribes, travel fees, hospitality, or any form of benefit. If either party is aware that any Personnel may violate the principles of integrity, they shall immediately notify the other party in writing or by email, provide relevant evidence, and cooperate with the investigation. If either party or its Personnel violates this clause, the other party may unconditionally terminate this quotation at any time and request compensation for damages. The amount of damages may be deducted from any amounts payable under this quotation. If the quotation is terminated under this clause, the provisions of Clause 5 shall not apply.


          The service license(s) granted under this quotation shall be effective from【DD/MM/YYYY】to【DD/MM/YYYY】(“Licensed Period”). By singing below, You acknowledge that You have read and agree to be bound by these terms and conditions.

                            DATE:________/_________/_________

          Authorized Signatory: n8n-person_name:{{ $('Clean & Map Data').item.json.person_details.name }}

          Title: n8n-job title:{{ $('Clean & Map Data').item.json.person_details?.job_title || '' }}

          GUI No. [ ]

          Address: n8n-address:{{ $('Clean & Map Data').item.json.org_details.address || '' }}

          Contact Person: n8n-person_name:{{ $('Clean & Map Data').item.json.person_details.name || '' }}

          Tel: n8n-tel:{{ $('Clean & Map Data').item.json.person_details.phone[0].value || ''}}

          \"},\"typeVersion\":1.2},{\"id\":\"1c66eeae-b758-4500-8324-d2a6f15f1003\",\"name\":\"Gotenberg to PDF\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[2672,176],\"parameters\":{\"url\":\"http://gotenberggotenberg.yourhost/forms/chromium/convert/html\",\"method\":\"POST\",\"options\":{\"response\":{\"response\":{\"responseFormat\":\"file\"}}},\"sendBody\":true,\"contentType\":\"multipart-form-data\",\"bodyParameters\":{\"parameters\":[{\"name\":\"files\",\"parameterType\":\"formBinaryData\",\"inputDataFieldName\":\"data\"}]}},\"typeVersion\":4.2},{\"id\":\"0c56eade-f38e-48f8-87b7-e4f8386803df\",\"name\":\"Rename PDF\",\"type\":\"n8n-nodes-base.code\",\"position\":[2896,176],\"parameters\":{\"jsCode\":\"$input.item.binary.data.fileName = 'result.pdf'\\n return $input.item;\"},\"typeVersion\":2},{\"id\":\"b7da5d6e-6a44-4b4c-b9e2-bb3aeed78de9\",\"name\":\"Get Pipedrive Custom Fields\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[432,-304],\"parameters\":{\"url\":\"https://kdanmobile.pipedrive.com/api/v1/dealFields\",\"options\":{},\"jsonHeaders\":\"{\\n \\\"Content-Type\\\": \\\"application/json\\\"\\n}\",\"sendHeaders\":true,\"authentication\":\"genericCredentialType\",\"specifyHeaders\":\"json\",\"genericAuthType\":\"httpQueryAuth\"},\"credentials\":{\"httpQueryAuth\":{\"id\":\"fQptBLiBdOmeIEzd\",\"name\":\"Pipedrive API token\"}},\"typeVersion\":4.2},{\"id\":\"9fc8335e-a975-4326-a416-345669ca90d5\",\"name\":\"Split Out Custom Fields\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[656,-304],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"data\"},\"typeVersion\":1},{\"id\":\"e1e9f24e-9093-45ce-a928-bbd73d43ad82\",\"name\":\"If Stage is 'Quotation'\",\"type\":\"n8n-nodes-base.if\",\"position\":[208,176],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"f6710bca-9bff-4c8d-8cea-ab9b8a517437\",\"operator\":{\"type\":\"number\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.data.stage_id }}\",\"rightValue\":7},{\"id\":\"6a9b26ee-fd35-441f-9826-665fe8373992\",\"operator\":{\"type\":\"number\",\"operation\":\"lt\"},\"leftValue\":\"={{ $json.previous.stage_id }}\",\"rightValue\":7}]}},\"typeVersion\":2.2},{\"id\":\"5d15907b-19f3-4d45-9320-b5404685c541\",\"name\":\"Get DottedSign Access Token\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[3344,272],\"parameters\":{\"url\":\"https://api.sandbox.dottedsign.com/v1/oauth/token\",\"method\":\"POST\",\"options\":{},\"sendBody\":true,\"sendQuery\":true,\"sendHeaders\":true,\"bodyParameters\":{\"parameters\":[{\"name\":\"grant_type\",\"value\":\"client_credentials\"},{\"name\":\"client_id\"},{\"name\":\"client_secret\"},{\"name\":\"code\"}]},\"queryParameters\":{\"parameters\":[{}]},\"headerParameters\":{\"parameters\":[{\"name\":\"accept\",\"value\":\"application/json\"},{\"name\":\"content-type\",\"value\":\"application/json\"}]}},\"typeVersion\":4.2}],\"active\":false,\"pinData\":{\"Pipedrive Trigger\":[{\"json\":{\"data\":{\"id\":1102,\"title\":\"Deal 1\",\"value\":1950,\"org_id\":1214,\"origin\":\"ManuallyCreated\",\"status\":\"open\",\"channel\":null,\"add_time\":\"2025-10-20T06:21:54Z\",\"currency\":\"TWD\",\"owner_id\":5674782,\"stage_id\":7,\"won_time\":null,\"label_ids\":[],\"lost_time\":null,\"origin_id\":null,\"person_id\":1222,\"channel_id\":null,\"close_time\":null,\"visible_to\":\"3\",\"is_archived\":false,\"lost_reason\":null,\"pipeline_id\":1,\"probability\":null,\"update_time\":\"2025-10-21T02:29:56Z\",\"archive_time\":null,\"custom_fields\":{\"085376a710a76b86622293222b048cc9c8b5809f\":null,\"10b0419f6153971fb927c1bc1e33004d37248377\":null,\"1631567a12a8c9848f7a38039ea59058711c9c81\":{\"id\":21,\"type\":\"enum\"},\"36444d22ff7c91a05ad6b13002169d7552bbce68\":null,\"3a1c7b49c503c0a07cd4bbc1cce0832259b1848d\":{\"type\":\"double\",\"value\":20},\"3ecef3e85ac838325cacbbce9a6b3543101bb638\":null,\"4957db5a993971ca8ebdc5a18a4bfbdb95c631bf\":{\"type\":\"set\",\"values\":[{\"id\":32},{\"id\":35},{\"id\":36},{\"id\":37},{\"id\":57}]},\"503bc5554fbcf7456ab01388ee8d922d72652b74\":null,\"631dce0ea3082a5f163572a006f5c5f0f2039b64\":{\"id\":42,\"type\":\"enum\"},\"85f55b6fcd3367a917675f8d4a33bb27b9d8213c\":null,\"a1c0492d8e2c34f14bc26e19c1ec9147d195130a\":null,\"ada6959920cefc4cea5439642d74199a7dc9ddee\":{\"id\":14,\"type\":\"enum\"},\"e0a4944818826f6ffd2ee931b698d02ff3b755bf\":{\"type\":\"set\",\"values\":[{\"id\":31}]},\"e1047f3eaffd194e52ae51ff4a9a45247821b2d6\":null,\"e24d56403c4134cb88b116145de99745e3488c25\":null,\"ee54481d542236715af422ce8517559d60c814b5\":{\"id\":47,\"type\":\"enum\"},\"f1a31a7081c7e11be09f04ca262bf10d73970942\":null},\"first_won_time\":null,\"creator_user_id\":5674782,\"stage_change_time\":\"2025-10-21T02:29:56Z\",\"expected_close_date\":null},\"meta\":{\"id\":\"3758a221-51e4-4d90-8a75-341ab1cbf550\",\"host\":\"kdanmobilesoftwareltd-sandbox.pipedrive.com\",\"type\":\"general\",\"action\":\"change\",\"entity\":\"deal\",\"attempt\":1,\"user_id\":\"5674782\",\"version\":\"2.0\",\"entity_id\":\"1102\",\"timestamp\":\"2025-10-21T02:29:56.276Z\",\"company_id\":\"7827175\",\"webhook_id\":\"2104704\",\"is_bulk_edit\":false,\"change_source\":\"app\",\"correlation_id\":\"5d8eaa57-65a7-4a11-8e7f-843500fbd7c4\",\"webhook_owner_id\":\"23549028\",\"permitted_user_ids\":[\"5674782\",\"11584359\",\"11775123\",\"16932806\",\"22135506\",\"23549028\"]},\"previous\":{\"stage_id\":6}}}]},\"settings\":{\"executionOrder\":\"v1\"},\"versionId\":\"4e0adb96-9b29-428b-a0e4-4d45a1b430f3\",\"connections\":{\"Aggregate\":{\"main\":[[{\"node\":\"field_mappings\",\"type\":\"main\",\"index\":0}]]},\"Aggregate1\":{\"main\":[[{\"node\":\"deal_products\",\"type\":\"main\",\"index\":0}]]},\"Get a deal\":{\"main\":[[{\"node\":\"deal_details\",\"type\":\"main\",\"index\":0}]]},\"MergeForDS\":{\"main\":[[{\"node\":\"DottedSign-CreateTask\",\"type\":\"main\",\"index\":0}]]},\"Rename PDF\":{\"main\":[[{\"node\":\"Create a file\",\"type\":\"main\",\"index\":0},{\"node\":\"Extract from File\",\"type\":\"main\",\"index\":0}]]},\"org_details\":{\"main\":[[{\"node\":\"MergeAllData\",\"type\":\"main\",\"index\":4}]]},\"Get a person\":{\"main\":[[{\"node\":\"person_details\",\"type\":\"main\",\"index\":0}]]},\"MergeAllData\":{\"main\":[[{\"node\":\"Clean & Map Data\",\"type\":\"main\",\"index\":0}]]},\"deal_details\":{\"main\":[[{\"node\":\"MergeAllData\",\"type\":\"main\",\"index\":1}]]},\"Create a file\":{\"main\":[[{\"node\":\"Get DottedSign Access Token\",\"type\":\"main\",\"index\":0}]]},\"deal_products\":{\"main\":[[{\"node\":\"MergeAllData\",\"type\":\"main\",\"index\":2}]]},\"editFlag=True\":{\"main\":[[{\"node\":\"Aggregate\",\"type\":\"main\",\"index\":0}]]},\"field_mappings\":{\"main\":[[{\"node\":\"MergeAllData\",\"type\":\"main\",\"index\":0}]]},\"person_details\":{\"main\":[[{\"node\":\"MergeAllData\",\"type\":\"main\",\"index\":3}]]},\"setProductRows\":{\"main\":[[{\"node\":\"Generate Quote HTML\",\"type\":\"main\",\"index\":0}]]},\"Convert to HTML\":{\"main\":[[{\"node\":\"Gotenberg to PDF\",\"type\":\"main\",\"index\":0}]]},\"Clean & Map Data\":{\"main\":[[{\"node\":\"setProductRows\",\"type\":\"main\",\"index\":0}]]},\"Gotenberg to PDF\":{\"main\":[[{\"node\":\"Rename PDF\",\"type\":\"main\",\"index\":0}]]},\"activity_details\":{\"main\":[[{\"node\":\"MergeAllData\",\"type\":\"main\",\"index\":5}]]},\"Extract from File\":{\"main\":[[{\"node\":\"MergeForDS\",\"type\":\"main\",\"index\":0}]]},\"Pipedrive Trigger\":{\"main\":[[{\"node\":\"If Stage is 'Quotation'\",\"type\":\"main\",\"index\":0}]]},\"Create an activity\":{\"main\":[[{\"node\":\"activity_details\",\"type\":\"main\",\"index\":0}]]},\"Generate Quote HTML\":{\"main\":[[{\"node\":\"Convert to HTML\",\"type\":\"main\",\"index\":0}]]},\"Get an organization\":{\"main\":[[{\"node\":\"org_details\",\"type\":\"main\",\"index\":0}]]},\"DottedSign-CreateTask\":{\"main\":[[]]},\"Get many deal products\":{\"main\":[[{\"node\":\"Aggregate1\",\"type\":\"main\",\"index\":0}]]},\"If Stage is 'Quotation'\":{\"main\":[[{\"node\":\"Get Pipedrive Custom Fields\",\"type\":\"main\",\"index\":0},{\"node\":\"Get a deal\",\"type\":\"main\",\"index\":0},{\"node\":\"Get many deal products\",\"type\":\"main\",\"index\":0},{\"node\":\"Get a person\",\"type\":\"main\",\"index\":0},{\"node\":\"Get an organization\",\"type\":\"main\",\"index\":0},{\"node\":\"Create an activity\",\"type\":\"main\",\"index\":0}]]},\"Split Out Custom Fields\":{\"main\":[[{\"node\":\"editFlag=True\",\"type\":\"main\",\"index\":0}]]},\"Get DottedSign Access Token\":{\"main\":[[{\"node\":\"MergeForDS\",\"type\":\"main\",\"index\":1}]]},\"Get Pipedrive Custom Fields\":{\"main\":[[{\"node\":\"Split Out Custom Fields\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 0, "complexity": "unknown", "services": [], "node_types": {}, "has_conditions": false, "has_loops": false, "has_code": false, "has_ai": false}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: Overview This comprehensive n8n workflow automatically transforms trending Google search queries into engaging LinkedIn posts using AI. The system runs autonomously, discovering viral topics, researching content, and publishing professionally formatted posts to grow your social media presence. Workflow Description Automate your entire social media content pipeline - from trend discovery to publication. This workflow monitors Google Trends, selects high-potential topics, creates human-like content using advanced AI, and publishes across multiple social platforms with built-in tracking. Key Features Automated Trend Discovery: Pulls trending topics from Google Trends API with customizable filters Intelligent Topic Selection: AI chooses the most relevant trending topic for your niche Multi-AI "}, {"role": "assistant", "content": "\n**Analyse du besoin**: Overview\n\nThis comprehensive n8n workflow automatically transforms trending Google search queries into engaging LinkedIn posts using AI. The system runs autonomously, discovering viral topics, researc...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 12 nodes utilisant ai, google, http.\nStructure: traitement par lots, code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"vJw8YoQhdA5CXGeB\",\"meta\":{\"instanceId\":\"f2cf6301a998e16084609c8635767c7f2fe71603e7ba21b5457aa517ce5164cb\",\"templateCredsSetupCompleted\":true},\"name\":\"Social_media_post _automation_from_google_trends_and _perplexity copy\",\"tags\":[],\"nodes\":[{\"id\":\"39b1272c-3700-4ce6-9aea-46b3a647fc26\",\"name\":\"X1\",\"type\":\"n8n-nodes-base.twitter\",\"position\":[-1500,0],\"parameters\":{\"additionalFields\":{}},\"typeVersion\":2},{\"id\":\"4bab1fd3-1c21-4438-8cc1-e0d0fdde390e\",\"name\":\"Facebook Graph API1\",\"type\":\"n8n-nodes-base.facebookGraphApi\",\"position\":[-1500,-400],\"parameters\":{\"options\":{},\"httpRequestMethod\":\"POST\"},\"typeVersion\":1},{\"id\":\"ffcd9aa8-daef-41dc-8ad3-b9a55a817b8b\",\"name\":\"LinkedIn1\",\"type\":\"n8n-nodes-base.linkedIn\",\"position\":[-1480,-200],\"parameters\":{\"text\":\"={{ $json['choices[0].message.content'] }}\",\"person\":\"[CONFIGURE_YOUR_LINKEDIN_PERSON_ID]\",\"authentication\":\"communityManagement\",\"additionalFields\":{}},\"typeVersion\":1},{\"id\":\"a2c2c5e5-e9b1-4744-9883-c63cda3306c9\",\"name\":\"Google Sheets2\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[-1280,-200],\"parameters\":{\"columns\":{\"value\":{\"Topic\":\"={{ $('Choosing Topic').item.json.message.content }}\",\"Status\":\"Posted\",\"AI Output\":\"={{ $json['choices[0].message.content'] }}\",\"Date Posted\":\"={{ $('Schedule Trigger').item.json.timestamp }}\"},\"schema\":[{\"id\":\"Topic\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"Topic\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"Status\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"Status\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"AI Output\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"AI Output\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"Date Posted\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"Date Posted\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[\"Topic\"],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{},\"operation\":\"appendOrUpdate\",\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gid=0\",\"cachedResultUrl\":\"[YOUR_GOOGLE_SHEETS_URL]\",\"cachedResultName\":\"Sheet1\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"[YOUR_GOOGLE_SHEETS_DOCUMENT_ID]\",\"cachedResultUrl\":\"[YOUR_GOOGLE_SHEETS_URL]\",\"cachedResultName\":\"LinkedIn Automation\"}},\"typeVersion\":4.5},{\"id\":\"51d3733a-004c-4938-9575-d227588140b7\",\"name\":\"Split Out\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-1720,-200],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"choices[0].message.content\"},\"typeVersion\":1},{\"id\":\"cc9b1e41-aaeb-43fb-a283-e3faf397cc73\",\"name\":\"Schedule Trigger\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"position\":[-3420,-200],\"parameters\":{\"rule\":{\"interval\":[{\"triggerAtHour\":6},{\"triggerAtHour\":18}]}},\"typeVersion\":1.2},{\"id\":\"01d0a3b7-66db-4032-b7d7-7a7b273920a7\",\"name\":\"Research Topic- Perplexity\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-2160,-200],\"parameters\":{\"url\":\"https://api.perplexity.ai/chat/completions\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"model\\\": \\\"sonar-pro\\\",\\n \\\"messages\\\": [\\n {\\n \\\"role\\\": \\\"system\\\",\\n \\\"content\\\": \\\"Act as a skilled editor revising AI-generated text to sound authentically human. Follow these rules:\\\\n\\\\n1. Punctuation Adjustments\\\\n - Replace em dashes, semicolons, or rephrase sentences where appropriate.\\\\n - Avoid semicolons in casual contexts; use periods or conjunctions (e.g., 'and,' 'but').\\\\n - Remove mid-sentence ellipses unless mimicking deliberate hesitation.\\\\n - Limit parenthetical asides; integrate explanations into the main sentence.\\\\n - Use colons sparingly.\\\\n\\\\n2. Language\\\\n - Replace hedging phrases with direct statements.\\\\n - Avoid stock transitions.\\\\n - Vary repetitive terms.\\\\n - Use contractions in informal contexts.\\\\n - Replace overly formal words with simpler alternatives.\\\\n\\\\n3. Style\\\\n - Prioritize concise, varied sentence lengths.\\\\n - Allow minor imperfections.\\\\n - Maintain the core message but adjust tone to match the audience.\\\"\\n },\\n {\\n \\\"role\\\": \\\"user\\\",\\n \\\"content\\\": \\\"You are a researcher and expert copywriter in a business development team of an AI Automation Agency. Generate exactly one LinkedIn post that adheres to LinkedIn's API formatting guidelines and is easy for humans to read. Follow these rules:\\\\n\\\\nStructure:\\\\n1. Hook: Start with a bold opening line using Unicode characters (e.g., \\\\\\\"𝐁𝐎𝐋𝐃 𝐒𝐓𝐀𝐓𝐄𝐌𝐄𝐍𝐓\\\\\\\").\\\\n2. Body: Use short paragraphs (1-3 sentences) separated by \\\\\\\\n\\\\\\\\n.\\\\n3. Use bullet points (•) for key features or highlights.\\\\n4. End with a clear call-to-action (e.g., \\\\\\\"Comment below with your thoughts!\\\\\\\").\\\\n\\\\nFormatting Requirements:\\\\n- Remove all numeric citation brackets like [2], [3], [4] from the text.\\\\n- Instead of citation brackets, if needed, add a brief phrase like \\\\\\\"according to Google I/O 2025\\\\\\\" or \\\\\\\"as reported by DeepMind\\\\\\\" naturally within the sentence.\\\\n- No Markdown or rich text formatting.\\\\n- Use Unicode characters or emojis for emphasis (e.g., ★, 🚀).\\\\n- Include up to 3 relevant hashtags at the end (e.g., #AI #Automation).\\\\n- For URLs or references, use placeholders like [Link] instead of raw URLs.\\\\n- If mentioning users or companies, use official LinkedIn URN format (e.g., \\\\\\\"urn:li:organization:123456\\\\\\\").\\\\n\\\\nContent Rules:\\\\n- Max 1,200 characters.\\\\n- Avoid promotional language.\\\\n- Include one statistical claim or industry insight.\\\\n- Add one personal anecdote or professional observation.\\\\n\\\\nReturn the post as plain text without additional commentary.\\\\n\\\\nInput: {{ $json.message.content }}\\\"\\n }\\n ]\\n}\\n\",\"sendBody\":true,\"specifyBody\":\"json\",\"authentication\":\"genericCredentialType\",\"genericAuthType\":\"httpHeaderAuth\"},\"typeVersion\":4.2},{\"id\":\"1b226459-7dc7-46c2-9b02-769cd213e927\",\"name\":\"2 Most Trending\",\"type\":\"n8n-nodes-base.set\",\"position\":[-2980,-200],\"parameters\":{\"mode\":\"raw\",\"options\":{},\"jsonOutput\":\"={\\n \\\"most-trending\\\": {\\n\\n \\\"#1\\\": { \\n\\n \\\"query\\\":\\\"{{ $json.related_queries.rising[0].query }}\\\",\\n \\\"score\\\":\\\"{{ $json.related_queries.rising[0].extracted_value }}\\\"\\n\\n },\\n\\n\\n \\\"#2\\\": { \\n\\n \\\"query\\\":\\\"{{ $json.related_queries.rising[1].query }}\\\",\\n \\\"score\\\":\\\"{{ $json.related_queries.rising[1].extracted_value }}\\\"\\n\\n }\\n }\\n}\"},\"typeVersion\":3.4},{\"id\":\"75ccf42a-7dc8-4cc8-9d5d-202ff4b2b795\",\"name\":\"High search volume keywords\",\"type\":\"n8n-nodes-base.code\",\"position\":[-2760,-200],\"parameters\":{\"jsCode\":\"// Get the top array from your JSON\\nconst topItems = $('Google Trends').first().json.related_queries.top;\\n\\n// Filter the items to only include those with extracted_value > 30\\nconst filtered = topItems.filter(item => item.extracted_value > 30);\\n\\n// Map the filtered items to their query values and join them with commas\\nconst resultString = filtered.map(item => item.query).join(', ');\\n\\n// Return the result in a new JSON property\\nreturn [{ json: { result: resultString } }];\\n\"},\"typeVersion\":2},{\"id\":\"c85503d1-76e7-4dd7-a2e3-69966f69e0cd\",\"name\":\"Choosing Topic\",\"type\":\"@n8n/n8n-nodes-langchain.openAi\",\"position\":[-2540,-200],\"parameters\":{\"modelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-3.5-turbo\",\"cachedResultName\":\"GPT-3.5-TURBO\"},\"options\":{},\"messages\":{\"values\":[{\"content\":\"=You are part of a team that creates world class blog posts. Your job is to choose the topic for each blog post. \\n\\nThe blog posts are posted on the website of a [COMPANY NAME + DESCRIPTION + PRODUCTS + TARGET MARKET]. The blog posts are mainly posted as part of an SEO campaign to get [YOUR_COMPANY] to rank high for its products and services.\\n\\nIn this instance, you are given a list of 2 keywords which have been trending the most on Google news search over the past few days. \\n\\nYour job is to pick one which you think would make for the most relevant blog post with the best SEO outcomes for the client. \\n\\nThe keywords have two attributes: \\n\\n1. query: This attribute determines the search query that users have been searching for which is trending. \\n\\n2. value: This attribute determines what percentage increase the keyword has seen compared to previous periods (i.e. the increase in search volume). \\n\\nYou must choose one out of the taking into consideration both the relevance of the keyword for [YOUR_COMPANY]'s SEO efforts and the comparative trendiness determined by the value attribute. \\n\\nOutput the keyword you decided to post a blog on and nothing else. Don't explain your reasoning. Just output the keyword. \\n\\nThis instance: \\n\\nKeyword 1:\\n{{ $('2 Most Trending').item.json['most-trending']['#1'].toJsonString() }} \\n\\nKeyword2: \\n{{ $('2 Most Trending').item.json['most-trending']['#2'].toJsonString() }} \"}]}},\"typeVersion\":1.8},{\"id\":\"089fdbf7-f1a0-4cd5-9769-caf94b05a939\",\"name\":\"Google Trends\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-3200,-200],\"parameters\":{\"url\":\"https://serpapi.com/search\",\"options\":{},\"sendQuery\":true,\"queryParameters\":{\"parameters\":[{\"name\":\"q\",\"value\":\"=ai agents\"},{\"name\":\"geo\",\"value\":\"US\"},{\"name\":\"hl\",\"value\":\"en\"},{\"name\":\"date\",\"value\":\"={{ $now.minus({ days: 3 }).format('yyyy-MM-dd') }} {{ $now.format('yyyy-MM-dd') }}\"},{\"name\":\"data_type\",\"value\":\"RELATED_QUERIES\"},{\"name\":\"engine\",\"value\":\"google_trends\"},{\"name\":\"api_key\",\"value\":\"[YOUR_SERPAPI_KEY]\"}]}},\"typeVersion\":4.2},{\"id\":\"13f0ea49-1dbe-4b33-9c73-ebe9d3099003\",\"name\":\"Wait\",\"type\":\"n8n-nodes-base.wait\",\"position\":[-1940,-200],\"webhookId\":\"[GENERATED_WEBHOOK_ID]\",\"parameters\":{\"amount\":10},\"typeVersion\":1.1}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Wait\":{\"main\":[[{\"node\":\"Split Out\",\"type\":\"main\",\"index\":0}]]},\"LinkedIn1\":{\"main\":[[{\"node\":\"Google Sheets2\",\"type\":\"main\",\"index\":0}]]},\"Split Out\":{\"main\":[[{\"node\":\"X1\",\"type\":\"main\",\"index\":0},{\"node\":\"Facebook Graph API1\",\"type\":\"main\",\"index\":0},{\"node\":\"LinkedIn1\",\"type\":\"main\",\"index\":0}]]},\"Google Trends\":{\"main\":[[{\"node\":\"2 Most Trending\",\"type\":\"main\",\"index\":0}]]},\"Choosing Topic\":{\"main\":[[{\"node\":\"Research Topic- Perplexity\",\"type\":\"main\",\"index\":0}]]},\"2 Most Trending\":{\"main\":[[{\"node\":\"High search volume keywords\",\"type\":\"main\",\"index\":0}]]},\"Schedule Trigger\":{\"main\":[[{\"node\":\"Google Trends\",\"type\":\"main\",\"index\":0}]]},\"Research Topic- Perplexity\":{\"main\":[[{\"node\":\"Wait\",\"type\":\"main\",\"index\":0}]]},\"High search volume keywords\":{\"main\":[[{\"node\":\"Choosing Topic\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 12, "node_types": {"twitter": 1, "facebookGraphApi": 1, "linkedIn": 1, "googleSheets": 1, "splitOut": 1, "scheduleTrigger": 1, "httpRequest": 2, "set": 1, "code": 1, "openAi": 1, "wait": 1}, "services": ["ai", "google", "http"], "complexity": "medium", "has_conditions": false, "has_loops": true, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: AI-Powered Multi-Social Media Post Automation: Google Trends & Perplexity AI"}, {"role": "assistant", "content": "\n**Analyse du besoin**: Overview\n\nThis comprehensive n8n workflow automatically transforms trending Google search queries into engaging LinkedIn posts using AI. The system runs autonomously, discovering viral topics, researc...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 12 nodes utilisant ai, google, http.\nStructure: traitement par lots, code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"vJw8YoQhdA5CXGeB\",\"meta\":{\"instanceId\":\"f2cf6301a998e16084609c8635767c7f2fe71603e7ba21b5457aa517ce5164cb\",\"templateCredsSetupCompleted\":true},\"name\":\"Social_media_post _automation_from_google_trends_and _perplexity copy\",\"tags\":[],\"nodes\":[{\"id\":\"39b1272c-3700-4ce6-9aea-46b3a647fc26\",\"name\":\"X1\",\"type\":\"n8n-nodes-base.twitter\",\"position\":[-1500,0],\"parameters\":{\"additionalFields\":{}},\"typeVersion\":2},{\"id\":\"4bab1fd3-1c21-4438-8cc1-e0d0fdde390e\",\"name\":\"Facebook Graph API1\",\"type\":\"n8n-nodes-base.facebookGraphApi\",\"position\":[-1500,-400],\"parameters\":{\"options\":{},\"httpRequestMethod\":\"POST\"},\"typeVersion\":1},{\"id\":\"ffcd9aa8-daef-41dc-8ad3-b9a55a817b8b\",\"name\":\"LinkedIn1\",\"type\":\"n8n-nodes-base.linkedIn\",\"position\":[-1480,-200],\"parameters\":{\"text\":\"={{ $json['choices[0].message.content'] }}\",\"person\":\"[CONFIGURE_YOUR_LINKEDIN_PERSON_ID]\",\"authentication\":\"communityManagement\",\"additionalFields\":{}},\"typeVersion\":1},{\"id\":\"a2c2c5e5-e9b1-4744-9883-c63cda3306c9\",\"name\":\"Google Sheets2\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[-1280,-200],\"parameters\":{\"columns\":{\"value\":{\"Topic\":\"={{ $('Choosing Topic').item.json.message.content }}\",\"Status\":\"Posted\",\"AI Output\":\"={{ $json['choices[0].message.content'] }}\",\"Date Posted\":\"={{ $('Schedule Trigger').item.json.timestamp }}\"},\"schema\":[{\"id\":\"Topic\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"Topic\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"Status\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"Status\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"AI Output\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"AI Output\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"Date Posted\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"Date Posted\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[\"Topic\"],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{},\"operation\":\"appendOrUpdate\",\"sheetName\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gid=0\",\"cachedResultUrl\":\"[YOUR_GOOGLE_SHEETS_URL]\",\"cachedResultName\":\"Sheet1\"},\"documentId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"[YOUR_GOOGLE_SHEETS_DOCUMENT_ID]\",\"cachedResultUrl\":\"[YOUR_GOOGLE_SHEETS_URL]\",\"cachedResultName\":\"LinkedIn Automation\"}},\"typeVersion\":4.5},{\"id\":\"51d3733a-004c-4938-9575-d227588140b7\",\"name\":\"Split Out\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-1720,-200],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"choices[0].message.content\"},\"typeVersion\":1},{\"id\":\"cc9b1e41-aaeb-43fb-a283-e3faf397cc73\",\"name\":\"Schedule Trigger\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"position\":[-3420,-200],\"parameters\":{\"rule\":{\"interval\":[{\"triggerAtHour\":6},{\"triggerAtHour\":18}]}},\"typeVersion\":1.2},{\"id\":\"01d0a3b7-66db-4032-b7d7-7a7b273920a7\",\"name\":\"Research Topic- Perplexity\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-2160,-200],\"parameters\":{\"url\":\"https://api.perplexity.ai/chat/completions\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"model\\\": \\\"sonar-pro\\\",\\n \\\"messages\\\": [\\n {\\n \\\"role\\\": \\\"system\\\",\\n \\\"content\\\": \\\"Act as a skilled editor revising AI-generated text to sound authentically human. Follow these rules:\\\\n\\\\n1. Punctuation Adjustments\\\\n - Replace em dashes, semicolons, or rephrase sentences where appropriate.\\\\n - Avoid semicolons in casual contexts; use periods or conjunctions (e.g., 'and,' 'but').\\\\n - Remove mid-sentence ellipses unless mimicking deliberate hesitation.\\\\n - Limit parenthetical asides; integrate explanations into the main sentence.\\\\n - Use colons sparingly.\\\\n\\\\n2. Language\\\\n - Replace hedging phrases with direct statements.\\\\n - Avoid stock transitions.\\\\n - Vary repetitive terms.\\\\n - Use contractions in informal contexts.\\\\n - Replace overly formal words with simpler alternatives.\\\\n\\\\n3. Style\\\\n - Prioritize concise, varied sentence lengths.\\\\n - Allow minor imperfections.\\\\n - Maintain the core message but adjust tone to match the audience.\\\"\\n },\\n {\\n \\\"role\\\": \\\"user\\\",\\n \\\"content\\\": \\\"You are a researcher and expert copywriter in a business development team of an AI Automation Agency. Generate exactly one LinkedIn post that adheres to LinkedIn's API formatting guidelines and is easy for humans to read. Follow these rules:\\\\n\\\\nStructure:\\\\n1. Hook: Start with a bold opening line using Unicode characters (e.g., \\\\\\\"𝐁𝐎𝐋𝐃 𝐒𝐓𝐀𝐓𝐄𝐌𝐄𝐍𝐓\\\\\\\").\\\\n2. Body: Use short paragraphs (1-3 sentences) separated by \\\\\\\\n\\\\\\\\n.\\\\n3. Use bullet points (•) for key features or highlights.\\\\n4. End with a clear call-to-action (e.g., \\\\\\\"Comment below with your thoughts!\\\\\\\").\\\\n\\\\nFormatting Requirements:\\\\n- Remove all numeric citation brackets like [2], [3], [4] from the text.\\\\n- Instead of citation brackets, if needed, add a brief phrase like \\\\\\\"according to Google I/O 2025\\\\\\\" or \\\\\\\"as reported by DeepMind\\\\\\\" naturally within the sentence.\\\\n- No Markdown or rich text formatting.\\\\n- Use Unicode characters or emojis for emphasis (e.g., ★, 🚀).\\\\n- Include up to 3 relevant hashtags at the end (e.g., #AI #Automation).\\\\n- For URLs or references, use placeholders like [Link] instead of raw URLs.\\\\n- If mentioning users or companies, use official LinkedIn URN format (e.g., \\\\\\\"urn:li:organization:123456\\\\\\\").\\\\n\\\\nContent Rules:\\\\n- Max 1,200 characters.\\\\n- Avoid promotional language.\\\\n- Include one statistical claim or industry insight.\\\\n- Add one personal anecdote or professional observation.\\\\n\\\\nReturn the post as plain text without additional commentary.\\\\n\\\\nInput: {{ $json.message.content }}\\\"\\n }\\n ]\\n}\\n\",\"sendBody\":true,\"specifyBody\":\"json\",\"authentication\":\"genericCredentialType\",\"genericAuthType\":\"httpHeaderAuth\"},\"typeVersion\":4.2},{\"id\":\"1b226459-7dc7-46c2-9b02-769cd213e927\",\"name\":\"2 Most Trending\",\"type\":\"n8n-nodes-base.set\",\"position\":[-2980,-200],\"parameters\":{\"mode\":\"raw\",\"options\":{},\"jsonOutput\":\"={\\n \\\"most-trending\\\": {\\n\\n \\\"#1\\\": { \\n\\n \\\"query\\\":\\\"{{ $json.related_queries.rising[0].query }}\\\",\\n \\\"score\\\":\\\"{{ $json.related_queries.rising[0].extracted_value }}\\\"\\n\\n },\\n\\n\\n \\\"#2\\\": { \\n\\n \\\"query\\\":\\\"{{ $json.related_queries.rising[1].query }}\\\",\\n \\\"score\\\":\\\"{{ $json.related_queries.rising[1].extracted_value }}\\\"\\n\\n }\\n }\\n}\"},\"typeVersion\":3.4},{\"id\":\"75ccf42a-7dc8-4cc8-9d5d-202ff4b2b795\",\"name\":\"High search volume keywords\",\"type\":\"n8n-nodes-base.code\",\"position\":[-2760,-200],\"parameters\":{\"jsCode\":\"// Get the top array from your JSON\\nconst topItems = $('Google Trends').first().json.related_queries.top;\\n\\n// Filter the items to only include those with extracted_value > 30\\nconst filtered = topItems.filter(item => item.extracted_value > 30);\\n\\n// Map the filtered items to their query values and join them with commas\\nconst resultString = filtered.map(item => item.query).join(', ');\\n\\n// Return the result in a new JSON property\\nreturn [{ json: { result: resultString } }];\\n\"},\"typeVersion\":2},{\"id\":\"c85503d1-76e7-4dd7-a2e3-69966f69e0cd\",\"name\":\"Choosing Topic\",\"type\":\"@n8n/n8n-nodes-langchain.openAi\",\"position\":[-2540,-200],\"parameters\":{\"modelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-3.5-turbo\",\"cachedResultName\":\"GPT-3.5-TURBO\"},\"options\":{},\"messages\":{\"values\":[{\"content\":\"=You are part of a team that creates world class blog posts. Your job is to choose the topic for each blog post. \\n\\nThe blog posts are posted on the website of a [COMPANY NAME + DESCRIPTION + PRODUCTS + TARGET MARKET]. The blog posts are mainly posted as part of an SEO campaign to get [YOUR_COMPANY] to rank high for its products and services.\\n\\nIn this instance, you are given a list of 2 keywords which have been trending the most on Google news search over the past few days. \\n\\nYour job is to pick one which you think would make for the most relevant blog post with the best SEO outcomes for the client. \\n\\nThe keywords have two attributes: \\n\\n1. query: This attribute determines the search query that users have been searching for which is trending. \\n\\n2. value: This attribute determines what percentage increase the keyword has seen compared to previous periods (i.e. the increase in search volume). \\n\\nYou must choose one out of the taking into consideration both the relevance of the keyword for [YOUR_COMPANY]'s SEO efforts and the comparative trendiness determined by the value attribute. \\n\\nOutput the keyword you decided to post a blog on and nothing else. Don't explain your reasoning. Just output the keyword. \\n\\nThis instance: \\n\\nKeyword 1:\\n{{ $('2 Most Trending').item.json['most-trending']['#1'].toJsonString() }} \\n\\nKeyword2: \\n{{ $('2 Most Trending').item.json['most-trending']['#2'].toJsonString() }} \"}]}},\"typeVersion\":1.8},{\"id\":\"089fdbf7-f1a0-4cd5-9769-caf94b05a939\",\"name\":\"Google Trends\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-3200,-200],\"parameters\":{\"url\":\"https://serpapi.com/search\",\"options\":{},\"sendQuery\":true,\"queryParameters\":{\"parameters\":[{\"name\":\"q\",\"value\":\"=ai agents\"},{\"name\":\"geo\",\"value\":\"US\"},{\"name\":\"hl\",\"value\":\"en\"},{\"name\":\"date\",\"value\":\"={{ $now.minus({ days: 3 }).format('yyyy-MM-dd') }} {{ $now.format('yyyy-MM-dd') }}\"},{\"name\":\"data_type\",\"value\":\"RELATED_QUERIES\"},{\"name\":\"engine\",\"value\":\"google_trends\"},{\"name\":\"api_key\",\"value\":\"[YOUR_SERPAPI_KEY]\"}]}},\"typeVersion\":4.2},{\"id\":\"13f0ea49-1dbe-4b33-9c73-ebe9d3099003\",\"name\":\"Wait\",\"type\":\"n8n-nodes-base.wait\",\"position\":[-1940,-200],\"webhookId\":\"[GENERATED_WEBHOOK_ID]\",\"parameters\":{\"amount\":10},\"typeVersion\":1.1}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Wait\":{\"main\":[[{\"node\":\"Split Out\",\"type\":\"main\",\"index\":0}]]},\"LinkedIn1\":{\"main\":[[{\"node\":\"Google Sheets2\",\"type\":\"main\",\"index\":0}]]},\"Split Out\":{\"main\":[[{\"node\":\"X1\",\"type\":\"main\",\"index\":0},{\"node\":\"Facebook Graph API1\",\"type\":\"main\",\"index\":0},{\"node\":\"LinkedIn1\",\"type\":\"main\",\"index\":0}]]},\"Google Trends\":{\"main\":[[{\"node\":\"2 Most Trending\",\"type\":\"main\",\"index\":0}]]},\"Choosing Topic\":{\"main\":[[{\"node\":\"Research Topic- Perplexity\",\"type\":\"main\",\"index\":0}]]},\"2 Most Trending\":{\"main\":[[{\"node\":\"High search volume keywords\",\"type\":\"main\",\"index\":0}]]},\"Schedule Trigger\":{\"main\":[[{\"node\":\"Google Trends\",\"type\":\"main\",\"index\":0}]]},\"Research Topic- Perplexity\":{\"main\":[[{\"node\":\"Wait\",\"type\":\"main\",\"index\":0}]]},\"High search volume keywords\":{\"main\":[[{\"node\":\"Choosing Topic\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 12, "node_types": {"twitter": 1, "facebookGraphApi": 1, "linkedIn": 1, "googleSheets": 1, "splitOut": 1, "scheduleTrigger": 1, "httpRequest": 2, "set": 1, "code": 1, "openAi": 1, "wait": 1}, "services": ["ai", "google", "http"], "complexity": "medium", "has_conditions": false, "has_loops": true, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: Introduction Automate price monitoring for e-commerce competitors—ideal for retailers, analysts, and pricing teams. Scrapes competitor sites, extracts pricing/stock data via AI, detects changes, and sends instant alerts for dynamic pricing strategies. How It Works Scrapes competitor URLs via Firecrawl and Apify, extracts data with AI, detects price/stock changes, logs to Google Sheets, and sends Telegram alerts. Workflow Template Trigger → Scrape URL → AI Extract → Parse → Merge Historical → Detect Changes → Update Sheets + Send Telegram Alert Workflow Steps Trigger & Scrape → Manual/scheduled trigger → Firecrawl + Apify fetch competitor data AI Processing → Claude extracts product details → Parses and structures data Change Detection → Reads historical prices → Merges with current data → "}, {"role": "assistant", "content": "\n**Analyse du besoin**: Introduction\n\nAutomate price monitoring for e-commerce competitors—ideal for retailers, analysts, and pricing teams. Scrapes competitor sites,\nextracts pricing/stock data via AI, detects changes, and ...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 17 nodes utilisant ai, google, http.\nStructure: traitement par lots, code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"YnD0kvM9AYMjYxmj\",\"meta\":{\"instanceId\":\"b91e510ebae4127f953fd2f5f8d40d58ca1e71c746d4500c12ae86aad04c1502\",\"templateCredsSetupCompleted\":true},\"name\":\"Multi-Site Product Price Monitor: Claude-Sonnet , Google Sheets & Telegram Alert\",\"tags\":[{\"id\":\"7zsdOA50QGm7RNqx\",\"name\":\"Monitoring\",\"createdAt\":\"2025-10-23T16:41:17.031Z\",\"updatedAt\":\"2025-10-23T16:41:17.031Z\"},{\"id\":\"BL8TsHYj5FkNYzfi\",\"name\":\"E-commerce\",\"createdAt\":\"2025-10-23T16:41:16.985Z\",\"updatedAt\":\"2025-10-23T16:41:16.985Z\"},{\"id\":\"dlf9zFSN3j6s2jgO\",\"name\":\"Business Intelligence\",\"createdAt\":\"2025-10-23T16:41:17.008Z\",\"updatedAt\":\"2025-10-23T16:41:17.008Z\"},{\"id\":\"lpozR2Ct8reF9bCk\",\"name\":\"AI\",\"createdAt\":\"2025-10-23T16:41:17.062Z\",\"updatedAt\":\"2025-10-23T16:41:17.062Z\"}],\"nodes\":[{\"id\":\"306294b3-27b8-4821-9b04-0e8d210af07e\",\"name\":\"⏰ Monitor Every 6 Hours\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"notes\":\"Triggers the workflow every 6 hours to check competitor data\",\"position\":[-832,352],\"parameters\":{\"rule\":{\"interval\":[{\"field\":\"hours\",\"hoursInterval\":6}]}},\"typeVersion\":1.2},{\"id\":\"8b934690-1e26-4810-820d-8ff785691adf\",\"name\":\"Scrape a url and get its content\",\"type\":\"@mendable/n8n-nodes-firecrawl.firecrawl\",\"position\":[-1408,96],\"parameters\":{\"url\":\"https://www.on.com/en-sg/shop/mens/shoes\",\"operation\":\"scrape\",\"scrapeOptions\":{\"options\":{\"formats\":{\"format\":[{\"type\":\"json\",\"prompt\":\"price of the shoe\"}]},\"headers\":{}}},\"requestOptions\":{}},\"typeVersion\":1},{\"id\":\"90ed5eb7-6236-47e1-88c6-c5278efe24fa\",\"name\":\"Message a model\",\"type\":\"n8n-nodes-base.perplexity\",\"position\":[-1568,0],\"parameters\":{\"model\":\"sonar\",\"options\":{},\"messages\":{\"message\":[{\"content\":\"Price of the shoe \"}]},\"requestOptions\":{}},\"typeVersion\":1},{\"id\":\"e1e006de-d363-4e5a-adbd-77ffc901f42d\",\"name\":\"Split Out\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-1296,0],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"citations\"},\"typeVersion\":1},{\"id\":\"11fdf8bc-aa37-4f42-8bbe-8e16c47c8b47\",\"name\":\"Get Results Apify\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-1216,272],\"parameters\":{\"url\":\"https://api.apify.com/v2/acts/compass~google-maps-extractor/runs/last/dataset/items?token=YOUR API KEY\",\"options\":{},\"authentication\":\"genericCredentialType\",\"genericAuthType\":\"httpBearerAuth\"},\"typeVersion\":4.2,\"alwaysOutputData\":true},{\"id\":\"b6a20e25-d82a-493b-b305-066e043f6ba1\",\"name\":\"Start Actor Apify\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-1616,272],\"parameters\":{\"url\":\"https://api.apify.com/v2/acts/compass~google-maps-extractor/runs?token=YOUR API KEY\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"{\\n \\\"language\\\": \\\"en\\\",\\n \\\"locationQuery\\\": \\\"worldwide\\\",\\n \\\"maxCrawledPlacesPerSearch\\\": 50,\\n \\\"searchStringsArray\\\": [\\n \\\"shoe stores\\\",\\n \\\"shoe shops\\\"\\n ],\\n \\\"skipClosedPlaces\\\": false\\n}\",\"sendBody\":true,\"specifyBody\":\"json\",\"authentication\":\"genericCredentialType\",\"genericAuthType\":\"httpBearerAuth\"},\"typeVersion\":4.2,\"alwaysOutputData\":true},{\"id\":\"47a1e71a-6bbf-4cfe-82f1-b46744d247ee\",\"name\":\"Converts unstructured AI text into organized, usable data fields\",\"type\":\"n8n-nodes-base.code\",\"notes\":\"Parses and validates the AI extracted data\",\"position\":[-576,192],\"parameters\":{\"jsCode\":\"// Parse AI response and clean data\\nconst items = [];\\n\\nfor (const item of $input.all()) {\\n try {\\n // Parse the AI response\\n let parsed;\\n const response = item.json.choices?.[0]?.message?.content || item.json.message || '';\\n \\n // Remove markdown code blocks if present\\n const cleaned = response.replace(/```json\\\\n?|```\\\\n?/g, '').trim();\\n \\n try {\\n parsed = JSON.parse(cleaned);\\n } catch (e) {\\n // Try to extract JSON from the response\\n const jsonMatch = cleaned.match(/\\\\{[\\\\s\\\\S]*\\\\}/);\\n if (jsonMatch) {\\n parsed = JSON.parse(jsonMatch[0]);\\n } else {\\n throw new Error('Could not parse JSON from AI response');\\n }\\n }\\n \\n // Enrich with metadata\\n items.push({\\n json: {\\n ...parsed,\\n scrapedAt: new Date().toISOString(),\\n priceChange: 0, // Will be calculated in comparison\\n priceChangePercent: 0,\\n isNewLow: false,\\n alertLevel: 'none'\\n }\\n });\\n } catch (error) {\\n console.error('Failed to parse item:', error.message);\\n // Add error item for debugging\\n items.push({\\n json: {\\n error: error.message,\\n rawResponse: item.json,\\n competitorName: 'Parse Error',\\n scrapedAt: new Date().toISOString()\\n }\\n });\\n }\\n}\\n\\nreturn items;\"},\"typeVersion\":2},{\"id\":\"3e8d7348-ccef-4cb5-aca4-d5ed6f210199\",\"name\":\"🔀 Merge Current with Historical1\",\"type\":\"n8n-nodes-base.merge\",\"notes\":\"Combines current scrape with historical data for comparison\",\"position\":[-384,224],\"parameters\":{\"mode\":\"combine\",\"options\":{},\"fieldsToMatchString\":\"rawResponse.message.content\"},\"typeVersion\":3},{\"id\":\"7e24cbab-31e4-47ba-97f2-9a7a71335905\",\"name\":\"🔍 Detect Price & Stock Changes1\",\"type\":\"n8n-nodes-base.code\",\"notes\":\"Intelligent change detection with alert level classification\",\"position\":[-208,224],\"parameters\":{\"jsCode\":\"// Compare current prices with historical and detect changes\\nconst results = [];\\n\\nfor (const item of $input.all()) {\\n const current = item.json;\\n \\n // Skip error items\\n if (current.error) {\\n results.push({ json: current });\\n continue;\\n }\\n \\n // Find historical data for this competitor\\n const historical = $('📊 Read Historical Data').all()\\n .find(h => h.json.competitorName === current.competitorName);\\n \\n let alertLevel = 'none';\\n let changes = [];\\n \\n if (historical && historical.json.currentPrice) {\\n const oldPrice = parseFloat(historical.json.currentPrice);\\n const newPrice = parseFloat(current.currentPrice);\\n const priceChange = newPrice - oldPrice;\\n const priceChangePercent = ((priceChange / oldPrice) * 100).toFixed(2);\\n \\n current.priceChange = priceChange;\\n current.priceChangePercent = parseFloat(priceChangePercent);\\n current.previousPrice = oldPrice;\\n \\n // Determine alert level based on price changes\\n if (Math.abs(priceChangePercent) >= 20) {\\n alertLevel = 'critical';\\n changes.push(`Price ${priceChange > 0 ? 'increased' : 'decreased'} by ${Math.abs(priceChangePercent)}%`);\\n } else if (Math.abs(priceChangePercent) >= 10) {\\n alertLevel = 'warning';\\n changes.push(`Price ${priceChange > 0 ? 'increased' : 'decreased'} by ${Math.abs(priceChangePercent)}%`);\\n } else if (Math.abs(priceChangePercent) >= 5) {\\n alertLevel = 'info';\\n changes.push(`Minor price change: ${priceChangePercent}%`);\\n }\\n \\n // Check if it's a new low price\\n const historicalLow = parseFloat(historical.json.lowestPrice || oldPrice);\\n if (newPrice < historicalLow) {\\n current.isNewLow = true;\\n alertLevel = alertLevel === 'none' ? 'info' : alertLevel;\\n changes.push('🎯 NEW LOWEST PRICE!');\\n }\\n current.lowestPrice = Math.min(newPrice, historicalLow);\\n \\n // Stock level changes\\n if (historical.json.stockLevel !== current.stockLevel) {\\n if (current.stockLevel === 'Out of Stock') {\\n alertLevel = 'critical';\\n changes.push('📦 Product went OUT OF STOCK');\\n } else if (current.stockLevel === 'Low Stock') {\\n alertLevel = alertLevel === 'none' ? 'warning' : alertLevel;\\n changes.push('⚠️ Stock level is LOW');\\n } else if (historical.json.stockLevel === 'Out of Stock' && current.inStock) {\\n alertLevel = alertLevel === 'none' ? 'info' : alertLevel;\\n changes.push('✅ Back in stock!');\\n }\\n }\\n \\n // Rating changes\\n const oldRating = parseFloat(historical.json.rating || 0);\\n const newRating = parseFloat(current.rating || 0);\\n const ratingChange = newRating - oldRating;\\n \\n if (Math.abs(ratingChange) >= 0.5) {\\n alertLevel = alertLevel === 'none' ? 'info' : alertLevel;\\n changes.push(`⭐ Rating ${ratingChange > 0 ? 'improved' : 'dropped'} by ${Math.abs(ratingChange).toFixed(1)} stars`);\\n }\\n \\n // Review count changes\\n const oldReviews = parseInt(historical.json.reviewCount || 0);\\n const newReviews = parseInt(current.reviewCount || 0);\\n const reviewDiff = newReviews - oldReviews;\\n \\n if (reviewDiff > 0) {\\n changes.push(`💬 ${reviewDiff} new review${reviewDiff > 1 ? 's' : ''}`);\\n }\\n } else {\\n // First time seeing this competitor\\n alertLevel = 'info';\\n changes.push('🆕 First time tracking this competitor');\\n current.lowestPrice = current.currentPrice;\\n }\\n \\n current.alertLevel = alertLevel;\\n current.changesSummary = changes.join(' | ');\\n current.hasChanges = alertLevel !== 'none';\\n \\n results.push({ json: current });\\n}\\n\\nreturn results;\"},\"typeVersion\":2},{\"id\":\"4b8b4578-e6aa-461a-ae0a-7289bd0bf7e3\",\"name\":\"💾 Update Historical Data1\",\"type\":\"n8n-nodes-base.googleSheets\",\"notes\":\"Saves current data to historical tracking sheet\",\"position\":[-32,320],\"parameters\":{\"columns\":{\"value\":{\"rating\":\"={{ $json.rating }}\",\"inStock\":\"={{ $json.inStock }}\",\"currency\":\"={{ $json.currency }}\",\"scrapedAt\":\"={{ $json.scrapedAt }}\",\"productUrl\":\"={{ $json.productUrl }}\",\"stockLevel\":\"={{ $json.stockLevel }}\",\"lowestPrice\":\"={{ $json.lowestPrice }}\",\"productName\":\"={{ $json.productName }}\",\"reviewCount\":\"={{ $json.reviewCount }}\",\"currentPrice\":\"={{ $json.currentPrice }}\",\"originalPrice\":\"={{ $json.originalPrice }}\",\"competitorName\":\"={{ $json.competitorName }}\"},\"mappingMode\":\"defineBelow\"},\"options\":{},\"operation\":\"append\",\"sheetName\":{\"mode\":\"name\",\"value\":\"Historical Data\"},\"documentId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"= {{ $env.GOOGLE_SHEET_ID }}\"}},\"typeVersion\":4.7},{\"id\":\"28d2de55-ef62-40cd-a22b-a13eee3c2dc8\",\"name\":\"When clicking ‘Execute workflow’\",\"type\":\"n8n-nodes-base.manualTrigger\",\"position\":[-1760,144],\"parameters\":{},\"typeVersion\":1},{\"id\":\"62cf73d2-a328-463b-9ea5-0d3fa8e3ba56\",\"name\":\"🤖 AI Extract Product Data using Claude-Sonnet 4.5\",\"type\":\"@n8n/n8n-nodes-langchain.anthropic\",\"position\":[-864,192],\"parameters\":{\"modelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"claude-sonnet-4-5-20250929\",\"cachedResultName\":\"claude-sonnet-4-5-20250929\"},\"options\":{},\"messages\":{\"values\":[{\"content\":\"You are an accurate e-commerce data parser. From the provided HTML, extract shoe details and output a pure JSON object—no markdown or extra text.\\n\\nInclude the following fields:\\n\\n- productName: string \\n- currentPrice: number (numeric value only, no currency symbols) \\n- originalPrice: number (if discounted, otherwise same as currentPrice) \\n- currency: string (USD, EUR, etc.) \\n- inStock: boolean \\n- stockLevel: string (\\\"In Stock\\\", \\\"Low Stock\\\", \\\"Out of Stock\\\", \\\"Limited\\\", etc.) \\n- rating: number (0-5 scale) \\n- reviewCount: number \\n- lastUpdated: string (current ISO timestamp) \\n- productUrl: string (from context) \\n- competitorName: string (from context)\\n\\nOutput only the JSON object—no notes, comments, or formatting.\\n\"}]}},\"typeVersion\":1},{\"id\":\"e5998861-2d29-4fdb-a5c0-445cf79ac50e\",\"name\":\"🔀 Merge Current with Historical\",\"type\":\"n8n-nodes-base.merge\",\"notes\":\"Combines current scrape with historical data for comparison\",\"position\":[-1024,176],\"parameters\":{\"numberInputs\":3},\"typeVersion\":3},{\"id\":\"6815d6c1-43c5-49a8-8f41-eafa0ee83363\",\"name\":\"📊 Read Historical Data\",\"type\":\"n8n-nodes-base.googleSheets\",\"notes\":\"Loads previous scan data for comparison\",\"position\":[-624,352],\"parameters\":{\"options\":{},\"sheetName\":{\"mode\":\"name\",\"value\":\"Historical Data\"},\"documentId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"={{ $env.GOOGLE_SHEET_ID }}\"}},\"typeVersion\":4.7},{\"id\":\"0c300e39-74da-4947-ab75-1360158f48a1\",\"name\":\"📝 Log Alert Details\",\"type\":\"n8n-nodes-base.googleSheets\",\"notes\":\"Logs all alerts to separate tracking sheet\",\"position\":[-48,160],\"parameters\":{\"columns\":{\"value\":{\"rating\":\"={{ $json.rating }}\",\"timestamp\":\"={{ $json.scrapedAt }}\",\"alertLevel\":\"={{ $json.alertLevel }}\",\"productUrl\":\"={{ $json.productUrl }}\",\"stockLevel\":\"={{ $json.stockLevel }}\",\"priceChange\":\"={{ $json.priceChange || 0 }}\",\"productName\":\"={{ $json.productName }}\",\"currentPrice\":\"={{ $json.currentPrice }}\",\"previousPrice\":\"={{ $json.previousPrice || 'N/A' }}\",\"changesSummary\":\"={{ $json.changesSummary }}\",\"competitorName\":\"={{ $json.competitorName }}\",\"priceChangePercent\":\"={{ $json.priceChangePercent || 0 }}\"},\"mappingMode\":\"defineBelow\"},\"options\":{},\"operation\":\"append\",\"sheetName\":{\"mode\":\"name\",\"value\":\"Alert Log\"},\"documentId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"={{ $env.GOOGLE_SHEET_ID }}\"}},\"typeVersion\":4.7},{\"id\":\"1833ee8f-13ca-40f3-a3ce-e7c09bbff5fc\",\"name\":\"Send a text message\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[112,240],\"webhookId\":\"ae976d33-11d1-4d92-9289-fc86a1525828\",\"parameters\":{\"text\":\"The competitors’ pricing has been finalized.\",\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"864886e9-21d0-402f-8f1f-46216a5e1373\",\"name\":\"Pause the workflow to let the Apify scraping task finish\",\"type\":\"n8n-nodes-base.wait\",\"position\":[-1424,272],\"webhookId\":\"426f22d5-31db-4344-ae7a-13dedfc46bf4\",\"parameters\":{\"amount\":25},\"typeVersion\":1.1}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Split Out\":{\"main\":[[{\"node\":\"🔀 Merge Current with Historical\",\"type\":\"main\",\"index\":0}]]},\"Message a model\":{\"main\":[[{\"node\":\"Split Out\",\"type\":\"main\",\"index\":0}]]},\"Get Results Apify\":{\"main\":[[{\"node\":\"🔀 Merge Current with Historical\",\"type\":\"main\",\"index\":2}]]},\"Start Actor Apify\":{\"main\":[[{\"node\":\"Pause the workflow to let the Apify scraping task finish\",\"type\":\"main\",\"index\":0}]]},\"📝 Log Alert Details\":{\"main\":[[{\"node\":\"Send a text message\",\"type\":\"main\",\"index\":0}]]},\"⏰ Monitor Every 6 Hours\":{\"main\":[[{\"node\":\"📊 Read Historical Data\",\"type\":\"main\",\"index\":0}]]},\"📊 Read Historical Data\":{\"main\":[[{\"node\":\"🔀 Merge Current with Historical1\",\"type\":\"main\",\"index\":1}]]},\"💾 Update Historical Data1\":{\"main\":[[{\"node\":\"Send a text message\",\"type\":\"main\",\"index\":0}]]},\"Scrape a url and get its content\":{\"main\":[[{\"node\":\"🔀 Merge Current with Historical\",\"type\":\"main\",\"index\":1}]]},\"🔀 Merge Current with Historical\":{\"main\":[[{\"node\":\"🤖 AI Extract Product Data using Claude-Sonnet 4.5\",\"type\":\"main\",\"index\":0}]]},\"🔍 Detect Price & Stock Changes1\":{\"main\":[[{\"node\":\"💾 Update Historical Data1\",\"type\":\"main\",\"index\":0},{\"node\":\"📝 Log Alert Details\",\"type\":\"main\",\"index\":0}]]},\"🔀 Merge Current with Historical1\":{\"main\":[[{\"node\":\"🔍 Detect Price & Stock Changes1\",\"type\":\"main\",\"index\":0}]]},\"When clicking ‘Execute workflow’\":{\"main\":[[{\"node\":\"Message a model\",\"type\":\"main\",\"index\":0},{\"node\":\"Scrape a url and get its content\",\"type\":\"main\",\"index\":0},{\"node\":\"Start Actor Apify\",\"type\":\"main\",\"index\":0}]]},\"🤖 AI Extract Product Data using Claude-Sonnet 4.5\":{\"main\":[[{\"node\":\"Converts unstructured AI text into organized, usable data fields\",\"type\":\"main\",\"index\":0}]]},\"Pause the workflow to let the Apify scraping task finish\":{\"main\":[[{\"node\":\"Get Results Apify\",\"type\":\"main\",\"index\":0}]]},\"Converts unstructured AI text into organized, usable data fields\":{\"main\":[[{\"node\":\"🔀 Merge Current with Historical1\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 17, "node_types": {"scheduleTrigger": 1, "firecrawl": 1, "perplexity": 1, "splitOut": 1, "httpRequest": 2, "code": 2, "merge": 2, "googleSheets": 3, "manualTrigger": 1, "anthropic": 1, "telegram": 1, "wait": 1}, "services": ["ai", "google", "http"], "complexity": "complex", "has_conditions": false, "has_loops": true, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: E-commerce Price Monitor with Firecrawl, Claude-Sonnet AI & Telegram Alerts"}, {"role": "assistant", "content": "\n**Analyse du besoin**: Introduction\n\nAutomate price monitoring for e-commerce competitors—ideal for retailers, analysts, and pricing teams. Scrapes competitor sites,\nextracts pricing/stock data via AI, detects changes, and ...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 17 nodes utilisant ai, google, http.\nStructure: traitement par lots, code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"YnD0kvM9AYMjYxmj\",\"meta\":{\"instanceId\":\"b91e510ebae4127f953fd2f5f8d40d58ca1e71c746d4500c12ae86aad04c1502\",\"templateCredsSetupCompleted\":true},\"name\":\"Multi-Site Product Price Monitor: Claude-Sonnet , Google Sheets & Telegram Alert\",\"tags\":[{\"id\":\"7zsdOA50QGm7RNqx\",\"name\":\"Monitoring\",\"createdAt\":\"2025-10-23T16:41:17.031Z\",\"updatedAt\":\"2025-10-23T16:41:17.031Z\"},{\"id\":\"BL8TsHYj5FkNYzfi\",\"name\":\"E-commerce\",\"createdAt\":\"2025-10-23T16:41:16.985Z\",\"updatedAt\":\"2025-10-23T16:41:16.985Z\"},{\"id\":\"dlf9zFSN3j6s2jgO\",\"name\":\"Business Intelligence\",\"createdAt\":\"2025-10-23T16:41:17.008Z\",\"updatedAt\":\"2025-10-23T16:41:17.008Z\"},{\"id\":\"lpozR2Ct8reF9bCk\",\"name\":\"AI\",\"createdAt\":\"2025-10-23T16:41:17.062Z\",\"updatedAt\":\"2025-10-23T16:41:17.062Z\"}],\"nodes\":[{\"id\":\"306294b3-27b8-4821-9b04-0e8d210af07e\",\"name\":\"⏰ Monitor Every 6 Hours\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"notes\":\"Triggers the workflow every 6 hours to check competitor data\",\"position\":[-832,352],\"parameters\":{\"rule\":{\"interval\":[{\"field\":\"hours\",\"hoursInterval\":6}]}},\"typeVersion\":1.2},{\"id\":\"8b934690-1e26-4810-820d-8ff785691adf\",\"name\":\"Scrape a url and get its content\",\"type\":\"@mendable/n8n-nodes-firecrawl.firecrawl\",\"position\":[-1408,96],\"parameters\":{\"url\":\"https://www.on.com/en-sg/shop/mens/shoes\",\"operation\":\"scrape\",\"scrapeOptions\":{\"options\":{\"formats\":{\"format\":[{\"type\":\"json\",\"prompt\":\"price of the shoe\"}]},\"headers\":{}}},\"requestOptions\":{}},\"typeVersion\":1},{\"id\":\"90ed5eb7-6236-47e1-88c6-c5278efe24fa\",\"name\":\"Message a model\",\"type\":\"n8n-nodes-base.perplexity\",\"position\":[-1568,0],\"parameters\":{\"model\":\"sonar\",\"options\":{},\"messages\":{\"message\":[{\"content\":\"Price of the shoe \"}]},\"requestOptions\":{}},\"typeVersion\":1},{\"id\":\"e1e006de-d363-4e5a-adbd-77ffc901f42d\",\"name\":\"Split Out\",\"type\":\"n8n-nodes-base.splitOut\",\"position\":[-1296,0],\"parameters\":{\"options\":{},\"fieldToSplitOut\":\"citations\"},\"typeVersion\":1},{\"id\":\"11fdf8bc-aa37-4f42-8bbe-8e16c47c8b47\",\"name\":\"Get Results Apify\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-1216,272],\"parameters\":{\"url\":\"https://api.apify.com/v2/acts/compass~google-maps-extractor/runs/last/dataset/items?token=YOUR API KEY\",\"options\":{},\"authentication\":\"genericCredentialType\",\"genericAuthType\":\"httpBearerAuth\"},\"typeVersion\":4.2,\"alwaysOutputData\":true},{\"id\":\"b6a20e25-d82a-493b-b305-066e043f6ba1\",\"name\":\"Start Actor Apify\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[-1616,272],\"parameters\":{\"url\":\"https://api.apify.com/v2/acts/compass~google-maps-extractor/runs?token=YOUR API KEY\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"{\\n \\\"language\\\": \\\"en\\\",\\n \\\"locationQuery\\\": \\\"worldwide\\\",\\n \\\"maxCrawledPlacesPerSearch\\\": 50,\\n \\\"searchStringsArray\\\": [\\n \\\"shoe stores\\\",\\n \\\"shoe shops\\\"\\n ],\\n \\\"skipClosedPlaces\\\": false\\n}\",\"sendBody\":true,\"specifyBody\":\"json\",\"authentication\":\"genericCredentialType\",\"genericAuthType\":\"httpBearerAuth\"},\"typeVersion\":4.2,\"alwaysOutputData\":true},{\"id\":\"47a1e71a-6bbf-4cfe-82f1-b46744d247ee\",\"name\":\"Converts unstructured AI text into organized, usable data fields\",\"type\":\"n8n-nodes-base.code\",\"notes\":\"Parses and validates the AI extracted data\",\"position\":[-576,192],\"parameters\":{\"jsCode\":\"// Parse AI response and clean data\\nconst items = [];\\n\\nfor (const item of $input.all()) {\\n try {\\n // Parse the AI response\\n let parsed;\\n const response = item.json.choices?.[0]?.message?.content || item.json.message || '';\\n \\n // Remove markdown code blocks if present\\n const cleaned = response.replace(/```json\\\\n?|```\\\\n?/g, '').trim();\\n \\n try {\\n parsed = JSON.parse(cleaned);\\n } catch (e) {\\n // Try to extract JSON from the response\\n const jsonMatch = cleaned.match(/\\\\{[\\\\s\\\\S]*\\\\}/);\\n if (jsonMatch) {\\n parsed = JSON.parse(jsonMatch[0]);\\n } else {\\n throw new Error('Could not parse JSON from AI response');\\n }\\n }\\n \\n // Enrich with metadata\\n items.push({\\n json: {\\n ...parsed,\\n scrapedAt: new Date().toISOString(),\\n priceChange: 0, // Will be calculated in comparison\\n priceChangePercent: 0,\\n isNewLow: false,\\n alertLevel: 'none'\\n }\\n });\\n } catch (error) {\\n console.error('Failed to parse item:', error.message);\\n // Add error item for debugging\\n items.push({\\n json: {\\n error: error.message,\\n rawResponse: item.json,\\n competitorName: 'Parse Error',\\n scrapedAt: new Date().toISOString()\\n }\\n });\\n }\\n}\\n\\nreturn items;\"},\"typeVersion\":2},{\"id\":\"3e8d7348-ccef-4cb5-aca4-d5ed6f210199\",\"name\":\"🔀 Merge Current with Historical1\",\"type\":\"n8n-nodes-base.merge\",\"notes\":\"Combines current scrape with historical data for comparison\",\"position\":[-384,224],\"parameters\":{\"mode\":\"combine\",\"options\":{},\"fieldsToMatchString\":\"rawResponse.message.content\"},\"typeVersion\":3},{\"id\":\"7e24cbab-31e4-47ba-97f2-9a7a71335905\",\"name\":\"🔍 Detect Price & Stock Changes1\",\"type\":\"n8n-nodes-base.code\",\"notes\":\"Intelligent change detection with alert level classification\",\"position\":[-208,224],\"parameters\":{\"jsCode\":\"// Compare current prices with historical and detect changes\\nconst results = [];\\n\\nfor (const item of $input.all()) {\\n const current = item.json;\\n \\n // Skip error items\\n if (current.error) {\\n results.push({ json: current });\\n continue;\\n }\\n \\n // Find historical data for this competitor\\n const historical = $('📊 Read Historical Data').all()\\n .find(h => h.json.competitorName === current.competitorName);\\n \\n let alertLevel = 'none';\\n let changes = [];\\n \\n if (historical && historical.json.currentPrice) {\\n const oldPrice = parseFloat(historical.json.currentPrice);\\n const newPrice = parseFloat(current.currentPrice);\\n const priceChange = newPrice - oldPrice;\\n const priceChangePercent = ((priceChange / oldPrice) * 100).toFixed(2);\\n \\n current.priceChange = priceChange;\\n current.priceChangePercent = parseFloat(priceChangePercent);\\n current.previousPrice = oldPrice;\\n \\n // Determine alert level based on price changes\\n if (Math.abs(priceChangePercent) >= 20) {\\n alertLevel = 'critical';\\n changes.push(`Price ${priceChange > 0 ? 'increased' : 'decreased'} by ${Math.abs(priceChangePercent)}%`);\\n } else if (Math.abs(priceChangePercent) >= 10) {\\n alertLevel = 'warning';\\n changes.push(`Price ${priceChange > 0 ? 'increased' : 'decreased'} by ${Math.abs(priceChangePercent)}%`);\\n } else if (Math.abs(priceChangePercent) >= 5) {\\n alertLevel = 'info';\\n changes.push(`Minor price change: ${priceChangePercent}%`);\\n }\\n \\n // Check if it's a new low price\\n const historicalLow = parseFloat(historical.json.lowestPrice || oldPrice);\\n if (newPrice < historicalLow) {\\n current.isNewLow = true;\\n alertLevel = alertLevel === 'none' ? 'info' : alertLevel;\\n changes.push('🎯 NEW LOWEST PRICE!');\\n }\\n current.lowestPrice = Math.min(newPrice, historicalLow);\\n \\n // Stock level changes\\n if (historical.json.stockLevel !== current.stockLevel) {\\n if (current.stockLevel === 'Out of Stock') {\\n alertLevel = 'critical';\\n changes.push('📦 Product went OUT OF STOCK');\\n } else if (current.stockLevel === 'Low Stock') {\\n alertLevel = alertLevel === 'none' ? 'warning' : alertLevel;\\n changes.push('⚠️ Stock level is LOW');\\n } else if (historical.json.stockLevel === 'Out of Stock' && current.inStock) {\\n alertLevel = alertLevel === 'none' ? 'info' : alertLevel;\\n changes.push('✅ Back in stock!');\\n }\\n }\\n \\n // Rating changes\\n const oldRating = parseFloat(historical.json.rating || 0);\\n const newRating = parseFloat(current.rating || 0);\\n const ratingChange = newRating - oldRating;\\n \\n if (Math.abs(ratingChange) >= 0.5) {\\n alertLevel = alertLevel === 'none' ? 'info' : alertLevel;\\n changes.push(`⭐ Rating ${ratingChange > 0 ? 'improved' : 'dropped'} by ${Math.abs(ratingChange).toFixed(1)} stars`);\\n }\\n \\n // Review count changes\\n const oldReviews = parseInt(historical.json.reviewCount || 0);\\n const newReviews = parseInt(current.reviewCount || 0);\\n const reviewDiff = newReviews - oldReviews;\\n \\n if (reviewDiff > 0) {\\n changes.push(`💬 ${reviewDiff} new review${reviewDiff > 1 ? 's' : ''}`);\\n }\\n } else {\\n // First time seeing this competitor\\n alertLevel = 'info';\\n changes.push('🆕 First time tracking this competitor');\\n current.lowestPrice = current.currentPrice;\\n }\\n \\n current.alertLevel = alertLevel;\\n current.changesSummary = changes.join(' | ');\\n current.hasChanges = alertLevel !== 'none';\\n \\n results.push({ json: current });\\n}\\n\\nreturn results;\"},\"typeVersion\":2},{\"id\":\"4b8b4578-e6aa-461a-ae0a-7289bd0bf7e3\",\"name\":\"💾 Update Historical Data1\",\"type\":\"n8n-nodes-base.googleSheets\",\"notes\":\"Saves current data to historical tracking sheet\",\"position\":[-32,320],\"parameters\":{\"columns\":{\"value\":{\"rating\":\"={{ $json.rating }}\",\"inStock\":\"={{ $json.inStock }}\",\"currency\":\"={{ $json.currency }}\",\"scrapedAt\":\"={{ $json.scrapedAt }}\",\"productUrl\":\"={{ $json.productUrl }}\",\"stockLevel\":\"={{ $json.stockLevel }}\",\"lowestPrice\":\"={{ $json.lowestPrice }}\",\"productName\":\"={{ $json.productName }}\",\"reviewCount\":\"={{ $json.reviewCount }}\",\"currentPrice\":\"={{ $json.currentPrice }}\",\"originalPrice\":\"={{ $json.originalPrice }}\",\"competitorName\":\"={{ $json.competitorName }}\"},\"mappingMode\":\"defineBelow\"},\"options\":{},\"operation\":\"append\",\"sheetName\":{\"mode\":\"name\",\"value\":\"Historical Data\"},\"documentId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"= {{ $env.GOOGLE_SHEET_ID }}\"}},\"typeVersion\":4.7},{\"id\":\"28d2de55-ef62-40cd-a22b-a13eee3c2dc8\",\"name\":\"When clicking ‘Execute workflow’\",\"type\":\"n8n-nodes-base.manualTrigger\",\"position\":[-1760,144],\"parameters\":{},\"typeVersion\":1},{\"id\":\"62cf73d2-a328-463b-9ea5-0d3fa8e3ba56\",\"name\":\"🤖 AI Extract Product Data using Claude-Sonnet 4.5\",\"type\":\"@n8n/n8n-nodes-langchain.anthropic\",\"position\":[-864,192],\"parameters\":{\"modelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"claude-sonnet-4-5-20250929\",\"cachedResultName\":\"claude-sonnet-4-5-20250929\"},\"options\":{},\"messages\":{\"values\":[{\"content\":\"You are an accurate e-commerce data parser. From the provided HTML, extract shoe details and output a pure JSON object—no markdown or extra text.\\n\\nInclude the following fields:\\n\\n- productName: string \\n- currentPrice: number (numeric value only, no currency symbols) \\n- originalPrice: number (if discounted, otherwise same as currentPrice) \\n- currency: string (USD, EUR, etc.) \\n- inStock: boolean \\n- stockLevel: string (\\\"In Stock\\\", \\\"Low Stock\\\", \\\"Out of Stock\\\", \\\"Limited\\\", etc.) \\n- rating: number (0-5 scale) \\n- reviewCount: number \\n- lastUpdated: string (current ISO timestamp) \\n- productUrl: string (from context) \\n- competitorName: string (from context)\\n\\nOutput only the JSON object—no notes, comments, or formatting.\\n\"}]}},\"typeVersion\":1},{\"id\":\"e5998861-2d29-4fdb-a5c0-445cf79ac50e\",\"name\":\"🔀 Merge Current with Historical\",\"type\":\"n8n-nodes-base.merge\",\"notes\":\"Combines current scrape with historical data for comparison\",\"position\":[-1024,176],\"parameters\":{\"numberInputs\":3},\"typeVersion\":3},{\"id\":\"6815d6c1-43c5-49a8-8f41-eafa0ee83363\",\"name\":\"📊 Read Historical Data\",\"type\":\"n8n-nodes-base.googleSheets\",\"notes\":\"Loads previous scan data for comparison\",\"position\":[-624,352],\"parameters\":{\"options\":{},\"sheetName\":{\"mode\":\"name\",\"value\":\"Historical Data\"},\"documentId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"={{ $env.GOOGLE_SHEET_ID }}\"}},\"typeVersion\":4.7},{\"id\":\"0c300e39-74da-4947-ab75-1360158f48a1\",\"name\":\"📝 Log Alert Details\",\"type\":\"n8n-nodes-base.googleSheets\",\"notes\":\"Logs all alerts to separate tracking sheet\",\"position\":[-48,160],\"parameters\":{\"columns\":{\"value\":{\"rating\":\"={{ $json.rating }}\",\"timestamp\":\"={{ $json.scrapedAt }}\",\"alertLevel\":\"={{ $json.alertLevel }}\",\"productUrl\":\"={{ $json.productUrl }}\",\"stockLevel\":\"={{ $json.stockLevel }}\",\"priceChange\":\"={{ $json.priceChange || 0 }}\",\"productName\":\"={{ $json.productName }}\",\"currentPrice\":\"={{ $json.currentPrice }}\",\"previousPrice\":\"={{ $json.previousPrice || 'N/A' }}\",\"changesSummary\":\"={{ $json.changesSummary }}\",\"competitorName\":\"={{ $json.competitorName }}\",\"priceChangePercent\":\"={{ $json.priceChangePercent || 0 }}\"},\"mappingMode\":\"defineBelow\"},\"options\":{},\"operation\":\"append\",\"sheetName\":{\"mode\":\"name\",\"value\":\"Alert Log\"},\"documentId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"={{ $env.GOOGLE_SHEET_ID }}\"}},\"typeVersion\":4.7},{\"id\":\"1833ee8f-13ca-40f3-a3ce-e7c09bbff5fc\",\"name\":\"Send a text message\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[112,240],\"webhookId\":\"ae976d33-11d1-4d92-9289-fc86a1525828\",\"parameters\":{\"text\":\"The competitors’ pricing has been finalized.\",\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"864886e9-21d0-402f-8f1f-46216a5e1373\",\"name\":\"Pause the workflow to let the Apify scraping task finish\",\"type\":\"n8n-nodes-base.wait\",\"position\":[-1424,272],\"webhookId\":\"426f22d5-31db-4344-ae7a-13dedfc46bf4\",\"parameters\":{\"amount\":25},\"typeVersion\":1.1}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Split Out\":{\"main\":[[{\"node\":\"🔀 Merge Current with Historical\",\"type\":\"main\",\"index\":0}]]},\"Message a model\":{\"main\":[[{\"node\":\"Split Out\",\"type\":\"main\",\"index\":0}]]},\"Get Results Apify\":{\"main\":[[{\"node\":\"🔀 Merge Current with Historical\",\"type\":\"main\",\"index\":2}]]},\"Start Actor Apify\":{\"main\":[[{\"node\":\"Pause the workflow to let the Apify scraping task finish\",\"type\":\"main\",\"index\":0}]]},\"📝 Log Alert Details\":{\"main\":[[{\"node\":\"Send a text message\",\"type\":\"main\",\"index\":0}]]},\"⏰ Monitor Every 6 Hours\":{\"main\":[[{\"node\":\"📊 Read Historical Data\",\"type\":\"main\",\"index\":0}]]},\"📊 Read Historical Data\":{\"main\":[[{\"node\":\"🔀 Merge Current with Historical1\",\"type\":\"main\",\"index\":1}]]},\"💾 Update Historical Data1\":{\"main\":[[{\"node\":\"Send a text message\",\"type\":\"main\",\"index\":0}]]},\"Scrape a url and get its content\":{\"main\":[[{\"node\":\"🔀 Merge Current with Historical\",\"type\":\"main\",\"index\":1}]]},\"🔀 Merge Current with Historical\":{\"main\":[[{\"node\":\"🤖 AI Extract Product Data using Claude-Sonnet 4.5\",\"type\":\"main\",\"index\":0}]]},\"🔍 Detect Price & Stock Changes1\":{\"main\":[[{\"node\":\"💾 Update Historical Data1\",\"type\":\"main\",\"index\":0},{\"node\":\"📝 Log Alert Details\",\"type\":\"main\",\"index\":0}]]},\"🔀 Merge Current with Historical1\":{\"main\":[[{\"node\":\"🔍 Detect Price & Stock Changes1\",\"type\":\"main\",\"index\":0}]]},\"When clicking ‘Execute workflow’\":{\"main\":[[{\"node\":\"Message a model\",\"type\":\"main\",\"index\":0},{\"node\":\"Scrape a url and get its content\",\"type\":\"main\",\"index\":0},{\"node\":\"Start Actor Apify\",\"type\":\"main\",\"index\":0}]]},\"🤖 AI Extract Product Data using Claude-Sonnet 4.5\":{\"main\":[[{\"node\":\"Converts unstructured AI text into organized, usable data fields\",\"type\":\"main\",\"index\":0}]]},\"Pause the workflow to let the Apify scraping task finish\":{\"main\":[[{\"node\":\"Get Results Apify\",\"type\":\"main\",\"index\":0}]]},\"Converts unstructured AI text into organized, usable data fields\":{\"main\":[[{\"node\":\"🔀 Merge Current with Historical1\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 17, "node_types": {"scheduleTrigger": 1, "firecrawl": 1, "perplexity": 1, "splitOut": 1, "httpRequest": 2, "code": 2, "merge": 2, "googleSheets": 3, "manualTrigger": 1, "anthropic": 1, "telegram": 1, "wait": 1}, "services": ["ai", "google", "http"], "complexity": "complex", "has_conditions": false, "has_loops": true, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: Automate Multi-Platform Social Media Content Creation with AI Who is this for? Social Media Managers and Digital Marketers seeking to streamline content production across 7+ platforms (X/Twitter, Instagram, LinkedIn, Facebook, TikTok, Threads, YouTube Shorts) using AI-powered automation. What problem does this solve? Creating platform-optimized content at scale while maintaining brand consistency across multiple channels, reducing manual work by 80% through AI generation and automated publishing. What this workflow does AI Content Generation: Uses GPT-4/Gemini to create platform-specific posts Automatically generates hashtags, CTAs, and emoji placement Supports image/video suggestions and image creation using OpenAI or Pollinations.ai Uses SERP api to search for relavent content Approval W"}, {"role": "assistant", "content": "\n**Analyse du besoin**: Automate Multi-Platform Social Media Content Creation with AI\nWho is this for?\n\nSocial Media Managers and Digital Marketers seeking to streamline content production across 7+ platforms (X/Twitter, Ins...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 39 nodes utilisant ai, google, email, http.\nStructure: logique conditionnelle, code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"CfdF2XtXC68iJ6Hr\",\"meta\":{\"instanceId\":\"31e69f7f4a77bf465b805824e303232f0227212ae922d12133a0f96ffeab4fef\",\"templateCredsSetupCompleted\":true},\"name\":\"✨🤖Automated AI Powered Social Media Content Factory for X + Facebook + Instagram + LinkedIn\",\"tags\":[],\"nodes\":[{\"id\":\"9b6e2038-9f65-4e0f-b13d-6c09e8224ed6\",\"name\":\"Social Media Content\",\"type\":\"@n8n/n8n-nodes-langchain.outputParserStructured\",\"position\":[560,-540],\"parameters\":{\"schemaType\":\"manual\",\"inputSchema\":\"{\\n\\t\\\"type\\\": \\\"object\\\",\\n\\t\\\"properties\\\": {\\n\\t\\t\\\"name\\\": {\\n\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t},\\n\\t\\t\\\"description\\\": {\\n\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t},\\n\\t\\t\\\"platform_posts\\\": {\\n\\t\\t\\t\\\"type\\\": \\\"object\\\",\\n\\t\\t\\t\\\"properties\\\": {\\n\\t\\t\\t\\t\\\"LinkedIn\\\": {\\n\\t\\t\\t\\t\\t\\\"type\\\": \\\"object\\\",\\n\\t\\t\\t\\t\\t\\\"properties\\\": {\\n \\\"image_suggestion\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"post\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"hashtags\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"array\\\",\\n\\t\\t\\t\\t\\t\\t\\t\\\"items\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"call_to_action\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\\"Instagram\\\": {\\n\\t\\t\\t\\t\\t\\\"type\\\": \\\"object\\\",\\n\\t\\t\\t\\t\\t\\\"properties\\\": {\\n\\t\\t\\t\\t\\t\\t\\\"image_suggestion\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"caption\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"hashtags\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"array\\\",\\n\\t\\t\\t\\t\\t\\t\\t\\\"items\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"emojis\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"array\\\",\\n\\t\\t\\t\\t\\t\\t\\t\\\"items\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"call_to_action\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\\"Facebook\\\": {\\n\\t\\t\\t\\t\\t\\\"type\\\": \\\"object\\\",\\n\\t\\t\\t\\t\\t\\\"properties\\\": {\\n\\t\\t\\t\\t\\t\\t\\\"post\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"hashtags\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"array\\\",\\n\\t\\t\\t\\t\\t\\t\\t\\\"items\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"call_to_action\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"image_suggestion\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\\"X-Twitter\\\": {\\n\\t\\t\\t\\t\\t\\\"type\\\": \\\"object\\\",\\n\\t\\t\\t\\t\\t\\\"properties\\\": {\\n \\\"video_suggestion\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t},\\n \\\"image_suggestion\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"post\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"hashtags\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"array\\\",\\n\\t\\t\\t\\t\\t\\t\\t\\\"items\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"character_limit\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"integer\\\"\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t},\\n \\\"TikTok\\\": {\\n \\t\\\"type\\\": \\\"object\\\",\\n \\t\\\"properties\\\": {\\n \\t\\t\\\"video_suggestion\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t},\\n \\t\\t\\\"caption\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t},\\n \\t\\t\\\"hashtags\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"array\\\",\\n \\t\\t\\t\\\"items\\\": {\\n \\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t\\t}\\n \\t\\t},\\n \\t\\t\\\"call_to_action\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t}\\n \\t}\\n },\\n \\\"Threads\\\": {\\n \\t\\\"type\\\": \\\"object\\\",\\n \\t\\\"properties\\\": {\\n \\\"image_suggestion\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t},\\n \\t\\t\\\"text_post\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t},\\n \\t\\t\\\"hashtags\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"array\\\",\\n \\t\\t\\t\\\"items\\\": {\\n \\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t\\t}\\n \\t\\t},\\n \\t\\t\\\"call_to_action\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t}\\n \\t}\\n },\\n \\\"YouTube_Shorts\\\": {\\n \\t\\\"type\\\": \\\"object\\\",\\n \\t\\\"properties\\\": {\\n \\t\\t\\\"video_suggestion\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t},\\n \\t\\t\\\"title\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t},\\n \\\"description\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"hashtags\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n },\\n \\\"call_to_action\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n }\\n\\t\\t\\t}\\n\\t\\t},\\n\\t\\t\\\"additional_notes\\\": {\\n\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t}\\n\\t}\\n}\\n\"},\"typeVersion\":1.2},{\"id\":\"a1211873-05ca-48c7-aa93-57d80b37174b\",\"name\":\"Google Gemini LLM\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatGoogleGemini\",\"disabled\":true,\"position\":[320,-540],\"parameters\":{\"options\":{\"temperature\":0.4},\"modelName\":\"models/gemini-2.0-flash-exp\"},\"typeVersion\":1},{\"id\":\"14327277-1e66-401d-9c74-8fdb6d76445f\",\"name\":\"gpt-4o-mini\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[1360,-540],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4o-mini\",\"cachedResultName\":\"gpt-4o-mini\"},\"options\":{\"responseFormat\":\"text\"}},\"typeVersion\":1.2},{\"id\":\"9a49454b-f518-4388-82a7-2529addae3e5\",\"name\":\"gpt-4o\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"disabled\":true,\"position\":[1500,-540],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4o\",\"cachedResultName\":\"gpt-4o\"},\"options\":{\"responseFormat\":\"text\"}},\"typeVersion\":1.2},{\"id\":\"56eb9c72-87fc-42b2-b576-be68b3a8c7d2\",\"name\":\"gpt-4o LLM\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[180,-540],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4o\",\"cachedResultName\":\"gpt-4o\"},\"options\":{\"responseFormat\":\"text\"}},\"typeVersion\":1.2},{\"id\":\"bf4e6d41-b2be-44fc-8fc7-6dc6bc4ee69a\",\"name\":\"pollinations.ai\",\"type\":\"n8n-nodes-base.httpRequest\",\"disabled\":true,\"position\":[980,780],\"parameters\":{\"url\":\"=https://image.pollinations.ai/prompt/{{$('Social Media Content Factory').item.json.output.description.replaceAll(' ','-').replaceAll(',','').replaceAll('.','') }}\",\"options\":{}},\"typeVersion\":4.2},{\"id\":\"7b5b53eb-85c6-4a90-b209-7bd8d638f237\",\"name\":\"Merge\",\"type\":\"n8n-nodes-base.merge\",\"position\":[700,20],\"parameters\":{\"mode\":\"combine\",\"options\":{\"includeUnpaired\":true},\"combineBy\":\"combineByPosition\"},\"typeVersion\":3},{\"id\":\"daa6773e-0e15-4994-bcee-b3d996655855\",\"name\":\"Save Image to imgbb.com3\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[360,-140],\"parameters\":{\"url\":\"https://api.imgbb.com/1/upload\",\"method\":\"POST\",\"options\":{\"redirect\":{\"redirect\":{}}},\"sendBody\":true,\"sendQuery\":true,\"contentType\":\"multipart-form-data\",\"bodyParameters\":{\"parameters\":[{\"name\":\"image\",\"parameterType\":\"formBinaryData\",\"inputDataFieldName\":\"data\"}]},\"queryParameters\":{\"parameters\":[{\"name\":\"expiration\",\"value\":\"0\"},{\"name\":\"key\",\"value\":\"={{ $env.IMGBB_API_KEY}} \"}]}},\"typeVersion\":4.2},{\"id\":\"af06853c-258e-4dfb-a579-3168c8de96bd\",\"name\":\"Instagram Image\",\"type\":\"n8n-nodes-base.httpRequest\",\"onError\":\"continueRegularOutput\",\"position\":[1700,-60],\"parameters\":{\"url\":\"https://graph.facebook.com/v20.0/[your-unique-id]/media\",\"method\":\"POST\",\"options\":{},\"sendQuery\":true,\"authentication\":\"predefinedCredentialType\",\"queryParameters\":{\"parameters\":[{\"name\":\"image_url\",\"value\":\"={{ $json.data.medium.url }}\"},{\"name\":\"caption\",\"value\":\"={{ $('Social Media Content Factory').item.json.output.platform_posts.Instagram.caption }}\"}]},\"nodeCredentialType\":\"facebookGraphApi\"},\"typeVersion\":4.2},{\"id\":\"6ee72138-a8ec-4fbd-8f14-fd6e881edfd1\",\"name\":\"Instragram Post\",\"type\":\"n8n-nodes-base.facebookGraphApi\",\"onError\":\"continueRegularOutput\",\"position\":[1700,160],\"parameters\":{\"edge\":\"media_publish\",\"node\":\"[your-unique-id]\",\"options\":{\"queryParameters\":{\"parameter\":[{\"name\":\"creation_id\",\"value\":\"={{ $json.id }}\"},{\"name\":\"caption\",\"value\":\"={{ $('Social Media Content Factory').item.json.output.platform_posts.Instagram.caption }}\"}]}},\"graphApiVersion\":\"v20.0\",\"httpRequestMethod\":\"POST\"},\"typeVersion\":1,\"alwaysOutputData\":true},{\"id\":\"9e168865-1eae-4e53-99c9-91b041426ecb\",\"name\":\"X Post\",\"type\":\"n8n-nodes-base.twitter\",\"onError\":\"continueRegularOutput\",\"position\":[1700,380],\"parameters\":{\"text\":\"={{ $('Social Media Content Factory').item.json.output.platform_posts['X-Twitter'].post }}\",\"additionalFields\":{}},\"typeVersion\":2,\"alwaysOutputData\":true},{\"id\":\"4ee55c94-7251-445e-8ce7-15eee7165010\",\"name\":\"Facebook Post\",\"type\":\"n8n-nodes-base.facebookGraphApi\",\"onError\":\"continueRegularOutput\",\"position\":[1700,600],\"parameters\":{\"edge\":\"photos\",\"node\":\"[your-unique-id]\",\"options\":{\"queryParameters\":{\"parameter\":[{\"name\":\"message\",\"value\":\"={{ $('Social Media Content Factory').item.json.output.platform_posts.Facebook.post }}\\n\\n{{ $('Social Media Content Factory').item.json.output.platform_posts.Facebook.call_to_action }}\\n\"},{\"name\":\"link\",\"value\":\"={{ $('Social Media Content Factory').item.json.output.platform_posts.Facebook.call_to_action }}\"}]}},\"sendBinaryData\":true,\"graphApiVersion\":\"v20.0\",\"httpRequestMethod\":\"POST\",\"binaryPropertyName\":\"data\"},\"typeVersion\":1,\"alwaysOutputData\":true},{\"id\":\"3a015f3f-a162-411a-85e8-e1f042d9c653\",\"name\":\"LinkedIn Post\",\"type\":\"n8n-nodes-base.linkedIn\",\"onError\":\"continueRegularOutput\",\"position\":[1700,780],\"parameters\":{\"text\":\"={{ $('Social Media Content Factory').item.json.output.platform_posts.LinkedIn.post }}\\n{{ $('Social Media Content Factory').item.json.output.platform_posts.LinkedIn.call_to_action }}\\n{{ $('Social Media Content Factory').item.json.output.platform_posts.LinkedIn.hashtags }}\\n{{ $('Social Media Content Factory').item.json.output.platform_posts.LinkedIn.call_to_action }}\",\"postAs\":\"organization\",\"organization\":\"12345678\",\"additionalFields\":{},\"binaryPropertyName\":\"=data\",\"shareMediaCategory\":\"IMAGE\"},\"typeVersion\":1,\"alwaysOutputData\":true},{\"id\":\"8ab03d75-b4c5-4271-8fa9-830f449a3a3c\",\"name\":\"OpenAI\",\"type\":\"@n8n/n8n-nodes-langchain.openAi\",\"position\":[40,-20],\"parameters\":{\"prompt\":\"={{ $('Social Media Content Factory').item.json.output.platform_posts.Instagram.caption }}\",\"options\":{},\"resource\":\"image\"},\"typeVersion\":1.8,\"alwaysOutputData\":true},{\"id\":\"d1ac29b1-128d-4615-b828-89f1f64d1b15\",\"name\":\"Merge1\",\"type\":\"n8n-nodes-base.merge\",\"position\":[1440,-60],\"parameters\":{\"mode\":\"combine\",\"options\":{},\"combineBy\":\"combineByPosition\"},\"typeVersion\":3},{\"id\":\"71eebce8-027a-4b12-b07e-692121de9a68\",\"name\":\"Merge2\",\"type\":\"n8n-nodes-base.merge\",\"position\":[1440,680],\"parameters\":{\"mode\":\"combine\",\"options\":{\"includeUnpaired\":true},\"combineBy\":\"combineByPosition\"},\"typeVersion\":3},{\"id\":\"140cff41-a619-4111-8dc9-3ec8fc45e061\",\"name\":\"Aggregate\",\"type\":\"n8n-nodes-base.aggregate\",\"position\":[-240,520],\"parameters\":{\"options\":{},\"aggregate\":\"aggregateAllItemData\"},\"typeVersion\":1},{\"id\":\"3e96bfac-dad5-4b75-b51b-50329892ee70\",\"name\":\"gpt-4o-mini1\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[-20,540],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4o-mini\",\"cachedResultName\":\"gpt-4o-mini\"},\"options\":{\"responseFormat\":\"text\"}},\"typeVersion\":1.2},{\"id\":\"4d73d59f-bb8c-481b-877a-bf4dc64f3277\",\"name\":\"gpt-4o-mini2\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[-20,820],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4o-mini\",\"cachedResultName\":\"gpt-4o-mini\"},\"options\":{\"responseFormat\":\"text\"}},\"typeVersion\":1.2},{\"id\":\"aaef70d7-6029-4fae-afc1-72a6a0019b03\",\"name\":\"Gmail User for Approval\",\"type\":\"n8n-nodes-base.gmail\",\"position\":[2000,-540],\"webhookId\":\"c46cf421-ddb6-45a8-b83b-80b381666f0e\",\"parameters\":{\"sendTo\":\"={{ $env.EMAIL_ADDRESS_JOE }} \",\"message\":\"={{ $json.output }}\",\"options\":{\"limitWaitTime\":{\"values\":{\"resumeUnit\":\"minutes\",\"resumeAmount\":45}}},\"subject\":\"=🔥FOR APPROVAL🔥{{ $('Social Media Content Factory').item.json.output.name }} - {{ $('Social Media Content Factory').item.json.output.description }}\",\"operation\":\"sendAndWait\",\"approvalOptions\":{\"values\":{\"approvalType\":\"double\"}}},\"typeVersion\":2.1},{\"id\":\"930e76ac-6e9c-4a3f-9229-28ba18de25a3\",\"name\":\"Approve Final Post Content\",\"type\":\"n8n-nodes-base.gmail\",\"disabled\":true,\"position\":[980,380],\"webhookId\":\"c46cf421-ddb6-45a8-b83b-80b381666f0e\",\"parameters\":{\"sendTo\":\"={{ $env.EMAIL_ADDRESS_JOE }} \",\"message\":\"=\\n\\n
          \\n\\n

          LinkedIn

          \\n \\n \\n
          \\n\\n \\n
          \\n \\\"Featured\\n
          \\n\\n \\n
          \\n\\n

          \\n {{ $('Social Media Content Factory').item.json.output.platform_posts.LinkedIn.post }}\\n

          \\n \\n
          \\n \\n {{ $('Social Media Content Factory').item.json.output.platform_posts.LinkedIn.hashtags }}\\n \\n
          \\n\\n

          \\n {{ $('Social Media Content Factory').item.json.output.platform_posts.LinkedIn.call_to_action }}\\n

          \\n
          \\n
          \\n
          \\n\\n\\n\",\"options\":{\"limitWaitTime\":{\"values\":{\"resumeUnit\":\"minutes\",\"resumeAmount\":45}}},\"subject\":\"=🔥FOR APPROVAL🔥 New LinkedIn Post\",\"operation\":\"sendAndWait\",\"approvalOptions\":{\"values\":{\"approvalType\":\"double\"}}},\"typeVersion\":2.1},{\"id\":\"b42df164-47ae-4e08-9099-d0958dd41c8f\",\"name\":\"Is Approved?\",\"type\":\"n8n-nodes-base.if\",\"position\":[1160,20],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"efe337a1-63e0-4513-873d-421bf41e4868\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json.data.approved }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2},{\"id\":\"e3193aef-d115-4c3b-87b2-b8ebd5bb0c05\",\"name\":\"Instagram Result\",\"type\":\"n8n-nodes-base.set\",\"position\":[2040,160],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"5c6edc76-1e3b-45b0-8baa-33a14c678150\",\"name\":\"Instagram Post Result\",\"type\":\"string\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"6f8b248f-5c79-412c-81ef-3c52bef7f257\",\"name\":\"X Result\",\"type\":\"n8n-nodes-base.set\",\"position\":[2040,380],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"5c6edc76-1e3b-45b0-8baa-33a14c678150\",\"name\":\"X Post Result\",\"type\":\"string\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"4c1ee118-aba1-4632-bd48-27cef9d5e272\",\"name\":\"Facebook Result\",\"type\":\"n8n-nodes-base.set\",\"position\":[2040,600],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"5c6edc76-1e3b-45b0-8baa-33a14c678150\",\"name\":\"Facebook Post Result\",\"type\":\"string\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"490223f9-9b6a-4617-8829-c8e4b130feb7\",\"name\":\"LinkedIn Result\",\"type\":\"n8n-nodes-base.set\",\"position\":[2040,780],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"5c6edc76-1e3b-45b0-8baa-33a14c678150\",\"name\":\"LinkedIn Post Result\",\"type\":\"string\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"9732c12e-903e-49ac-8d29-ffc4d78c7ff8\",\"name\":\"Submit Social Post Details\",\"type\":\"n8n-nodes-base.formTrigger\",\"position\":[-180,-740],\"webhookId\":\"3e762442-715e-47e1-a65e-ae92085857ae\",\"parameters\":{\"options\":{\"buttonLabel\":\"Automatically Generate Social Media Content\"},\"formTitle\":\"workflows.diy\",\"formFields\":{\"values\":[{\"fieldLabel\":\"Topic\",\"placeholder\":\"Provide a concise and clear title or main topic for your post (e.g., \\\"New Product Launch,\\\" \\\"Exciting Company Update\\\"). This helps the AI accurately capture the focus of your content.\",\"requiredField\":true},{\"fieldLabel\":\"Keywords or Hashtags (optional)\",\"placeholder\":\"Include any specific keywords or hashtags you'd like the AI to incorporate into the post. This ensures the content aligns with your branding and campaign objectives.\",\"requiredField\":\"={{ false }}\"},{\"fieldLabel\":\"Link (optional)\",\"placeholder\":\"=Provide the URL of any product, service, form, support page, or other resource. This link will be included in the generated post to direct your audience to the relevant content.\\n\"}]},\"responseMode\":\"lastNode\",\"formDescription\":\"=Welcome to the workflows.diy AI-Powered Assistant!\\n\\nThis tool is designed to streamline and enhance your social media content creation process.\\n\\nSimply provide key inputs like a topic or title and an optional image, and our intelligent agent will generate engaging, platform-specific post descriptions tailored to your audience. \\n\\nWhether you're a marketer, business owner, or influencer, this assistant saves you time while delivering professional-quality content optimized for maximum impact.\\n\\n\"},\"typeVersion\":2.2},{\"id\":\"1955b762-b9c4-4704-955b-093686e827bd\",\"name\":\"Merge Results\",\"type\":\"n8n-nodes-base.merge\",\"onError\":\"continueRegularOutput\",\"position\":[2340,780],\"parameters\":{\"numberInputs\":4},\"typeVersion\":3,\"alwaysOutputData\":true},{\"id\":\"6dc47749-eb49-4351-89aa-50f2b6c035bb\",\"name\":\"Social Media Content Factory\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[300,-740],\"parameters\":{\"text\":\"=You are a **content creation AI** for workflows.diy, a leading creator of **n8n workflow automation solutions and AI Agentic workflows**.\\n\\nYour goal is to craft **engaging, platform-specific content** for LinkedIn, Instagram, Facebook, Twitter (X), TikTok, Threads, and YouTube Shorts. Each post must align with the platform’s audience preferences, tone, and style while reflecting workflows.diy's expertise. The content should provide **value-driven insights**, tutorials, reviews, and discussions that resonate with tech professionals, automation enthusiasts, businesses, and n8n users.\\n\\n### Key Objectives:\\n1. **Platform Optimization**: Tailor content format, tone, and hashtags to suit each platform’s algorithm and audience engagement patterns.\\n2. **SEO & Hashtags**: Use a mix of general automation hashtags and trending platform-specific hashtags to maximize reach.\\n3. **Engagement Focus**: Create content that sparks interaction through tutorials, comparisons, reviews, or thought-provoking discussions.\\n4. **Consistency**: Maintain a professional yet approachable tone across all platforms while adapting to audience needs.\\n5. **Data-Driven Strategy**: Analyze trends and performance data to refine content strategy and hashtag usage.\\n\\n### General Hashtags:\\n#workflowsdiy #n8n #automation #AIWorkflows #WorkflowAutomation #TechSolutions\\n\\n---\\n\\n### Platform-Specific Guidelines:\\n\\n#### 1. LinkedIn\\n - **Style**: Professional and insightful.\\n - **Tone**: Business-oriented; focus on automation use cases, industry insights, and community impact.\\n - **Content Length**: 3-4 sentences; concise but detailed.\\n - **Hashtags**: #Innovation #Automation #WorkflowSolutions #DigitalTransformation #Leadership\\n - **Call to Action (CTA)**: Encourage comments or visits to workflows.diy’s website for more insights.\\n\\n#### 2. Instagram\\n - **Style**: Visual storytelling with creative captions.\\n - **Tone**: Inspirational and engaging; use emojis for relatability.\\n - **Content Length**: 2-3 sentences paired with eye-catching visuals (e.g., infographics or workflow demos).\\n - **Visuals**: Showcase milestones (e.g., new workflow launches), tutorials, or product highlights.\\n - **CTA**: Use phrases like \\\"Swipe to learn more,\\\" \\\"Tag your team,\\\" or \\\"Check out the link below!\\\"\\n - **Link Placement**: Add the provided link before hashtags; if no link is provided, use \\\"Visit our website: https://workflows.diy.\\\"\\n - **Hashtags**: #AutomationLife #TechInnovation #WorkflowTips #Programming #Engineering\\n\\n#### 3. Facebook\\n - **Style**: Friendly and community-focused.\\n - **Tone**: Relatable; highlight user success stories or company achievements in automation.\\n - **Content Length**: 2-3 sentences; conversational yet professional.\\n - **Hashtags**: #SmallBusinessAutomation #Entrepreneurship #Leadership #WorkflowInnovation\\n - **CTA**: Encourage likes, shares, comments (e.g., “What’s your favorite automation tip?”).\\n\\n#### 4. Twitter (X)\\n - **Style**: Concise and impactful.\\n - **Tone**: Crisp and engaging; spark curiosity in 150 characters or less.\\n - **Hashtags**: #WorkflowTrends #AIWorkflows #AutomationTips #NoCodeSolutions\\n - **CTA**: Drive quick engagement through retweets or replies (e.g., “What’s your go-to n8n workflow?”).\\n\\n#### 5. TikTok\\n - **Style**: Short-form video content with trending audio or effects.\\n - **Tone**: Fun yet informative; focus on quick workflow demos or automation tips.\\n - **Content Length**: 15-60 seconds with captions summarizing the key message.\\n - **Hashtags**: Use trending tech-related hashtags relevant to TikTok’s audience (e.g., #n8nTips).\\n - **CTA**: Encourage viewers to follow workflows.diy for more automation hacks.\\n\\n#### 6. Threads\\n - **Style**: Conversational and community-driven posts.\\n - **Tone**: Casual yet informative; encourage discussions around automation trends or innovations.\\n - **Content Length**: 1-2 short paragraphs with a question or thought-provoking statement at the end.\\n - **Hashtags**: Similar to Instagram but tailored for trending Threads topics related to automation.\\n\\n#### 7. YouTube Shorts\\n - **Style**: Short-form video content showcasing quick workflow tutorials or use cases.\\n - **Tone**: Authoritative yet approachable; establish workflows.diy as a leader in n8n automation solutions.\\n - Content Length:\\n - Tutorials/Reviews (long-form): 5-10 minutes\\n - Shorts/Highlights (short-form): Under 1 minute\\n - CTA:** Encourage subscriptions**, likes, comments (e.g., “Subscribe for more workflow tips!”).\\n\\n---\\n\\n### Content Creation Workflow:\\nFor every post:\\n1. Use the following input fields:\\n - Topic/About the Post: {{ $json.Topic }}\\n - Keywords/Focus Areas: {{ $json.formMode }}\\n - Link (optional): {{ $json['Link (optional)'] }}\\n2. Adapt the tone/style based on the platform guidelines above.\\n\\nEnsure every post reflects workflows.diy's mission of delivering high-quality automation insights while maximizing engagement across platforms.\\n\\nFollow the provided JSON schema for your reponse.\\n\",\"options\":{\"systemMessage\":\"=Use the provided tools to research the topic based on latest information. Todays date is {{ $now }}\"},\"promptType\":\"define\",\"hasOutputParser\":true},\"retryOnFail\":true,\"typeVersion\":1.7},{\"id\":\"88c548bf-40e5-4b89-aef0-9233c3f5bc9c\",\"name\":\"Prepare Content Review Email\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[1440,-740],\"parameters\":{\"text\":\"=Generate clean, modern HTML email content from the provided JSON data with these requirements:\\n- Use table-based layout with inline CSS for email compatibility\\n- Create card sections for each platform containing:\\n • Title header (20px) \\n • Post content (16px) \\n • Video/image suggestions (italic 14px)\\n • Hashtag list (inline-block with # prefix)\\n • Emoji preservation where present\\n • Call-to-action (bold 14px)\\n- Structure using:\\n • 600px max-width container\\n • 20px padding between cards\\n • Left-aligned text hierarchy\\n • Arial/sans-serif font stack\\n • Email-safe colors (#333 text, #555 secondary)\\n- Include all platform-specific elements:\\n ▶ Video/image suggestions in italic\\n ▶ Hashtags as linked search terms\\n ▶ Emojis in original positions\\n ▶ Character limits for Twitter\\n ▶ Platform-specific CTAs\\n ▶ Visual quality reminders\\n- Format hashtags as:\\n #tag\\n\\nInput data: {{ $json.output.toJsonString() }}\\n\\nRemove ALL code blocks and comments. Output ONLY the raw HTML with:\\n- Platform cards in JSON order\\n- All data elements represented\\n- Mobile-responsive tables\\n- W3C-valid markup\\n\\n## Example HTML:\\n\\n\\t\\t\\n\\t\\t\\t
          \\n\\t\\t\\t\\t\\n\\t\\t\\t\\t\\t\\n\\t\\t\\t\\t\\t\\t\\n\\t\\t\\t\\t\\t\\n\\t\\t\\t\\t\\n
          \\n\\t\\t\\t\\t\\t\\t\\t

          LinkedIn
          Discover why n8n stands out as the premier workflow automation tool. Its flexibility and open-source nature empower businesses to create custom solutions that drive efficiency and innovation.
          Video/Image suggestion pending
          #Innovation#Automation#WorkflowSolutions#DigitalTransformation#Leadership#workflowsdiy#n8n#AIWorkflows#WorkflowAutomation#TechSolutions
          Visit workflows.diy to explore how n8n can transform your business processes!
          Instagram
          Eye-catching infographic comparing n8n to other automation tools, highlighting its unique features.
          n8n: The ultimate workflow automation tool! \\\"💡\\\" Unlock limitless possibilities with its open-source platform. Boost your productivity and streamline your processes. \\\"💤\\\"
          #AutomationLife#TechInnovation#WorkflowTips#Programming#Engineering#workflowsdiy#n8n#AIWorkflows#WorkflowAutomation#TechSolutions
          Visit our website: https://n8n.io/ #AutomationLife #TechInnovation #WorkflowTips #Programming #Engineering
          Facebook
          See why businesses are choosing n8n for their workflow automation needs. From its user-friendly interface to its powerful customization options, n8n is revolutionizing how companies approach automation.
          A visually appealing graphic showcasing n8n's key features and benefits.
          #SmallBusinessAutomation#Entrepreneurship#Leadership#WorkflowInnovation#workflowsdiy#n8n#AIWorkflows#WorkflowAutomation#TechSolutions
          What's your favorite automation tip? Share in the comments!
          Twitter
          n8n: The best #WorkflowAutomation tool! Open-source, customizable, and powerful. Transform your business processes today!
          #WorkflowTrends#AIWorkflows#AutomationTips#NoCodeSolutions#workflowsdiy#n8n#TechSolutions
          TikTok
          Quick demo showcasing how n8n simplifies complex workflows with its intuitive interface.
          n8n: Your go-to for effortless workflow automation! \\\"✨\\\"
          #n8nTips#workflowsdiy#n8n#AIWorkflows#WorkflowAutomation#TechSolutions
          Follow workflows.diy for more automation hacks!
          Threads
          n8n is transforming the automation landscape. Its open-source nature and extensive integrations make it a top choice for businesses of all sizes. What are your thoughts on the future of workflow automation?
          #workflowsdiy#n8n#AIWorkflows#WorkflowAutomation#TechSolutions
          Share your insights below!
          YouTube Shorts
          Short tutorial demonstrating how to build a simple automation workflow in n8n.
          Learn why n8n is the top choice for workflow automation. Its open-source platform and powerful features make it a game-changer for businesses.
          #n8n#automation#workflowautomation#nocode#workflowsdiy#AIWorkflows#TechSolutions
          Subscribe for more workflow tips!

          \\n\\t\\t\\t\\t\\t\\t
          \\n\",\"agent\":\"conversationalAgent\",\"options\":{},\"promptType\":\"define\"},\"typeVersion\":1.7},{\"id\":\"3b074887-262f-47ab-b69c-c51b3a513993\",\"name\":\"Prepare Results Email\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[0,380],\"parameters\":{\"text\":\"=Parse the social media post results and generate a modern single line HTML table showing platform statuses. For each entry:\\n\\n-Extract platform name from the JSON key\\n-Identify status (Success/Error) based on statusCode or error presence\\n-Capture error message if present\\n-Format as responsive HTML table with professional styling\\n-Ensure email client compatibility with inline CSS\\n-Include error handling for invalid JSON formats\\n-Remove all line breaks and \\\\n from response.\\n-Avoid any preamble or further explanation and remove all ``` and ```html from response.\\n\\n## Implementation Example:\\nThis solution uses the parsed results from your workflow to generate:\\n\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
          PlatformStatusDetails
          Instagram✗ ErrorUnsupported post request. Object with ID '[your-unique-id]' does not exist, cannot be loaded due to missing permissions.
          X (Twitter)✗ ErrorUnable to sign without access token
          Facebook✗ ErrorUnsupported post request. Object with ID '[your-unique-id]' does not exist, cannot be loaded due to missing permissions.
          LinkedIn✗ ErrorUnable to sign without access token
          \\n\\n\\nThis is the social media post results: \\n{{ $json.data.toJsonString() }}\\n\",\"agent\":\"conversationalAgent\",\"options\":{},\"promptType\":\"define\"},\"typeVersion\":1.7},{\"id\":\"abb3994f-bf23-43f8-9c46-28795cfd2017\",\"name\":\"Prepare Results Message\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[0,660],\"parameters\":{\"text\":\"=Parse the social media post results and generate a brief summary of the results.\\n\\nThis is the social media post results: \\n{{ $json.data.toJsonString() }}\\n\\n## Example Response:\\nThe social media post results indicate multiple errors when attempting to access or post content on various platforms. \\n\\n1. Instagram: The response shows a 400 status code with an error message indicating that the specific post request is unsupported due to missing permissions or an invalid object ID. \\n\\n2. X Post: Success\\n\\n3. Facebook: Success \\n\\n4. LinkedIn: Also returned an 'Unable to sign without access token' error. \\n\\nOverall, access token issues and unsupported requests are frequent problems across these social media platforms.\\n\",\"agent\":\"conversationalAgent\",\"options\":{},\"promptType\":\"define\"},\"typeVersion\":1.7},{\"id\":\"b4a4838a-83b0-4f28-a9f3-dea915228325\",\"name\":\"Image Choice\",\"type\":\"n8n-nodes-base.form\",\"disabled\":true,\"position\":[-620,-120],\"webhookId\":\"0dc811ef-b2e0-4213-a0c9-e9b5fb9fcbf1\",\"parameters\":{\"options\":{\"formTitle\":\"Generate Post Image\",\"buttonLabel\":\"Submit\"},\"formFields\":{\"values\":[{\"fieldType\":\"file\",\"fieldLabel\":\"Upload Image (optional)\",\"multipleFiles\":false,\"acceptFileTypes\":\".jpg, .png, .jpeg\"},{\"fieldType\":\"dropdown\",\"fieldLabel\":\"Generate Custom Image using AI Image Generator\",\"fieldOptions\":{\"values\":[{\"option\":\"Yes\"},{\"option\":\"No\"}]},\"requiredField\":true}]}},\"typeVersion\":1},{\"id\":\"1cf97c10-e60f-4584-b069-3d4506868d8e\",\"name\":\"Gmail Results\",\"type\":\"n8n-nodes-base.gmail\",\"position\":[360,380],\"webhookId\":\"0a81b95a-cd82-465d-8450-cf38518a4cbb\",\"parameters\":{\"sendTo\":\"={{ $env.EMAIL_ADDRESS_JOE }} \",\"message\":\"={{ $json.output }}\",\"options\":{\"appendAttribution\":false},\"subject\":\"🔥RESULTS🔥 Social Media Factory\"},\"typeVersion\":2.1},{\"id\":\"c845ae46-9d37-472b-ae0f-49fc6940e685\",\"name\":\"Telegram Results\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[360,660],\"webhookId\":\"bb40ede7-03cf-493d-b051-196b96725925\",\"parameters\":{\"text\":\"={{ $json.output }}\",\"chatId\":\"={{ $env.TELEGRAM_CHAT_ID }}\",\"additionalFields\":{\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"643b94c6-4535-4876-9660-d82ff69cbcf6\",\"name\":\"Is Content Approved?\",\"type\":\"n8n-nodes-base.if\",\"position\":[-240,-20],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"e32d270f-f258-4522-94e1-2cb7ee4e8d2a\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json.data.approved }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2},{\"id\":\"fb7108e2-21cf-4df4-ab20-fe75b15b0a24\",\"name\":\"Set Default True 2\",\"type\":\"n8n-nodes-base.set\",\"position\":[980,20],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"f150aa79-2d20-4869-b60a-350d49a215a5\",\"name\":\"data\",\"type\":\"object\",\"value\":\"={\\n \\\"approved\\\": true\\n}\"}]}},\"typeVersion\":3.4},{\"id\":\"0a10bca0-c3a8-496b-a22e-120928ad7736\",\"name\":\"SerpAPI\",\"type\":\"@n8n/n8n-nodes-langchain.toolSerpApi\",\"position\":[460,-540],\"parameters\":{\"options\":{}},\"typeVersion\":1},{\"id\":\"b21f527c-5674-49d0-a114-866d669e7ad6\",\"name\":\"Rename Binary File\",\"type\":\"n8n-nodes-base.code\",\"position\":[-620,120],\"parameters\":{\"jsCode\":\"$input.first().binary.data = $input.first().binary.Upload_Image__optional_\\ndelete $input.first().binary.Upload_Image__optional_\\nreturn $input.first()\"},\"typeVersion\":2,\"alwaysOutputData\":true}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Merge\":{\"main\":[[{\"node\":\"Set Default True 2\",\"type\":\"main\",\"index\":0}]]},\"Merge1\":{\"main\":[[{\"node\":\"Instagram Image\",\"type\":\"main\",\"index\":0}]]},\"Merge2\":{\"main\":[[{\"node\":\"Facebook Post\",\"type\":\"main\",\"index\":0},{\"node\":\"LinkedIn Post\",\"type\":\"main\",\"index\":0}]]},\"OpenAI\":{\"main\":[[{\"node\":\"Save Image to imgbb.com3\",\"type\":\"main\",\"index\":0},{\"node\":\"Merge\",\"type\":\"main\",\"index\":1},{\"node\":\"Merge2\",\"type\":\"main\",\"index\":1}]]},\"X Post\":{\"main\":[[{\"node\":\"X Result\",\"type\":\"main\",\"index\":0}],[]]},\"SerpAPI\":{\"ai_tool\":[[{\"node\":\"Social Media Content Factory\",\"type\":\"ai_tool\",\"index\":0}]]},\"X Result\":{\"main\":[[{\"node\":\"Merge Results\",\"type\":\"main\",\"index\":1}]]},\"Aggregate\":{\"main\":[[{\"node\":\"Prepare Results Email\",\"type\":\"main\",\"index\":0},{\"node\":\"Prepare Results Message\",\"type\":\"main\",\"index\":0}]]},\"gpt-4o LLM\":{\"ai_languageModel\":[[{\"node\":\"Social Media Content Factory\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"gpt-4o-mini\":{\"ai_languageModel\":[[{\"node\":\"Prepare Content Review Email\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Image Choice\":{\"main\":[[{\"node\":\"Rename Binary File\",\"type\":\"main\",\"index\":0}]]},\"Is Approved?\":{\"main\":[[{\"node\":\"X Post\",\"type\":\"main\",\"index\":0},{\"node\":\"Merge1\",\"type\":\"main\",\"index\":1},{\"node\":\"Merge2\",\"type\":\"main\",\"index\":0}],[]]},\"gpt-4o-mini1\":{\"ai_languageModel\":[[{\"node\":\"Prepare Results Email\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"gpt-4o-mini2\":{\"ai_languageModel\":[[{\"node\":\"Prepare Results Message\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Facebook Post\":{\"main\":[[{\"node\":\"Facebook Result\",\"type\":\"main\",\"index\":0}],[]]},\"LinkedIn Post\":{\"main\":[[{\"node\":\"LinkedIn Result\",\"type\":\"main\",\"index\":0}],[]]},\"Merge Results\":{\"main\":[[{\"node\":\"Aggregate\",\"type\":\"main\",\"index\":0}]]},\"Facebook Result\":{\"main\":[[{\"node\":\"Merge Results\",\"type\":\"main\",\"index\":2}]]},\"Instagram Image\":{\"main\":[[{\"node\":\"Instragram Post\",\"type\":\"main\",\"index\":0}]]},\"Instragram Post\":{\"main\":[[{\"node\":\"Instagram Result\",\"type\":\"main\",\"index\":0}],[]]},\"LinkedIn Result\":{\"main\":[[{\"node\":\"Merge Results\",\"type\":\"main\",\"index\":3}]]},\"pollinations.ai\":{\"main\":[[]]},\"Instagram Result\":{\"main\":[[{\"node\":\"Merge Results\",\"type\":\"main\",\"index\":0}]]},\"Google Gemini LLM\":{\"ai_languageModel\":[[]]},\"Set Default True 2\":{\"main\":[[{\"node\":\"Is Approved?\",\"type\":\"main\",\"index\":0}]]},\"Is Content Approved?\":{\"main\":[[{\"node\":\"OpenAI\",\"type\":\"main\",\"index\":0}]]},\"Social Media Content\":{\"ai_outputParser\":[[{\"node\":\"Social Media Content Factory\",\"type\":\"ai_outputParser\",\"index\":0}]]},\"Prepare Results Email\":{\"main\":[[{\"node\":\"Gmail Results\",\"type\":\"main\",\"index\":0}]]},\"Gmail User for Approval\":{\"main\":[[{\"node\":\"Is Content Approved?\",\"type\":\"main\",\"index\":0}]]},\"Prepare Results Message\":{\"main\":[[{\"node\":\"Telegram Results\",\"type\":\"main\",\"index\":0}]]},\"Save Image to imgbb.com3\":{\"main\":[[{\"node\":\"Merge\",\"type\":\"main\",\"index\":0},{\"node\":\"Merge1\",\"type\":\"main\",\"index\":0}]]},\"Approve Final Post Content\":{\"main\":[[]]},\"Submit Social Post Details\":{\"main\":[[{\"node\":\"Social Media Content Factory\",\"type\":\"main\",\"index\":0}]]},\"Prepare Content Review Email\":{\"main\":[[{\"node\":\"Gmail User for Approval\",\"type\":\"main\",\"index\":0}]]},\"Social Media Content Factory\":{\"main\":[[{\"node\":\"Prepare Content Review Email\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 39, "node_types": {"outputParserStructured": 1, "lmChatGoogleGemini": 1, "lmChatOpenAi": 5, "httpRequest": 3, "merge": 4, "facebookGraphApi": 2, "twitter": 1, "linkedIn": 1, "openAi": 1, "aggregate": 1, "gmail": 3, "if": 2, "set": 5, "formTrigger": 1, "agent": 4, "form": 1, "telegram": 1, "toolSerpApi": 1, "code": 1}, "services": ["ai", "google", "email", "http"], "complexity": "complex", "has_conditions": true, "has_loops": false, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: ✨🤖Automate Multi-Platform Social Media Content Creation with AI"}, {"role": "assistant", "content": "\n**Analyse du besoin**: Automate Multi-Platform Social Media Content Creation with AI\nWho is this for?\n\nSocial Media Managers and Digital Marketers seeking to streamline content production across 7+ platforms (X/Twitter, Ins...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 39 nodes utilisant ai, google, email, http.\nStructure: logique conditionnelle, code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"CfdF2XtXC68iJ6Hr\",\"meta\":{\"instanceId\":\"31e69f7f4a77bf465b805824e303232f0227212ae922d12133a0f96ffeab4fef\",\"templateCredsSetupCompleted\":true},\"name\":\"✨🤖Automated AI Powered Social Media Content Factory for X + Facebook + Instagram + LinkedIn\",\"tags\":[],\"nodes\":[{\"id\":\"9b6e2038-9f65-4e0f-b13d-6c09e8224ed6\",\"name\":\"Social Media Content\",\"type\":\"@n8n/n8n-nodes-langchain.outputParserStructured\",\"position\":[560,-540],\"parameters\":{\"schemaType\":\"manual\",\"inputSchema\":\"{\\n\\t\\\"type\\\": \\\"object\\\",\\n\\t\\\"properties\\\": {\\n\\t\\t\\\"name\\\": {\\n\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t},\\n\\t\\t\\\"description\\\": {\\n\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t},\\n\\t\\t\\\"platform_posts\\\": {\\n\\t\\t\\t\\\"type\\\": \\\"object\\\",\\n\\t\\t\\t\\\"properties\\\": {\\n\\t\\t\\t\\t\\\"LinkedIn\\\": {\\n\\t\\t\\t\\t\\t\\\"type\\\": \\\"object\\\",\\n\\t\\t\\t\\t\\t\\\"properties\\\": {\\n \\\"image_suggestion\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"post\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"hashtags\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"array\\\",\\n\\t\\t\\t\\t\\t\\t\\t\\\"items\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"call_to_action\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\\"Instagram\\\": {\\n\\t\\t\\t\\t\\t\\\"type\\\": \\\"object\\\",\\n\\t\\t\\t\\t\\t\\\"properties\\\": {\\n\\t\\t\\t\\t\\t\\t\\\"image_suggestion\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"caption\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"hashtags\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"array\\\",\\n\\t\\t\\t\\t\\t\\t\\t\\\"items\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"emojis\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"array\\\",\\n\\t\\t\\t\\t\\t\\t\\t\\\"items\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"call_to_action\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\\"Facebook\\\": {\\n\\t\\t\\t\\t\\t\\\"type\\\": \\\"object\\\",\\n\\t\\t\\t\\t\\t\\\"properties\\\": {\\n\\t\\t\\t\\t\\t\\t\\\"post\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"hashtags\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"array\\\",\\n\\t\\t\\t\\t\\t\\t\\t\\\"items\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"call_to_action\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"image_suggestion\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\\"X-Twitter\\\": {\\n\\t\\t\\t\\t\\t\\\"type\\\": \\\"object\\\",\\n\\t\\t\\t\\t\\t\\\"properties\\\": {\\n \\\"video_suggestion\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t},\\n \\\"image_suggestion\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"post\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"hashtags\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"array\\\",\\n\\t\\t\\t\\t\\t\\t\\t\\\"items\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t\\\"character_limit\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"integer\\\"\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t},\\n \\\"TikTok\\\": {\\n \\t\\\"type\\\": \\\"object\\\",\\n \\t\\\"properties\\\": {\\n \\t\\t\\\"video_suggestion\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t},\\n \\t\\t\\\"caption\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t},\\n \\t\\t\\\"hashtags\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"array\\\",\\n \\t\\t\\t\\\"items\\\": {\\n \\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t\\t}\\n \\t\\t},\\n \\t\\t\\\"call_to_action\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t}\\n \\t}\\n },\\n \\\"Threads\\\": {\\n \\t\\\"type\\\": \\\"object\\\",\\n \\t\\\"properties\\\": {\\n \\\"image_suggestion\\\": {\\n\\t\\t\\t\\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t\\t\\t\\t\\t},\\n \\t\\t\\\"text_post\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t},\\n \\t\\t\\\"hashtags\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"array\\\",\\n \\t\\t\\t\\\"items\\\": {\\n \\t\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t\\t}\\n \\t\\t},\\n \\t\\t\\\"call_to_action\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t}\\n \\t}\\n },\\n \\\"YouTube_Shorts\\\": {\\n \\t\\\"type\\\": \\\"object\\\",\\n \\t\\\"properties\\\": {\\n \\t\\t\\\"video_suggestion\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t},\\n \\t\\t\\\"title\\\": {\\n \\t\\t\\t\\\"type\\\": \\\"string\\\"\\n \\t\\t},\\n \\\"description\\\": {\\n \\\"type\\\": \\\"string\\\"\\n },\\n \\\"hashtags\\\": {\\n \\\"type\\\": \\\"array\\\",\\n \\\"items\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n },\\n \\\"call_to_action\\\": {\\n \\\"type\\\": \\\"string\\\"\\n }\\n }\\n }\\n\\t\\t\\t}\\n\\t\\t},\\n\\t\\t\\\"additional_notes\\\": {\\n\\t\\t\\t\\\"type\\\": \\\"string\\\"\\n\\t\\t}\\n\\t}\\n}\\n\"},\"typeVersion\":1.2},{\"id\":\"a1211873-05ca-48c7-aa93-57d80b37174b\",\"name\":\"Google Gemini LLM\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatGoogleGemini\",\"disabled\":true,\"position\":[320,-540],\"parameters\":{\"options\":{\"temperature\":0.4},\"modelName\":\"models/gemini-2.0-flash-exp\"},\"typeVersion\":1},{\"id\":\"14327277-1e66-401d-9c74-8fdb6d76445f\",\"name\":\"gpt-4o-mini\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[1360,-540],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4o-mini\",\"cachedResultName\":\"gpt-4o-mini\"},\"options\":{\"responseFormat\":\"text\"}},\"typeVersion\":1.2},{\"id\":\"9a49454b-f518-4388-82a7-2529addae3e5\",\"name\":\"gpt-4o\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"disabled\":true,\"position\":[1500,-540],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4o\",\"cachedResultName\":\"gpt-4o\"},\"options\":{\"responseFormat\":\"text\"}},\"typeVersion\":1.2},{\"id\":\"56eb9c72-87fc-42b2-b576-be68b3a8c7d2\",\"name\":\"gpt-4o LLM\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[180,-540],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4o\",\"cachedResultName\":\"gpt-4o\"},\"options\":{\"responseFormat\":\"text\"}},\"typeVersion\":1.2},{\"id\":\"bf4e6d41-b2be-44fc-8fc7-6dc6bc4ee69a\",\"name\":\"pollinations.ai\",\"type\":\"n8n-nodes-base.httpRequest\",\"disabled\":true,\"position\":[980,780],\"parameters\":{\"url\":\"=https://image.pollinations.ai/prompt/{{$('Social Media Content Factory').item.json.output.description.replaceAll(' ','-').replaceAll(',','').replaceAll('.','') }}\",\"options\":{}},\"typeVersion\":4.2},{\"id\":\"7b5b53eb-85c6-4a90-b209-7bd8d638f237\",\"name\":\"Merge\",\"type\":\"n8n-nodes-base.merge\",\"position\":[700,20],\"parameters\":{\"mode\":\"combine\",\"options\":{\"includeUnpaired\":true},\"combineBy\":\"combineByPosition\"},\"typeVersion\":3},{\"id\":\"daa6773e-0e15-4994-bcee-b3d996655855\",\"name\":\"Save Image to imgbb.com3\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[360,-140],\"parameters\":{\"url\":\"https://api.imgbb.com/1/upload\",\"method\":\"POST\",\"options\":{\"redirect\":{\"redirect\":{}}},\"sendBody\":true,\"sendQuery\":true,\"contentType\":\"multipart-form-data\",\"bodyParameters\":{\"parameters\":[{\"name\":\"image\",\"parameterType\":\"formBinaryData\",\"inputDataFieldName\":\"data\"}]},\"queryParameters\":{\"parameters\":[{\"name\":\"expiration\",\"value\":\"0\"},{\"name\":\"key\",\"value\":\"={{ $env.IMGBB_API_KEY}} \"}]}},\"typeVersion\":4.2},{\"id\":\"af06853c-258e-4dfb-a579-3168c8de96bd\",\"name\":\"Instagram Image\",\"type\":\"n8n-nodes-base.httpRequest\",\"onError\":\"continueRegularOutput\",\"position\":[1700,-60],\"parameters\":{\"url\":\"https://graph.facebook.com/v20.0/[your-unique-id]/media\",\"method\":\"POST\",\"options\":{},\"sendQuery\":true,\"authentication\":\"predefinedCredentialType\",\"queryParameters\":{\"parameters\":[{\"name\":\"image_url\",\"value\":\"={{ $json.data.medium.url }}\"},{\"name\":\"caption\",\"value\":\"={{ $('Social Media Content Factory').item.json.output.platform_posts.Instagram.caption }}\"}]},\"nodeCredentialType\":\"facebookGraphApi\"},\"typeVersion\":4.2},{\"id\":\"6ee72138-a8ec-4fbd-8f14-fd6e881edfd1\",\"name\":\"Instragram Post\",\"type\":\"n8n-nodes-base.facebookGraphApi\",\"onError\":\"continueRegularOutput\",\"position\":[1700,160],\"parameters\":{\"edge\":\"media_publish\",\"node\":\"[your-unique-id]\",\"options\":{\"queryParameters\":{\"parameter\":[{\"name\":\"creation_id\",\"value\":\"={{ $json.id }}\"},{\"name\":\"caption\",\"value\":\"={{ $('Social Media Content Factory').item.json.output.platform_posts.Instagram.caption }}\"}]}},\"graphApiVersion\":\"v20.0\",\"httpRequestMethod\":\"POST\"},\"typeVersion\":1,\"alwaysOutputData\":true},{\"id\":\"9e168865-1eae-4e53-99c9-91b041426ecb\",\"name\":\"X Post\",\"type\":\"n8n-nodes-base.twitter\",\"onError\":\"continueRegularOutput\",\"position\":[1700,380],\"parameters\":{\"text\":\"={{ $('Social Media Content Factory').item.json.output.platform_posts['X-Twitter'].post }}\",\"additionalFields\":{}},\"typeVersion\":2,\"alwaysOutputData\":true},{\"id\":\"4ee55c94-7251-445e-8ce7-15eee7165010\",\"name\":\"Facebook Post\",\"type\":\"n8n-nodes-base.facebookGraphApi\",\"onError\":\"continueRegularOutput\",\"position\":[1700,600],\"parameters\":{\"edge\":\"photos\",\"node\":\"[your-unique-id]\",\"options\":{\"queryParameters\":{\"parameter\":[{\"name\":\"message\",\"value\":\"={{ $('Social Media Content Factory').item.json.output.platform_posts.Facebook.post }}\\n\\n{{ $('Social Media Content Factory').item.json.output.platform_posts.Facebook.call_to_action }}\\n\"},{\"name\":\"link\",\"value\":\"={{ $('Social Media Content Factory').item.json.output.platform_posts.Facebook.call_to_action }}\"}]}},\"sendBinaryData\":true,\"graphApiVersion\":\"v20.0\",\"httpRequestMethod\":\"POST\",\"binaryPropertyName\":\"data\"},\"typeVersion\":1,\"alwaysOutputData\":true},{\"id\":\"3a015f3f-a162-411a-85e8-e1f042d9c653\",\"name\":\"LinkedIn Post\",\"type\":\"n8n-nodes-base.linkedIn\",\"onError\":\"continueRegularOutput\",\"position\":[1700,780],\"parameters\":{\"text\":\"={{ $('Social Media Content Factory').item.json.output.platform_posts.LinkedIn.post }}\\n{{ $('Social Media Content Factory').item.json.output.platform_posts.LinkedIn.call_to_action }}\\n{{ $('Social Media Content Factory').item.json.output.platform_posts.LinkedIn.hashtags }}\\n{{ $('Social Media Content Factory').item.json.output.platform_posts.LinkedIn.call_to_action }}\",\"postAs\":\"organization\",\"organization\":\"12345678\",\"additionalFields\":{},\"binaryPropertyName\":\"=data\",\"shareMediaCategory\":\"IMAGE\"},\"typeVersion\":1,\"alwaysOutputData\":true},{\"id\":\"8ab03d75-b4c5-4271-8fa9-830f449a3a3c\",\"name\":\"OpenAI\",\"type\":\"@n8n/n8n-nodes-langchain.openAi\",\"position\":[40,-20],\"parameters\":{\"prompt\":\"={{ $('Social Media Content Factory').item.json.output.platform_posts.Instagram.caption }}\",\"options\":{},\"resource\":\"image\"},\"typeVersion\":1.8,\"alwaysOutputData\":true},{\"id\":\"d1ac29b1-128d-4615-b828-89f1f64d1b15\",\"name\":\"Merge1\",\"type\":\"n8n-nodes-base.merge\",\"position\":[1440,-60],\"parameters\":{\"mode\":\"combine\",\"options\":{},\"combineBy\":\"combineByPosition\"},\"typeVersion\":3},{\"id\":\"71eebce8-027a-4b12-b07e-692121de9a68\",\"name\":\"Merge2\",\"type\":\"n8n-nodes-base.merge\",\"position\":[1440,680],\"parameters\":{\"mode\":\"combine\",\"options\":{\"includeUnpaired\":true},\"combineBy\":\"combineByPosition\"},\"typeVersion\":3},{\"id\":\"140cff41-a619-4111-8dc9-3ec8fc45e061\",\"name\":\"Aggregate\",\"type\":\"n8n-nodes-base.aggregate\",\"position\":[-240,520],\"parameters\":{\"options\":{},\"aggregate\":\"aggregateAllItemData\"},\"typeVersion\":1},{\"id\":\"3e96bfac-dad5-4b75-b51b-50329892ee70\",\"name\":\"gpt-4o-mini1\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[-20,540],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4o-mini\",\"cachedResultName\":\"gpt-4o-mini\"},\"options\":{\"responseFormat\":\"text\"}},\"typeVersion\":1.2},{\"id\":\"4d73d59f-bb8c-481b-877a-bf4dc64f3277\",\"name\":\"gpt-4o-mini2\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[-20,820],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4o-mini\",\"cachedResultName\":\"gpt-4o-mini\"},\"options\":{\"responseFormat\":\"text\"}},\"typeVersion\":1.2},{\"id\":\"aaef70d7-6029-4fae-afc1-72a6a0019b03\",\"name\":\"Gmail User for Approval\",\"type\":\"n8n-nodes-base.gmail\",\"position\":[2000,-540],\"webhookId\":\"c46cf421-ddb6-45a8-b83b-80b381666f0e\",\"parameters\":{\"sendTo\":\"={{ $env.EMAIL_ADDRESS_JOE }} \",\"message\":\"={{ $json.output }}\",\"options\":{\"limitWaitTime\":{\"values\":{\"resumeUnit\":\"minutes\",\"resumeAmount\":45}}},\"subject\":\"=🔥FOR APPROVAL🔥{{ $('Social Media Content Factory').item.json.output.name }} - {{ $('Social Media Content Factory').item.json.output.description }}\",\"operation\":\"sendAndWait\",\"approvalOptions\":{\"values\":{\"approvalType\":\"double\"}}},\"typeVersion\":2.1},{\"id\":\"930e76ac-6e9c-4a3f-9229-28ba18de25a3\",\"name\":\"Approve Final Post Content\",\"type\":\"n8n-nodes-base.gmail\",\"disabled\":true,\"position\":[980,380],\"webhookId\":\"c46cf421-ddb6-45a8-b83b-80b381666f0e\",\"parameters\":{\"sendTo\":\"={{ $env.EMAIL_ADDRESS_JOE }} \",\"message\":\"=\\n\\n
          \\n\\n

          LinkedIn

          \\n \\n \\n
          \\n\\n \\n
          \\n \\\"Featured\\n
          \\n\\n \\n
          \\n\\n

          \\n {{ $('Social Media Content Factory').item.json.output.platform_posts.LinkedIn.post }}\\n

          \\n \\n
          \\n \\n {{ $('Social Media Content Factory').item.json.output.platform_posts.LinkedIn.hashtags }}\\n \\n
          \\n\\n

          \\n {{ $('Social Media Content Factory').item.json.output.platform_posts.LinkedIn.call_to_action }}\\n

          \\n
          \\n
          \\n
          \\n\\n\\n\",\"options\":{\"limitWaitTime\":{\"values\":{\"resumeUnit\":\"minutes\",\"resumeAmount\":45}}},\"subject\":\"=🔥FOR APPROVAL🔥 New LinkedIn Post\",\"operation\":\"sendAndWait\",\"approvalOptions\":{\"values\":{\"approvalType\":\"double\"}}},\"typeVersion\":2.1},{\"id\":\"b42df164-47ae-4e08-9099-d0958dd41c8f\",\"name\":\"Is Approved?\",\"type\":\"n8n-nodes-base.if\",\"position\":[1160,20],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"efe337a1-63e0-4513-873d-421bf41e4868\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json.data.approved }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2},{\"id\":\"e3193aef-d115-4c3b-87b2-b8ebd5bb0c05\",\"name\":\"Instagram Result\",\"type\":\"n8n-nodes-base.set\",\"position\":[2040,160],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"5c6edc76-1e3b-45b0-8baa-33a14c678150\",\"name\":\"Instagram Post Result\",\"type\":\"string\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"6f8b248f-5c79-412c-81ef-3c52bef7f257\",\"name\":\"X Result\",\"type\":\"n8n-nodes-base.set\",\"position\":[2040,380],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"5c6edc76-1e3b-45b0-8baa-33a14c678150\",\"name\":\"X Post Result\",\"type\":\"string\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"4c1ee118-aba1-4632-bd48-27cef9d5e272\",\"name\":\"Facebook Result\",\"type\":\"n8n-nodes-base.set\",\"position\":[2040,600],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"5c6edc76-1e3b-45b0-8baa-33a14c678150\",\"name\":\"Facebook Post Result\",\"type\":\"string\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"490223f9-9b6a-4617-8829-c8e4b130feb7\",\"name\":\"LinkedIn Result\",\"type\":\"n8n-nodes-base.set\",\"position\":[2040,780],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"5c6edc76-1e3b-45b0-8baa-33a14c678150\",\"name\":\"LinkedIn Post Result\",\"type\":\"string\",\"value\":\"={{ $json }}\"}]}},\"typeVersion\":3.4},{\"id\":\"9732c12e-903e-49ac-8d29-ffc4d78c7ff8\",\"name\":\"Submit Social Post Details\",\"type\":\"n8n-nodes-base.formTrigger\",\"position\":[-180,-740],\"webhookId\":\"3e762442-715e-47e1-a65e-ae92085857ae\",\"parameters\":{\"options\":{\"buttonLabel\":\"Automatically Generate Social Media Content\"},\"formTitle\":\"workflows.diy\",\"formFields\":{\"values\":[{\"fieldLabel\":\"Topic\",\"placeholder\":\"Provide a concise and clear title or main topic for your post (e.g., \\\"New Product Launch,\\\" \\\"Exciting Company Update\\\"). This helps the AI accurately capture the focus of your content.\",\"requiredField\":true},{\"fieldLabel\":\"Keywords or Hashtags (optional)\",\"placeholder\":\"Include any specific keywords or hashtags you'd like the AI to incorporate into the post. This ensures the content aligns with your branding and campaign objectives.\",\"requiredField\":\"={{ false }}\"},{\"fieldLabel\":\"Link (optional)\",\"placeholder\":\"=Provide the URL of any product, service, form, support page, or other resource. This link will be included in the generated post to direct your audience to the relevant content.\\n\"}]},\"responseMode\":\"lastNode\",\"formDescription\":\"=Welcome to the workflows.diy AI-Powered Assistant!\\n\\nThis tool is designed to streamline and enhance your social media content creation process.\\n\\nSimply provide key inputs like a topic or title and an optional image, and our intelligent agent will generate engaging, platform-specific post descriptions tailored to your audience. \\n\\nWhether you're a marketer, business owner, or influencer, this assistant saves you time while delivering professional-quality content optimized for maximum impact.\\n\\n\"},\"typeVersion\":2.2},{\"id\":\"1955b762-b9c4-4704-955b-093686e827bd\",\"name\":\"Merge Results\",\"type\":\"n8n-nodes-base.merge\",\"onError\":\"continueRegularOutput\",\"position\":[2340,780],\"parameters\":{\"numberInputs\":4},\"typeVersion\":3,\"alwaysOutputData\":true},{\"id\":\"6dc47749-eb49-4351-89aa-50f2b6c035bb\",\"name\":\"Social Media Content Factory\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[300,-740],\"parameters\":{\"text\":\"=You are a **content creation AI** for workflows.diy, a leading creator of **n8n workflow automation solutions and AI Agentic workflows**.\\n\\nYour goal is to craft **engaging, platform-specific content** for LinkedIn, Instagram, Facebook, Twitter (X), TikTok, Threads, and YouTube Shorts. Each post must align with the platform’s audience preferences, tone, and style while reflecting workflows.diy's expertise. The content should provide **value-driven insights**, tutorials, reviews, and discussions that resonate with tech professionals, automation enthusiasts, businesses, and n8n users.\\n\\n### Key Objectives:\\n1. **Platform Optimization**: Tailor content format, tone, and hashtags to suit each platform’s algorithm and audience engagement patterns.\\n2. **SEO & Hashtags**: Use a mix of general automation hashtags and trending platform-specific hashtags to maximize reach.\\n3. **Engagement Focus**: Create content that sparks interaction through tutorials, comparisons, reviews, or thought-provoking discussions.\\n4. **Consistency**: Maintain a professional yet approachable tone across all platforms while adapting to audience needs.\\n5. **Data-Driven Strategy**: Analyze trends and performance data to refine content strategy and hashtag usage.\\n\\n### General Hashtags:\\n#workflowsdiy #n8n #automation #AIWorkflows #WorkflowAutomation #TechSolutions\\n\\n---\\n\\n### Platform-Specific Guidelines:\\n\\n#### 1. LinkedIn\\n - **Style**: Professional and insightful.\\n - **Tone**: Business-oriented; focus on automation use cases, industry insights, and community impact.\\n - **Content Length**: 3-4 sentences; concise but detailed.\\n - **Hashtags**: #Innovation #Automation #WorkflowSolutions #DigitalTransformation #Leadership\\n - **Call to Action (CTA)**: Encourage comments or visits to workflows.diy’s website for more insights.\\n\\n#### 2. Instagram\\n - **Style**: Visual storytelling with creative captions.\\n - **Tone**: Inspirational and engaging; use emojis for relatability.\\n - **Content Length**: 2-3 sentences paired with eye-catching visuals (e.g., infographics or workflow demos).\\n - **Visuals**: Showcase milestones (e.g., new workflow launches), tutorials, or product highlights.\\n - **CTA**: Use phrases like \\\"Swipe to learn more,\\\" \\\"Tag your team,\\\" or \\\"Check out the link below!\\\"\\n - **Link Placement**: Add the provided link before hashtags; if no link is provided, use \\\"Visit our website: https://workflows.diy.\\\"\\n - **Hashtags**: #AutomationLife #TechInnovation #WorkflowTips #Programming #Engineering\\n\\n#### 3. Facebook\\n - **Style**: Friendly and community-focused.\\n - **Tone**: Relatable; highlight user success stories or company achievements in automation.\\n - **Content Length**: 2-3 sentences; conversational yet professional.\\n - **Hashtags**: #SmallBusinessAutomation #Entrepreneurship #Leadership #WorkflowInnovation\\n - **CTA**: Encourage likes, shares, comments (e.g., “What’s your favorite automation tip?”).\\n\\n#### 4. Twitter (X)\\n - **Style**: Concise and impactful.\\n - **Tone**: Crisp and engaging; spark curiosity in 150 characters or less.\\n - **Hashtags**: #WorkflowTrends #AIWorkflows #AutomationTips #NoCodeSolutions\\n - **CTA**: Drive quick engagement through retweets or replies (e.g., “What’s your go-to n8n workflow?”).\\n\\n#### 5. TikTok\\n - **Style**: Short-form video content with trending audio or effects.\\n - **Tone**: Fun yet informative; focus on quick workflow demos or automation tips.\\n - **Content Length**: 15-60 seconds with captions summarizing the key message.\\n - **Hashtags**: Use trending tech-related hashtags relevant to TikTok’s audience (e.g., #n8nTips).\\n - **CTA**: Encourage viewers to follow workflows.diy for more automation hacks.\\n\\n#### 6. Threads\\n - **Style**: Conversational and community-driven posts.\\n - **Tone**: Casual yet informative; encourage discussions around automation trends or innovations.\\n - **Content Length**: 1-2 short paragraphs with a question or thought-provoking statement at the end.\\n - **Hashtags**: Similar to Instagram but tailored for trending Threads topics related to automation.\\n\\n#### 7. YouTube Shorts\\n - **Style**: Short-form video content showcasing quick workflow tutorials or use cases.\\n - **Tone**: Authoritative yet approachable; establish workflows.diy as a leader in n8n automation solutions.\\n - Content Length:\\n - Tutorials/Reviews (long-form): 5-10 minutes\\n - Shorts/Highlights (short-form): Under 1 minute\\n - CTA:** Encourage subscriptions**, likes, comments (e.g., “Subscribe for more workflow tips!”).\\n\\n---\\n\\n### Content Creation Workflow:\\nFor every post:\\n1. Use the following input fields:\\n - Topic/About the Post: {{ $json.Topic }}\\n - Keywords/Focus Areas: {{ $json.formMode }}\\n - Link (optional): {{ $json['Link (optional)'] }}\\n2. Adapt the tone/style based on the platform guidelines above.\\n\\nEnsure every post reflects workflows.diy's mission of delivering high-quality automation insights while maximizing engagement across platforms.\\n\\nFollow the provided JSON schema for your reponse.\\n\",\"options\":{\"systemMessage\":\"=Use the provided tools to research the topic based on latest information. Todays date is {{ $now }}\"},\"promptType\":\"define\",\"hasOutputParser\":true},\"retryOnFail\":true,\"typeVersion\":1.7},{\"id\":\"88c548bf-40e5-4b89-aef0-9233c3f5bc9c\",\"name\":\"Prepare Content Review Email\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[1440,-740],\"parameters\":{\"text\":\"=Generate clean, modern HTML email content from the provided JSON data with these requirements:\\n- Use table-based layout with inline CSS for email compatibility\\n- Create card sections for each platform containing:\\n • Title header (20px) \\n • Post content (16px) \\n • Video/image suggestions (italic 14px)\\n • Hashtag list (inline-block with # prefix)\\n • Emoji preservation where present\\n • Call-to-action (bold 14px)\\n- Structure using:\\n • 600px max-width container\\n • 20px padding between cards\\n • Left-aligned text hierarchy\\n • Arial/sans-serif font stack\\n • Email-safe colors (#333 text, #555 secondary)\\n- Include all platform-specific elements:\\n ▶ Video/image suggestions in italic\\n ▶ Hashtags as linked search terms\\n ▶ Emojis in original positions\\n ▶ Character limits for Twitter\\n ▶ Platform-specific CTAs\\n ▶ Visual quality reminders\\n- Format hashtags as:\\n #tag\\n\\nInput data: {{ $json.output.toJsonString() }}\\n\\nRemove ALL code blocks and comments. Output ONLY the raw HTML with:\\n- Platform cards in JSON order\\n- All data elements represented\\n- Mobile-responsive tables\\n- W3C-valid markup\\n\\n## Example HTML:\\n\\n\\t\\t\\n\\t\\t\\t
          \\n\\t\\t\\t\\t\\n\\t\\t\\t\\t\\t\\n\\t\\t\\t\\t\\t\\t\\n\\t\\t\\t\\t\\t\\n\\t\\t\\t\\t\\n
          \\n\\t\\t\\t\\t\\t\\t\\t

          LinkedIn
          Discover why n8n stands out as the premier workflow automation tool. Its flexibility and open-source nature empower businesses to create custom solutions that drive efficiency and innovation.
          Video/Image suggestion pending
          #Innovation#Automation#WorkflowSolutions#DigitalTransformation#Leadership#workflowsdiy#n8n#AIWorkflows#WorkflowAutomation#TechSolutions
          Visit workflows.diy to explore how n8n can transform your business processes!
          Instagram
          Eye-catching infographic comparing n8n to other automation tools, highlighting its unique features.
          n8n: The ultimate workflow automation tool! \\\"💡\\\" Unlock limitless possibilities with its open-source platform. Boost your productivity and streamline your processes. \\\"💤\\\"
          #AutomationLife#TechInnovation#WorkflowTips#Programming#Engineering#workflowsdiy#n8n#AIWorkflows#WorkflowAutomation#TechSolutions
          Visit our website: https://n8n.io/ #AutomationLife #TechInnovation #WorkflowTips #Programming #Engineering
          Facebook
          See why businesses are choosing n8n for their workflow automation needs. From its user-friendly interface to its powerful customization options, n8n is revolutionizing how companies approach automation.
          A visually appealing graphic showcasing n8n's key features and benefits.
          #SmallBusinessAutomation#Entrepreneurship#Leadership#WorkflowInnovation#workflowsdiy#n8n#AIWorkflows#WorkflowAutomation#TechSolutions
          What's your favorite automation tip? Share in the comments!
          Twitter
          n8n: The best #WorkflowAutomation tool! Open-source, customizable, and powerful. Transform your business processes today!
          #WorkflowTrends#AIWorkflows#AutomationTips#NoCodeSolutions#workflowsdiy#n8n#TechSolutions
          TikTok
          Quick demo showcasing how n8n simplifies complex workflows with its intuitive interface.
          n8n: Your go-to for effortless workflow automation! \\\"✨\\\"
          #n8nTips#workflowsdiy#n8n#AIWorkflows#WorkflowAutomation#TechSolutions
          Follow workflows.diy for more automation hacks!
          Threads
          n8n is transforming the automation landscape. Its open-source nature and extensive integrations make it a top choice for businesses of all sizes. What are your thoughts on the future of workflow automation?
          #workflowsdiy#n8n#AIWorkflows#WorkflowAutomation#TechSolutions
          Share your insights below!
          YouTube Shorts
          Short tutorial demonstrating how to build a simple automation workflow in n8n.
          Learn why n8n is the top choice for workflow automation. Its open-source platform and powerful features make it a game-changer for businesses.
          #n8n#automation#workflowautomation#nocode#workflowsdiy#AIWorkflows#TechSolutions
          Subscribe for more workflow tips!

          \\n\\t\\t\\t\\t\\t\\t
          \\n\",\"agent\":\"conversationalAgent\",\"options\":{},\"promptType\":\"define\"},\"typeVersion\":1.7},{\"id\":\"3b074887-262f-47ab-b69c-c51b3a513993\",\"name\":\"Prepare Results Email\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[0,380],\"parameters\":{\"text\":\"=Parse the social media post results and generate a modern single line HTML table showing platform statuses. For each entry:\\n\\n-Extract platform name from the JSON key\\n-Identify status (Success/Error) based on statusCode or error presence\\n-Capture error message if present\\n-Format as responsive HTML table with professional styling\\n-Ensure email client compatibility with inline CSS\\n-Include error handling for invalid JSON formats\\n-Remove all line breaks and \\\\n from response.\\n-Avoid any preamble or further explanation and remove all ``` and ```html from response.\\n\\n## Implementation Example:\\nThis solution uses the parsed results from your workflow to generate:\\n\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
          PlatformStatusDetails
          Instagram✗ ErrorUnsupported post request. Object with ID '[your-unique-id]' does not exist, cannot be loaded due to missing permissions.
          X (Twitter)✗ ErrorUnable to sign without access token
          Facebook✗ ErrorUnsupported post request. Object with ID '[your-unique-id]' does not exist, cannot be loaded due to missing permissions.
          LinkedIn✗ ErrorUnable to sign without access token
          \\n\\n\\nThis is the social media post results: \\n{{ $json.data.toJsonString() }}\\n\",\"agent\":\"conversationalAgent\",\"options\":{},\"promptType\":\"define\"},\"typeVersion\":1.7},{\"id\":\"abb3994f-bf23-43f8-9c46-28795cfd2017\",\"name\":\"Prepare Results Message\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[0,660],\"parameters\":{\"text\":\"=Parse the social media post results and generate a brief summary of the results.\\n\\nThis is the social media post results: \\n{{ $json.data.toJsonString() }}\\n\\n## Example Response:\\nThe social media post results indicate multiple errors when attempting to access or post content on various platforms. \\n\\n1. Instagram: The response shows a 400 status code with an error message indicating that the specific post request is unsupported due to missing permissions or an invalid object ID. \\n\\n2. X Post: Success\\n\\n3. Facebook: Success \\n\\n4. LinkedIn: Also returned an 'Unable to sign without access token' error. \\n\\nOverall, access token issues and unsupported requests are frequent problems across these social media platforms.\\n\",\"agent\":\"conversationalAgent\",\"options\":{},\"promptType\":\"define\"},\"typeVersion\":1.7},{\"id\":\"b4a4838a-83b0-4f28-a9f3-dea915228325\",\"name\":\"Image Choice\",\"type\":\"n8n-nodes-base.form\",\"disabled\":true,\"position\":[-620,-120],\"webhookId\":\"0dc811ef-b2e0-4213-a0c9-e9b5fb9fcbf1\",\"parameters\":{\"options\":{\"formTitle\":\"Generate Post Image\",\"buttonLabel\":\"Submit\"},\"formFields\":{\"values\":[{\"fieldType\":\"file\",\"fieldLabel\":\"Upload Image (optional)\",\"multipleFiles\":false,\"acceptFileTypes\":\".jpg, .png, .jpeg\"},{\"fieldType\":\"dropdown\",\"fieldLabel\":\"Generate Custom Image using AI Image Generator\",\"fieldOptions\":{\"values\":[{\"option\":\"Yes\"},{\"option\":\"No\"}]},\"requiredField\":true}]}},\"typeVersion\":1},{\"id\":\"1cf97c10-e60f-4584-b069-3d4506868d8e\",\"name\":\"Gmail Results\",\"type\":\"n8n-nodes-base.gmail\",\"position\":[360,380],\"webhookId\":\"0a81b95a-cd82-465d-8450-cf38518a4cbb\",\"parameters\":{\"sendTo\":\"={{ $env.EMAIL_ADDRESS_JOE }} \",\"message\":\"={{ $json.output }}\",\"options\":{\"appendAttribution\":false},\"subject\":\"🔥RESULTS🔥 Social Media Factory\"},\"typeVersion\":2.1},{\"id\":\"c845ae46-9d37-472b-ae0f-49fc6940e685\",\"name\":\"Telegram Results\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[360,660],\"webhookId\":\"bb40ede7-03cf-493d-b051-196b96725925\",\"parameters\":{\"text\":\"={{ $json.output }}\",\"chatId\":\"={{ $env.TELEGRAM_CHAT_ID }}\",\"additionalFields\":{\"appendAttribution\":false}},\"typeVersion\":1.2},{\"id\":\"643b94c6-4535-4876-9660-d82ff69cbcf6\",\"name\":\"Is Content Approved?\",\"type\":\"n8n-nodes-base.if\",\"position\":[-240,-20],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"e32d270f-f258-4522-94e1-2cb7ee4e8d2a\",\"operator\":{\"type\":\"boolean\",\"operation\":\"true\",\"singleValue\":true},\"leftValue\":\"={{ $json.data.approved }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2},{\"id\":\"fb7108e2-21cf-4df4-ab20-fe75b15b0a24\",\"name\":\"Set Default True 2\",\"type\":\"n8n-nodes-base.set\",\"position\":[980,20],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"f150aa79-2d20-4869-b60a-350d49a215a5\",\"name\":\"data\",\"type\":\"object\",\"value\":\"={\\n \\\"approved\\\": true\\n}\"}]}},\"typeVersion\":3.4},{\"id\":\"0a10bca0-c3a8-496b-a22e-120928ad7736\",\"name\":\"SerpAPI\",\"type\":\"@n8n/n8n-nodes-langchain.toolSerpApi\",\"position\":[460,-540],\"parameters\":{\"options\":{}},\"typeVersion\":1},{\"id\":\"b21f527c-5674-49d0-a114-866d669e7ad6\",\"name\":\"Rename Binary File\",\"type\":\"n8n-nodes-base.code\",\"position\":[-620,120],\"parameters\":{\"jsCode\":\"$input.first().binary.data = $input.first().binary.Upload_Image__optional_\\ndelete $input.first().binary.Upload_Image__optional_\\nreturn $input.first()\"},\"typeVersion\":2,\"alwaysOutputData\":true}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Merge\":{\"main\":[[{\"node\":\"Set Default True 2\",\"type\":\"main\",\"index\":0}]]},\"Merge1\":{\"main\":[[{\"node\":\"Instagram Image\",\"type\":\"main\",\"index\":0}]]},\"Merge2\":{\"main\":[[{\"node\":\"Facebook Post\",\"type\":\"main\",\"index\":0},{\"node\":\"LinkedIn Post\",\"type\":\"main\",\"index\":0}]]},\"OpenAI\":{\"main\":[[{\"node\":\"Save Image to imgbb.com3\",\"type\":\"main\",\"index\":0},{\"node\":\"Merge\",\"type\":\"main\",\"index\":1},{\"node\":\"Merge2\",\"type\":\"main\",\"index\":1}]]},\"X Post\":{\"main\":[[{\"node\":\"X Result\",\"type\":\"main\",\"index\":0}],[]]},\"SerpAPI\":{\"ai_tool\":[[{\"node\":\"Social Media Content Factory\",\"type\":\"ai_tool\",\"index\":0}]]},\"X Result\":{\"main\":[[{\"node\":\"Merge Results\",\"type\":\"main\",\"index\":1}]]},\"Aggregate\":{\"main\":[[{\"node\":\"Prepare Results Email\",\"type\":\"main\",\"index\":0},{\"node\":\"Prepare Results Message\",\"type\":\"main\",\"index\":0}]]},\"gpt-4o LLM\":{\"ai_languageModel\":[[{\"node\":\"Social Media Content Factory\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"gpt-4o-mini\":{\"ai_languageModel\":[[{\"node\":\"Prepare Content Review Email\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Image Choice\":{\"main\":[[{\"node\":\"Rename Binary File\",\"type\":\"main\",\"index\":0}]]},\"Is Approved?\":{\"main\":[[{\"node\":\"X Post\",\"type\":\"main\",\"index\":0},{\"node\":\"Merge1\",\"type\":\"main\",\"index\":1},{\"node\":\"Merge2\",\"type\":\"main\",\"index\":0}],[]]},\"gpt-4o-mini1\":{\"ai_languageModel\":[[{\"node\":\"Prepare Results Email\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"gpt-4o-mini2\":{\"ai_languageModel\":[[{\"node\":\"Prepare Results Message\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Facebook Post\":{\"main\":[[{\"node\":\"Facebook Result\",\"type\":\"main\",\"index\":0}],[]]},\"LinkedIn Post\":{\"main\":[[{\"node\":\"LinkedIn Result\",\"type\":\"main\",\"index\":0}],[]]},\"Merge Results\":{\"main\":[[{\"node\":\"Aggregate\",\"type\":\"main\",\"index\":0}]]},\"Facebook Result\":{\"main\":[[{\"node\":\"Merge Results\",\"type\":\"main\",\"index\":2}]]},\"Instagram Image\":{\"main\":[[{\"node\":\"Instragram Post\",\"type\":\"main\",\"index\":0}]]},\"Instragram Post\":{\"main\":[[{\"node\":\"Instagram Result\",\"type\":\"main\",\"index\":0}],[]]},\"LinkedIn Result\":{\"main\":[[{\"node\":\"Merge Results\",\"type\":\"main\",\"index\":3}]]},\"pollinations.ai\":{\"main\":[[]]},\"Instagram Result\":{\"main\":[[{\"node\":\"Merge Results\",\"type\":\"main\",\"index\":0}]]},\"Google Gemini LLM\":{\"ai_languageModel\":[[]]},\"Set Default True 2\":{\"main\":[[{\"node\":\"Is Approved?\",\"type\":\"main\",\"index\":0}]]},\"Is Content Approved?\":{\"main\":[[{\"node\":\"OpenAI\",\"type\":\"main\",\"index\":0}]]},\"Social Media Content\":{\"ai_outputParser\":[[{\"node\":\"Social Media Content Factory\",\"type\":\"ai_outputParser\",\"index\":0}]]},\"Prepare Results Email\":{\"main\":[[{\"node\":\"Gmail Results\",\"type\":\"main\",\"index\":0}]]},\"Gmail User for Approval\":{\"main\":[[{\"node\":\"Is Content Approved?\",\"type\":\"main\",\"index\":0}]]},\"Prepare Results Message\":{\"main\":[[{\"node\":\"Telegram Results\",\"type\":\"main\",\"index\":0}]]},\"Save Image to imgbb.com3\":{\"main\":[[{\"node\":\"Merge\",\"type\":\"main\",\"index\":0},{\"node\":\"Merge1\",\"type\":\"main\",\"index\":0}]]},\"Approve Final Post Content\":{\"main\":[[]]},\"Submit Social Post Details\":{\"main\":[[{\"node\":\"Social Media Content Factory\",\"type\":\"main\",\"index\":0}]]},\"Prepare Content Review Email\":{\"main\":[[{\"node\":\"Gmail User for Approval\",\"type\":\"main\",\"index\":0}]]},\"Social Media Content Factory\":{\"main\":[[{\"node\":\"Prepare Content Review Email\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 39, "node_types": {"outputParserStructured": 1, "lmChatGoogleGemini": 1, "lmChatOpenAi": 5, "httpRequest": 3, "merge": 4, "facebookGraphApi": 2, "twitter": 1, "linkedIn": 1, "openAi": 1, "aggregate": 1, "gmail": 3, "if": 2, "set": 5, "formTrigger": 1, "agent": 4, "form": 1, "telegram": 1, "toolSerpApi": 1, "code": 1}, "services": ["ai", "google", "email", "http"], "complexity": "complex", "has_conditions": true, "has_loops": false, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: This n8n template demonstrates how to use AI to generate custom images from scratch - fully automated, prompt-driven, and ready to deploy at scale. Use cases are many: You can use it for marketing visuals, character art, digital posters, storyboards, or even daily image generation for your personal purposes. How It Works The flow is triggered by a chat message in N8N or via Telegram. The default image size is 1080 x 1920 pixels. To use a different size, update the values in the “Fields - Set Values” node before triggering the workflow. The input is parsed into a clean, structured prompt using a multi-step transformation process. Our AI Agent sends the final prompt to Google Gemini’s image model for generation (you can also integrate with OpenAI or other chat models). The raw image data cre"}, {"role": "assistant", "content": "\n**Analyse du besoin**: This n8n template demonstrates how to use AI to generate custom images from scratch - fully automated, prompt-driven, and ready to deploy at scale.\n\nUse cases are many: You can use it for marketing vi...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 11 nodes utilisant ai, google, http.\nStructure: code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"cmncRJ2rlecEwZxU\",\"meta\":{\"instanceId\":\"ed6d846a2fce1f660ede2e7da800724cca01dc3d0685524a3c917881b7cfcfe9\"},\"name\":\"[Agent Circle's N8N Workflow] Automated AI Image Creator\",\"tags\":[],\"nodes\":[{\"id\":\"d5d1fe1b-f053-4162-adf4-5b52b409942d\",\"name\":\"Fields - Set Values\",\"type\":\"n8n-nodes-base.set\",\"position\":[240,100],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"4e04fec4-441e-45f7-acea-0017a4b5c104\",\"name\":\"model\",\"type\":\"string\",\"value\":\"flux\"},{\"id\":\"aa80cd68-1c82-4032-b1d7-e098856eec38\",\"name\":\"width\",\"type\":\"string\",\"value\":\"1080\"},{\"id\":\"da6d305f-aece-49bd-ae02-52df59915c60\",\"name\":\"height\",\"type\":\"string\",\"value\":\"1920\"}]}},\"typeVersion\":3.4},{\"id\":\"e108c56f-b7fb-4818-aed5-c55c59b81516\",\"name\":\"When chat message received\",\"type\":\"@n8n/n8n-nodes-langchain.chatTrigger\",\"position\":[20,200],\"webhookId\":\"5b347b5d-8f35-45b3-a499-de95153088f0\",\"parameters\":{\"options\":{}},\"typeVersion\":1.1},{\"id\":\"7565ff7c-cfe7-4157-953b-74c1e66d659e\",\"name\":\"Code - Clean Json\",\"type\":\"n8n-nodes-base.code\",\"position\":[980,100],\"parameters\":{\"jsCode\":\"function cleanAndExtractJSON(response) {\\n try {\\n const result = {\\n image_prompt: []\\n };\\n\\n const lines = response.split('\\\\n');\\n let currentPrompt = '';\\n\\n for (const line of lines) {\\n if (line.includes('\\\"prompt\\\":')) {\\n if (currentPrompt) {\\n result.image_prompt.push(currentPrompt.trim());\\n }\\n currentPrompt = line.split('\\\"prompt\\\":')[1].trim();\\n }\\n }\\n\\n if (currentPrompt) {\\n result.image_prompt.push(currentPrompt.trim());\\n }\\n\\n return { json: result };\\n \\n } catch (error) {\\n return { \\n json: {\\n image_prompt: []\\n }\\n };\\n }\\n}\\n\\nconst response = $input.first().json.output;\\nreturn cleanAndExtractJSON(response);\"},\"executeOnce\":false,\"typeVersion\":2,\"alwaysOutputData\":true},{\"id\":\"8e33813d-bd34-46b9-91c8-89dac7f28add\",\"name\":\"Code - Get Prompt\",\"type\":\"n8n-nodes-base.code\",\"position\":[1160,100],\"parameters\":{\"jsCode\":\"return $input.first().json.image_prompt.map(prompt => ({\\n json: {\\n body: {\\n prompt: prompt,\\n \\\"image_size\\\": {\\n \\\"width\\\": $('Fields - Set Values').first().json.width,\\n \\\"height\\\": $('Fields - Set Values').first().json.height\\n },\\n \\\"num_inference_steps\\\": 12,\\n \\\"guidance_scale\\\": 3.5,\\n \\\"num_images\\\": 1,\\n \\\"enable_safety_checker\\\": true,\\n}\\n }\\n }\\n));\"},\"typeVersion\":2,\"alwaysOutputData\":true},{\"id\":\"fba88baa-70e8-452c-b44e-d1685df0eb7d\",\"name\":\"HTTP Request - Create Image\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1600,100],\"parameters\":{\"url\":\"=https://image.pollinations.ai/prompt/ {{ $('Code - Get Prompt').item.json.body.prompt }}\",\"options\":{},\"jsonQuery\":\"={\\n \\\"width\\\": {{ $('Fields - Set Values').item.json.width }},\\n \\\"height\\\": {{ $('Fields - Set Values').item.json.height }},\\n \\\"model\\\": \\\"{{ $('Fields - Set Values').item.json.model }}\\\",\\n \\\"seed\\\": 42,\\n \\\"nologo\\\": true\\n}\",\"sendQuery\":true,\"sendHeaders\":true,\"specifyQuery\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"Content-Type\",\"value\":\"application/json\"},{\"name\":\"Accept\",\"value\":\"application/json\"}]}},\"retryOnFail\":true,\"typeVersion\":4.2,\"alwaysOutputData\":true,\"waitBetweenTries\":5000},{\"id\":\"25617f21-8d05-4ca2-9c16-5cd97e369bdb\",\"name\":\"Telegram Trigger\",\"type\":\"n8n-nodes-base.telegramTrigger\",\"disabled\":true,\"position\":[20,0],\"webhookId\":\"ff17baeb-3182-41c4-b60a-e6159b02023b\",\"parameters\":{\"updates\":[\"message\"],\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"de666684-e743-40ef-b604-1cff33b107de\",\"name\":\"Code - Set Filename\",\"type\":\"n8n-nodes-base.code\",\"position\":[1320,100],\"parameters\":{\"jsCode\":\"for (let i = 0; i < items.length; i++) {\\n items[i].json.fileName = `images_${(i + 1).toString().padStart(3, '0')}.png`;\\n}\\nreturn items;\"},\"typeVersion\":2},{\"id\":\"e04c2a46-a670-4042-88d1-79207731c864\",\"name\":\"Google Gemini Chat Model\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatGoogleGemini\",\"position\":[540,300],\"parameters\":{\"options\":{\"topK\":40,\"topP\":1,\"temperature\":0.5,\"safetySettings\":{\"values\":[{\"category\":\"HARM_CATEGORY_HARASSMENT\",\"threshold\":\"BLOCK_NONE\"},{\"category\":\"HARM_CATEGORY_HATE_SPEECH\",\"threshold\":\"BLOCK_NONE\"},{\"category\":\"HARM_CATEGORY_SEXUALLY_EXPLICIT\",\"threshold\":\"BLOCK_NONE\"},{\"category\":\"HARM_CATEGORY_DANGEROUS_CONTENT\",\"threshold\":\"BLOCK_NONE\"}]},\"maxOutputTokens\":65536},\"modelName\":\"models/gemini-2.0-flash\"},\"typeVersion\":1},{\"id\":\"3a150703-2a7f-4255-9da0-6a15c005290c\",\"name\":\"AI Agent - Create Image From Prompt\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[540,100],\"parameters\":{\"text\":\"={{ $('When chat message received').item.json.chatInput }}\",\"options\":{\"systemMessage\":\"=You are an AI image‑prompt creation expert. Please create a post using the following JSON format:\\nAI Image Generation Prompt Guidelines:\\nObjective\\nCreate highly realistic, high‐quality images\\nEnsure the image content faithfully conveys the spirit of the original text\\nIntegrate short text (10–20 characters) naturally into the image\\nMaintain consistency and professionalism\\n\\nStandard Prompt Structure\\n[Main Scene] | [Key Elements] | [Text Integration] | [Lighting & Atmosphere] | [Technical Parameters] | [Style Parameters]\\n\\nComponent Breakdown\\n1. Main Scene (Weight ::8)\\nDescribe the primary setting in line with the content.\\nExamples:\\nTech news: “modern tech office setting, minimalist workspace”\\nEconomy news: “professional financial district, corporate environment”\\nEducation news: “modern classroom, advanced learning environment”\\n\\n2. Key Elements (Weight ::8)\\nList the main visual elements required.\\nExamples:\\n“large HD display showing text ‘AI Ethics’ in modern typography”\\n“professional people in business attire discussing around interactive screen”\\n“detailed infographic elements floating in augmented reality style”\\n\\n3. Text Integration (Weight ::7)\\nHow to display text within the image:\\ntext elements | elegant typography, clear readable text, integrated naturally into scene ::7\\n\\n4. Lighting & Atmosphere (Weight ::7)\\nlighting | cinematic dramatic lighting, natural ambient light, professional studio setup ::7\\nbackground | depth of field blur, clean professional environment ::6\\n\\n5. Technical Parameters\\nparameters | 8k resolution, hyperrealistic, photorealistic quality, octane render, cinematic composition --ar 16:9\\nsettings | sharp focus, high detail, professional photography --s 1000 --q 2\\nComplete Examples\\nExample 1: AI Ethics News\\nprofessional tech conference room | large display showing \\\"AI Ethics Now\\\" in modern typography, group of diverse executives in discussion ::8 | clean modern workspace, glass walls, tech atmosphere ::7 | cinematic lighting, natural window light ::7 | 8k resolution, hyperrealistic quality, octane render --ar 16:9 --s 1000 --q 2\\nExample 2: Financial Market News\\nmodern stock exchange environment | giant LED wall showing \\\"Market Alert\\\" in bold typography, professional traders in action ::8 | dynamic financial data visualization, sleek modern interior ::7 | dramatic lighting, blue-tinted atmosphere ::7 | 8k resolution, photorealistic quality --ar 16:9 --s 1000 --q 2\\n\\nAdditional Parameters\\n--chaos [0–100]: Adjust randomness\\n--stylize [0–1000]: Degree of stylization\\n--seed [number]: Ensure consistency across generations\\n--niji: Optimized for Asian‐style aesthetics\\n--v 5.2: Use the latest model version\\n\\nImportant Notes\\nText in Image\\nKeep it short and legible\\nUse professional fonts\\nIntegrate naturally into the scene\\n\\nComposition\\nFollow the rule of thirds\\nEnsure a clear focal point\\nBalance text and imagery\\n\\nColor\\nMatch a professional tone\\nProvide sufficient contrast for readability\\nMaintain visual consistency\\n\\nTechnical Details\\nAlways use high resolution (8k)\\nEnsure professional lighting\\nOptimize for sharpness and detail\\n\\nCommon Pitfalls to Avoid\\nOverly generic prompts\\nMissing text‐integration guidance\\nFailing to specify composition rules\\nOmitting key technical parameters\\n\\nThe structure is:\\n{\\n prompt_image {prompt : \\\"\\\" , ...}\\n}\"},\"promptType\":\"define\",\"hasOutputParser\":true},\"typeVersion\":1.7},{\"id\":\"a3e5fa40-51c1-41fa-83cb-d6d598f1ff49\",\"name\":\"Telegram Response\",\"type\":\"n8n-nodes-base.telegram\",\"disabled\":true,\"position\":[1820,0],\"webhookId\":\"ca4806ac-202c-4709-92f9-6484397c17c4\",\"parameters\":{\"operation\":\"sendPhoto\",\"binaryData\":true,\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"f7059ea5-106b-4b73-8cb3-b0e10e1c0c13\",\"name\":\"Save Image To Disk\",\"type\":\"n8n-nodes-base.readWriteFile\",\"disabled\":true,\"position\":[1820,200],\"parameters\":{\"options\":{},\"fileName\":\"=/files/{{ $('Code').item.json.fileName }}\",\"operation\":\"write\"},\"typeVersion\":1}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Telegram Trigger\":{\"main\":[[{\"node\":\"Fields - Set Values\",\"type\":\"main\",\"index\":0}]]},\"Code - Clean Json\":{\"main\":[[{\"node\":\"Code - Get Prompt\",\"type\":\"main\",\"index\":0}]]},\"Code - Get Prompt\":{\"main\":[[{\"node\":\"Code - Set Filename\",\"type\":\"main\",\"index\":0}]]},\"Code - Set Filename\":{\"main\":[[{\"node\":\"HTTP Request - Create Image\",\"type\":\"main\",\"index\":0}]]},\"Fields - Set Values\":{\"main\":[[{\"node\":\"AI Agent - Create Image From Prompt\",\"type\":\"main\",\"index\":0}]]},\"Google Gemini Chat Model\":{\"ai_languageModel\":[[{\"node\":\"AI Agent - Create Image From Prompt\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"When chat message received\":{\"main\":[[{\"node\":\"Fields - Set Values\",\"type\":\"main\",\"index\":0}]]},\"HTTP Request - Create Image\":{\"main\":[[{\"node\":\"Save Image To Disk\",\"type\":\"main\",\"index\":0},{\"node\":\"Telegram Response\",\"type\":\"main\",\"index\":0}]]},\"AI Agent - Create Image From Prompt\":{\"main\":[[{\"node\":\"Code - Clean Json\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 11, "node_types": {"set": 1, "chatTrigger": 1, "code": 3, "httpRequest": 1, "telegramTrigger": 1, "lmChatGoogleGemini": 1, "agent": 1, "telegram": 1, "readWriteFile": 1}, "services": ["ai", "google", "http"], "complexity": "medium", "has_conditions": false, "has_loops": false, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Free AI Image Generator - n8n Automation Workflow with Gemini/ChatGPT"}, {"role": "assistant", "content": "\n**Analyse du besoin**: This n8n template demonstrates how to use AI to generate custom images from scratch - fully automated, prompt-driven, and ready to deploy at scale.\n\nUse cases are many: You can use it for marketing vi...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 11 nodes utilisant ai, google, http.\nStructure: code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"cmncRJ2rlecEwZxU\",\"meta\":{\"instanceId\":\"ed6d846a2fce1f660ede2e7da800724cca01dc3d0685524a3c917881b7cfcfe9\"},\"name\":\"[Agent Circle's N8N Workflow] Automated AI Image Creator\",\"tags\":[],\"nodes\":[{\"id\":\"d5d1fe1b-f053-4162-adf4-5b52b409942d\",\"name\":\"Fields - Set Values\",\"type\":\"n8n-nodes-base.set\",\"position\":[240,100],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"4e04fec4-441e-45f7-acea-0017a4b5c104\",\"name\":\"model\",\"type\":\"string\",\"value\":\"flux\"},{\"id\":\"aa80cd68-1c82-4032-b1d7-e098856eec38\",\"name\":\"width\",\"type\":\"string\",\"value\":\"1080\"},{\"id\":\"da6d305f-aece-49bd-ae02-52df59915c60\",\"name\":\"height\",\"type\":\"string\",\"value\":\"1920\"}]}},\"typeVersion\":3.4},{\"id\":\"e108c56f-b7fb-4818-aed5-c55c59b81516\",\"name\":\"When chat message received\",\"type\":\"@n8n/n8n-nodes-langchain.chatTrigger\",\"position\":[20,200],\"webhookId\":\"5b347b5d-8f35-45b3-a499-de95153088f0\",\"parameters\":{\"options\":{}},\"typeVersion\":1.1},{\"id\":\"7565ff7c-cfe7-4157-953b-74c1e66d659e\",\"name\":\"Code - Clean Json\",\"type\":\"n8n-nodes-base.code\",\"position\":[980,100],\"parameters\":{\"jsCode\":\"function cleanAndExtractJSON(response) {\\n try {\\n const result = {\\n image_prompt: []\\n };\\n\\n const lines = response.split('\\\\n');\\n let currentPrompt = '';\\n\\n for (const line of lines) {\\n if (line.includes('\\\"prompt\\\":')) {\\n if (currentPrompt) {\\n result.image_prompt.push(currentPrompt.trim());\\n }\\n currentPrompt = line.split('\\\"prompt\\\":')[1].trim();\\n }\\n }\\n\\n if (currentPrompt) {\\n result.image_prompt.push(currentPrompt.trim());\\n }\\n\\n return { json: result };\\n \\n } catch (error) {\\n return { \\n json: {\\n image_prompt: []\\n }\\n };\\n }\\n}\\n\\nconst response = $input.first().json.output;\\nreturn cleanAndExtractJSON(response);\"},\"executeOnce\":false,\"typeVersion\":2,\"alwaysOutputData\":true},{\"id\":\"8e33813d-bd34-46b9-91c8-89dac7f28add\",\"name\":\"Code - Get Prompt\",\"type\":\"n8n-nodes-base.code\",\"position\":[1160,100],\"parameters\":{\"jsCode\":\"return $input.first().json.image_prompt.map(prompt => ({\\n json: {\\n body: {\\n prompt: prompt,\\n \\\"image_size\\\": {\\n \\\"width\\\": $('Fields - Set Values').first().json.width,\\n \\\"height\\\": $('Fields - Set Values').first().json.height\\n },\\n \\\"num_inference_steps\\\": 12,\\n \\\"guidance_scale\\\": 3.5,\\n \\\"num_images\\\": 1,\\n \\\"enable_safety_checker\\\": true,\\n}\\n }\\n }\\n));\"},\"typeVersion\":2,\"alwaysOutputData\":true},{\"id\":\"fba88baa-70e8-452c-b44e-d1685df0eb7d\",\"name\":\"HTTP Request - Create Image\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1600,100],\"parameters\":{\"url\":\"=https://image.pollinations.ai/prompt/ {{ $('Code - Get Prompt').item.json.body.prompt }}\",\"options\":{},\"jsonQuery\":\"={\\n \\\"width\\\": {{ $('Fields - Set Values').item.json.width }},\\n \\\"height\\\": {{ $('Fields - Set Values').item.json.height }},\\n \\\"model\\\": \\\"{{ $('Fields - Set Values').item.json.model }}\\\",\\n \\\"seed\\\": 42,\\n \\\"nologo\\\": true\\n}\",\"sendQuery\":true,\"sendHeaders\":true,\"specifyQuery\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"Content-Type\",\"value\":\"application/json\"},{\"name\":\"Accept\",\"value\":\"application/json\"}]}},\"retryOnFail\":true,\"typeVersion\":4.2,\"alwaysOutputData\":true,\"waitBetweenTries\":5000},{\"id\":\"25617f21-8d05-4ca2-9c16-5cd97e369bdb\",\"name\":\"Telegram Trigger\",\"type\":\"n8n-nodes-base.telegramTrigger\",\"disabled\":true,\"position\":[20,0],\"webhookId\":\"ff17baeb-3182-41c4-b60a-e6159b02023b\",\"parameters\":{\"updates\":[\"message\"],\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"de666684-e743-40ef-b604-1cff33b107de\",\"name\":\"Code - Set Filename\",\"type\":\"n8n-nodes-base.code\",\"position\":[1320,100],\"parameters\":{\"jsCode\":\"for (let i = 0; i < items.length; i++) {\\n items[i].json.fileName = `images_${(i + 1).toString().padStart(3, '0')}.png`;\\n}\\nreturn items;\"},\"typeVersion\":2},{\"id\":\"e04c2a46-a670-4042-88d1-79207731c864\",\"name\":\"Google Gemini Chat Model\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatGoogleGemini\",\"position\":[540,300],\"parameters\":{\"options\":{\"topK\":40,\"topP\":1,\"temperature\":0.5,\"safetySettings\":{\"values\":[{\"category\":\"HARM_CATEGORY_HARASSMENT\",\"threshold\":\"BLOCK_NONE\"},{\"category\":\"HARM_CATEGORY_HATE_SPEECH\",\"threshold\":\"BLOCK_NONE\"},{\"category\":\"HARM_CATEGORY_SEXUALLY_EXPLICIT\",\"threshold\":\"BLOCK_NONE\"},{\"category\":\"HARM_CATEGORY_DANGEROUS_CONTENT\",\"threshold\":\"BLOCK_NONE\"}]},\"maxOutputTokens\":65536},\"modelName\":\"models/gemini-2.0-flash\"},\"typeVersion\":1},{\"id\":\"3a150703-2a7f-4255-9da0-6a15c005290c\",\"name\":\"AI Agent - Create Image From Prompt\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[540,100],\"parameters\":{\"text\":\"={{ $('When chat message received').item.json.chatInput }}\",\"options\":{\"systemMessage\":\"=You are an AI image‑prompt creation expert. Please create a post using the following JSON format:\\nAI Image Generation Prompt Guidelines:\\nObjective\\nCreate highly realistic, high‐quality images\\nEnsure the image content faithfully conveys the spirit of the original text\\nIntegrate short text (10–20 characters) naturally into the image\\nMaintain consistency and professionalism\\n\\nStandard Prompt Structure\\n[Main Scene] | [Key Elements] | [Text Integration] | [Lighting & Atmosphere] | [Technical Parameters] | [Style Parameters]\\n\\nComponent Breakdown\\n1. Main Scene (Weight ::8)\\nDescribe the primary setting in line with the content.\\nExamples:\\nTech news: “modern tech office setting, minimalist workspace”\\nEconomy news: “professional financial district, corporate environment”\\nEducation news: “modern classroom, advanced learning environment”\\n\\n2. Key Elements (Weight ::8)\\nList the main visual elements required.\\nExamples:\\n“large HD display showing text ‘AI Ethics’ in modern typography”\\n“professional people in business attire discussing around interactive screen”\\n“detailed infographic elements floating in augmented reality style”\\n\\n3. Text Integration (Weight ::7)\\nHow to display text within the image:\\ntext elements | elegant typography, clear readable text, integrated naturally into scene ::7\\n\\n4. Lighting & Atmosphere (Weight ::7)\\nlighting | cinematic dramatic lighting, natural ambient light, professional studio setup ::7\\nbackground | depth of field blur, clean professional environment ::6\\n\\n5. Technical Parameters\\nparameters | 8k resolution, hyperrealistic, photorealistic quality, octane render, cinematic composition --ar 16:9\\nsettings | sharp focus, high detail, professional photography --s 1000 --q 2\\nComplete Examples\\nExample 1: AI Ethics News\\nprofessional tech conference room | large display showing \\\"AI Ethics Now\\\" in modern typography, group of diverse executives in discussion ::8 | clean modern workspace, glass walls, tech atmosphere ::7 | cinematic lighting, natural window light ::7 | 8k resolution, hyperrealistic quality, octane render --ar 16:9 --s 1000 --q 2\\nExample 2: Financial Market News\\nmodern stock exchange environment | giant LED wall showing \\\"Market Alert\\\" in bold typography, professional traders in action ::8 | dynamic financial data visualization, sleek modern interior ::7 | dramatic lighting, blue-tinted atmosphere ::7 | 8k resolution, photorealistic quality --ar 16:9 --s 1000 --q 2\\n\\nAdditional Parameters\\n--chaos [0–100]: Adjust randomness\\n--stylize [0–1000]: Degree of stylization\\n--seed [number]: Ensure consistency across generations\\n--niji: Optimized for Asian‐style aesthetics\\n--v 5.2: Use the latest model version\\n\\nImportant Notes\\nText in Image\\nKeep it short and legible\\nUse professional fonts\\nIntegrate naturally into the scene\\n\\nComposition\\nFollow the rule of thirds\\nEnsure a clear focal point\\nBalance text and imagery\\n\\nColor\\nMatch a professional tone\\nProvide sufficient contrast for readability\\nMaintain visual consistency\\n\\nTechnical Details\\nAlways use high resolution (8k)\\nEnsure professional lighting\\nOptimize for sharpness and detail\\n\\nCommon Pitfalls to Avoid\\nOverly generic prompts\\nMissing text‐integration guidance\\nFailing to specify composition rules\\nOmitting key technical parameters\\n\\nThe structure is:\\n{\\n prompt_image {prompt : \\\"\\\" , ...}\\n}\"},\"promptType\":\"define\",\"hasOutputParser\":true},\"typeVersion\":1.7},{\"id\":\"a3e5fa40-51c1-41fa-83cb-d6d598f1ff49\",\"name\":\"Telegram Response\",\"type\":\"n8n-nodes-base.telegram\",\"disabled\":true,\"position\":[1820,0],\"webhookId\":\"ca4806ac-202c-4709-92f9-6484397c17c4\",\"parameters\":{\"operation\":\"sendPhoto\",\"binaryData\":true,\"additionalFields\":{}},\"typeVersion\":1.2},{\"id\":\"f7059ea5-106b-4b73-8cb3-b0e10e1c0c13\",\"name\":\"Save Image To Disk\",\"type\":\"n8n-nodes-base.readWriteFile\",\"disabled\":true,\"position\":[1820,200],\"parameters\":{\"options\":{},\"fileName\":\"=/files/{{ $('Code').item.json.fileName }}\",\"operation\":\"write\"},\"typeVersion\":1}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Telegram Trigger\":{\"main\":[[{\"node\":\"Fields - Set Values\",\"type\":\"main\",\"index\":0}]]},\"Code - Clean Json\":{\"main\":[[{\"node\":\"Code - Get Prompt\",\"type\":\"main\",\"index\":0}]]},\"Code - Get Prompt\":{\"main\":[[{\"node\":\"Code - Set Filename\",\"type\":\"main\",\"index\":0}]]},\"Code - Set Filename\":{\"main\":[[{\"node\":\"HTTP Request - Create Image\",\"type\":\"main\",\"index\":0}]]},\"Fields - Set Values\":{\"main\":[[{\"node\":\"AI Agent - Create Image From Prompt\",\"type\":\"main\",\"index\":0}]]},\"Google Gemini Chat Model\":{\"ai_languageModel\":[[{\"node\":\"AI Agent - Create Image From Prompt\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"When chat message received\":{\"main\":[[{\"node\":\"Fields - Set Values\",\"type\":\"main\",\"index\":0}]]},\"HTTP Request - Create Image\":{\"main\":[[{\"node\":\"Save Image To Disk\",\"type\":\"main\",\"index\":0},{\"node\":\"Telegram Response\",\"type\":\"main\",\"index\":0}]]},\"AI Agent - Create Image From Prompt\":{\"main\":[[{\"node\":\"Code - Clean Json\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 11, "node_types": {"set": 1, "chatTrigger": 1, "code": 3, "httpRequest": 1, "telegramTrigger": 1, "lmChatGoogleGemini": 1, "agent": 1, "telegram": 1, "readWriteFile": 1}, "services": ["ai", "google", "http"], "complexity": "medium", "has_conditions": false, "has_loops": false, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: Community Node Disclaimer: This workflow uses KlickTipp community nodes. Introduction This workflow automates Stripe checkout confirmations by capturing transaction data and syncing it into KlickTipp. Upon successful checkout, the contact's data is enriched with purchase details and tagged to trigger a personalized confirmation campaign in KlickTipp. Perfect for digital product sellers, course creators, and service providers seeking an end-to-end automated sales confirmation process. Benefits Instant confirmation emails: Automatically notify customers upon successful checkout—no manual processing needed. Structured contact data: Order data (invoice link, amount, transaction ID, products) is stored in KlickTipp custom fields. Smart campaign triggering: Assign dynamic tags to start automated"}, {"role": "assistant", "content": "\n**Analyse du besoin**: Community Node Disclaimer: This workflow uses KlickTipp community nodes.\n\nIntroduction\n\nThis workflow automates Stripe checkout confirmations by capturing transaction data and syncing it into KlickTip...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 5 nodes utilisant http.\nStructure: flux standard.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"meta\":{\"instanceId\":\"95b3ab5a70ab1c8c1906357a367f1b236ef12a1409406fd992f60255f0f95f85\",\"templateCredsSetupCompleted\":true},\"nodes\":[{\"id\":\"e19bea0c-f8d7-49f2-8b6f-a13bed1c465d\",\"name\":\"Subscribe buyer to KlickTipp\",\"type\":\"CUSTOM.klicktipp\",\"notes\":\"Subscribes the buyer to the KlickTipp list using their payment data.\",\"position\":[208,-176],\"parameters\":{\"email\":\"={{ $json.billing_details.email }}\",\"tagId\":\"13201265\",\"fields\":{\"dataFields\":[{\"fieldId\":\"field219541\",\"fieldValue\":\"={{ $json.amount }}\"},{\"fieldId\":\"field220266\",\"fieldValue\":\"={{ $json.receipt_url }}\"},{\"fieldId\":\"field219542\",\"fieldValue\":\"={{ $('New checkout session completed').item.json.data.object.id }}\"},{\"fieldId\":\"fieldFirstName\",\"fieldValue\":\"={{ \\n // Access the full name string from the JSON input\\n $json.billing_details.name\\n \\n // Remove any leading/trailing whitespace\\n ?.trim()\\n \\n // Split the name string into an array using one or more whitespace characters (handles multiple spaces)\\n .split(/\\\\s+/)\\n \\n // Select the first word from the array (typically the first name)\\n [0] \\n}}\\n\"},{\"fieldId\":\"fieldLastName\",\"fieldValue\":\"={{ \\n // Access the full name from the input JSON\\n $json.billing_details.name\\n\\n // Remove any leading/trailing whitespace\\n ?.trim()\\n\\n // Split the string into an array of words using any whitespace\\n .split(/\\\\s+/)\\n\\n // Get the last word in the array — typically the last name\\n .at(-1) \\n}}\"},{\"fieldId\":\"field219540\",\"fieldValue\":\"={{ $('Getting line items').item.json.data.map(item => item.description) }}\\n\"}]},\"listId\":\"358895\",\"resource\":\"subscriber\",\"operation\":\"subscribe\"},\"notesInFlow\":true,\"typeVersion\":2},{\"id\":\"26f6a896-68ce-491f-9e7e-92a667aff2a5\",\"name\":\"Getting invoice link\",\"type\":\"n8n-nodes-base.stripe\",\"notes\":\"This node gets the details from the payment in order to identify the line items and amount of the payment.\",\"position\":[-64,-176],\"parameters\":{\"chargeId\":\"={{ $json.latest_charge }}\",\"resource\":\"charge\"},\"notesInFlow\":true,\"typeVersion\":1},{\"id\":\"d16814e5-7255-4da3-ac0c-64b80e4fc72c\",\"name\":\"Getting charge ID\",\"type\":\"n8n-nodes-base.httpRequest\",\"notes\":\"This node gets the charge ID from the checkout completion in order to be able to fetch the receipt url.\",\"position\":[-288,-176],\"parameters\":{\"url\":\"=https://api.stripe.com/v1/payment_intents/{{ $('New checkout session completed').item.json.data.object.payment_intent }}\",\"options\":{},\"sendHeaders\":true,\"headerParameters\":{\"parameters\":[{\"name\":\"authorization\",\"value\":\"Basic \"}]}},\"notesInFlow\":true,\"typeVersion\":4.2},{\"id\":\"815f0790-be2c-455f-a3ad-02b2b118a3ff\",\"name\":\"Getting line items\",\"type\":\"n8n-nodes-base.httpRequest\",\"notes\":\"This node gets the line items from the checkout session.\",\"position\":[-480,-176],\"parameters\":{\"url\":\"=https://api.stripe.com/v1/checkout/sessions/{{ $json.data.object.id }}/line_items\",\"options\":{},\"sendHeaders\":true,\"headerParameters\":{\"parameters\":[{\"name\":\"Stripe-Version\",\"value\":\"2025-05-28.basil\"},{\"name\":\"authorization\",\"value\":\"Basic \"}]}},\"notesInFlow\":true,\"typeVersion\":4.2},{\"id\":\"e719d079-0065-44a2-a2c1-c59ded09b388\",\"name\":\"New checkout session completed\",\"type\":\"n8n-nodes-base.stripeTrigger\",\"notes\":\"This trigger listens to successful checkout completions from Stripe.\",\"position\":[-704,-176],\"webhookId\":\"0d270008-d22c-486b-8ba1-e7d68b942512\",\"parameters\":{\"events\":[\"checkout.session.completed\"]},\"notesInFlow\":true,\"typeVersion\":1}],\"connections\":{\"Getting charge ID\":{\"main\":[[{\"node\":\"Getting invoice link\",\"type\":\"main\",\"index\":0}]]},\"Getting line items\":{\"main\":[[{\"node\":\"Getting charge ID\",\"type\":\"main\",\"index\":0}]]},\"Getting invoice link\":{\"main\":[[{\"node\":\"Subscribe buyer to KlickTipp\",\"type\":\"main\",\"index\":0}]]},\"New checkout session completed\":{\"main\":[[{\"node\":\"Getting line items\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 5, "node_types": {"klicktipp": 1, "stripe": 1, "httpRequest": 2, "stripeTrigger": 1}, "services": ["http"], "complexity": "simple", "has_conditions": false, "has_loops": false, "has_code": false, "has_ai": false}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Automated Stripe to KlickTipp: Send Purchase Confirmation Emails via Tagging"}, {"role": "assistant", "content": "\n**Analyse du besoin**: Community Node Disclaimer: This workflow uses KlickTipp community nodes.\n\nIntroduction\n\nThis workflow automates Stripe checkout confirmations by capturing transaction data and syncing it into KlickTip...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 5 nodes utilisant http.\nStructure: flux standard.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"meta\":{\"instanceId\":\"95b3ab5a70ab1c8c1906357a367f1b236ef12a1409406fd992f60255f0f95f85\",\"templateCredsSetupCompleted\":true},\"nodes\":[{\"id\":\"e19bea0c-f8d7-49f2-8b6f-a13bed1c465d\",\"name\":\"Subscribe buyer to KlickTipp\",\"type\":\"CUSTOM.klicktipp\",\"notes\":\"Subscribes the buyer to the KlickTipp list using their payment data.\",\"position\":[208,-176],\"parameters\":{\"email\":\"={{ $json.billing_details.email }}\",\"tagId\":\"13201265\",\"fields\":{\"dataFields\":[{\"fieldId\":\"field219541\",\"fieldValue\":\"={{ $json.amount }}\"},{\"fieldId\":\"field220266\",\"fieldValue\":\"={{ $json.receipt_url }}\"},{\"fieldId\":\"field219542\",\"fieldValue\":\"={{ $('New checkout session completed').item.json.data.object.id }}\"},{\"fieldId\":\"fieldFirstName\",\"fieldValue\":\"={{ \\n // Access the full name string from the JSON input\\n $json.billing_details.name\\n \\n // Remove any leading/trailing whitespace\\n ?.trim()\\n \\n // Split the name string into an array using one or more whitespace characters (handles multiple spaces)\\n .split(/\\\\s+/)\\n \\n // Select the first word from the array (typically the first name)\\n [0] \\n}}\\n\"},{\"fieldId\":\"fieldLastName\",\"fieldValue\":\"={{ \\n // Access the full name from the input JSON\\n $json.billing_details.name\\n\\n // Remove any leading/trailing whitespace\\n ?.trim()\\n\\n // Split the string into an array of words using any whitespace\\n .split(/\\\\s+/)\\n\\n // Get the last word in the array — typically the last name\\n .at(-1) \\n}}\"},{\"fieldId\":\"field219540\",\"fieldValue\":\"={{ $('Getting line items').item.json.data.map(item => item.description) }}\\n\"}]},\"listId\":\"358895\",\"resource\":\"subscriber\",\"operation\":\"subscribe\"},\"notesInFlow\":true,\"typeVersion\":2},{\"id\":\"26f6a896-68ce-491f-9e7e-92a667aff2a5\",\"name\":\"Getting invoice link\",\"type\":\"n8n-nodes-base.stripe\",\"notes\":\"This node gets the details from the payment in order to identify the line items and amount of the payment.\",\"position\":[-64,-176],\"parameters\":{\"chargeId\":\"={{ $json.latest_charge }}\",\"resource\":\"charge\"},\"notesInFlow\":true,\"typeVersion\":1},{\"id\":\"d16814e5-7255-4da3-ac0c-64b80e4fc72c\",\"name\":\"Getting charge ID\",\"type\":\"n8n-nodes-base.httpRequest\",\"notes\":\"This node gets the charge ID from the checkout completion in order to be able to fetch the receipt url.\",\"position\":[-288,-176],\"parameters\":{\"url\":\"=https://api.stripe.com/v1/payment_intents/{{ $('New checkout session completed').item.json.data.object.payment_intent }}\",\"options\":{},\"sendHeaders\":true,\"headerParameters\":{\"parameters\":[{\"name\":\"authorization\",\"value\":\"Basic \"}]}},\"notesInFlow\":true,\"typeVersion\":4.2},{\"id\":\"815f0790-be2c-455f-a3ad-02b2b118a3ff\",\"name\":\"Getting line items\",\"type\":\"n8n-nodes-base.httpRequest\",\"notes\":\"This node gets the line items from the checkout session.\",\"position\":[-480,-176],\"parameters\":{\"url\":\"=https://api.stripe.com/v1/checkout/sessions/{{ $json.data.object.id }}/line_items\",\"options\":{},\"sendHeaders\":true,\"headerParameters\":{\"parameters\":[{\"name\":\"Stripe-Version\",\"value\":\"2025-05-28.basil\"},{\"name\":\"authorization\",\"value\":\"Basic \"}]}},\"notesInFlow\":true,\"typeVersion\":4.2},{\"id\":\"e719d079-0065-44a2-a2c1-c59ded09b388\",\"name\":\"New checkout session completed\",\"type\":\"n8n-nodes-base.stripeTrigger\",\"notes\":\"This trigger listens to successful checkout completions from Stripe.\",\"position\":[-704,-176],\"webhookId\":\"0d270008-d22c-486b-8ba1-e7d68b942512\",\"parameters\":{\"events\":[\"checkout.session.completed\"]},\"notesInFlow\":true,\"typeVersion\":1}],\"connections\":{\"Getting charge ID\":{\"main\":[[{\"node\":\"Getting invoice link\",\"type\":\"main\",\"index\":0}]]},\"Getting line items\":{\"main\":[[{\"node\":\"Getting charge ID\",\"type\":\"main\",\"index\":0}]]},\"Getting invoice link\":{\"main\":[[{\"node\":\"Subscribe buyer to KlickTipp\",\"type\":\"main\",\"index\":0}]]},\"New checkout session completed\":{\"main\":[[{\"node\":\"Getting line items\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 5, "node_types": {"klicktipp": 1, "stripe": 1, "httpRequest": 2, "stripeTrigger": 1}, "services": ["http"], "complexity": "simple", "has_conditions": false, "has_loops": false, "has_code": false, "has_ai": false}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: How it works: This project creates a personal AI assistant named Angie that operates through Telegram. Angie can summarize daily emails, look up calendar entries, remind users of upcoming tasks, and retrieve contact information. The assistant can interact with users via both voice and text inputs. Step-by-step: Telegram Trigger: The workflow starts with a Telegram trigger that listens for incoming message events. The system determines if the incoming message is voice or text. If voice, the voice file is retrieved and transcribed to text using OpenAI's API Speech to Text AI Assistant: The telegram request is passed to the AI assistant (Angie). Tools Integration: The AI assistant is equipped with several tools: Get Email: Uses Gmail API to fetch recent emails, filtering by date. Get Calendar"}, {"role": "assistant", "content": "\n**Analyse du besoin**: How it works:\n\nThis project creates a personal AI assistant named Angie that operates through Telegram. Angie can summarize daily emails, look up calendar entries, remind users of upcoming tasks, and ...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 13 nodes utilisant ai, google, email.\nStructure: logique conditionnelle, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"meta\":{\"instanceId\":\"04ddf1130268840c229f501edc57936c3c131339e8b0cdd696fcf3a7c69e696e\",\"templateId\":\"2462\"},\"nodes\":[{\"id\":\"c70236ea-91ab-4e47-b6f6-63a70ede5d3c\",\"name\":\"Google Calendar\",\"type\":\"n8n-nodes-base.googleCalendarTool\",\"position\":[2000,704],\"parameters\":{\"options\":{\"fields\":\"=items(summary, start(dateTime))\",\"timeMin\":\"={{$fromAI(\\\"date\\\",\\\"the date after which to fetch the messages in format YYYY-MM-DDTHH:MM:SS\\\")}}\"},\"calendar\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"derekcheungsa@gmail.com\",\"cachedResultName\":\"derekcheungsa@gmail.com\"},\"operation\":\"getAll\"},\"typeVersion\":1.1},{\"id\":\"d2287bea-de47-4180-8ee6-55d4ab1a89da\",\"name\":\"Window Buffer Memory\",\"type\":\"@n8n/n8n-nodes-langchain.memoryBufferWindow\",\"position\":[1760,704],\"parameters\":{\"sessionKey\":\"={{ $('Listen for incoming events').first().json.message.from.id }}\",\"sessionIdType\":\"customKey\"},\"typeVersion\":1.2},{\"id\":\"fa955731-86f6-4e4d-8604-dab5f52dee87\",\"name\":\"Get Email\",\"type\":\"n8n-nodes-base.gmailTool\",\"position\":[1872,704],\"webhookId\":\"abf7e707-2eb8-4063-a920-b8ed975b0d70\",\"parameters\":{\"filters\":{\"labelIds\":[\"INBOX\",\"UNREAD\"],\"readStatus\":\"unread\",\"receivedAfter\":\"={{$fromAI(\\\"date\\\",\\\"the date after which to fetch the messages in format YYYY-MM-DDTHH:MM:SS\\\")}}\"},\"operation\":\"getAll\"},\"typeVersion\":2.1},{\"id\":\"46511f47-1687-4cbe-ae41-ceb205ed1f11\",\"name\":\"OpenAI Chat Model\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[1632,704],\"parameters\":{\"options\":{}},\"typeVersion\":1},{\"id\":\"64fe44db-af19-43eb-9ff1-de0a72a9e645\",\"name\":\"Listen for incoming events\",\"type\":\"n8n-nodes-base.telegramTrigger\",\"position\":[832,384],\"webhookId\":\"322dce18-f93e-4f86-b9b1-3305519b7834\",\"parameters\":{\"updates\":[\"message\"],\"additionalFields\":{}},\"typeVersion\":1},{\"id\":\"e35c04ff-a050-4564-8c1b-5b22b556872f\",\"name\":\"Telegram\",\"type\":\"n8n-nodes-base.telegram\",\"onError\":\"continueErrorOutput\",\"position\":[2272,384],\"webhookId\":\"e699405e-8e52-4d38-a06b-1fa8edf050bd\",\"parameters\":{\"text\":\"={{ $json.output }}\",\"chatId\":\"={{ $('Listen for incoming events').first().json.message.from.id }}\",\"additionalFields\":{\"parse_mode\":\"Markdown\",\"appendAttribution\":false}},\"typeVersion\":1.1},{\"id\":\"e791d4f8-2c19-4c14-a71e-39a04f22e944\",\"name\":\"If\",\"type\":\"n8n-nodes-base.if\",\"position\":[1200,384],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"a0bf9719-4272-46f6-ab3b-eda6f7b44fd8\",\"operator\":{\"type\":\"string\",\"operation\":\"empty\",\"singleValue\":true},\"leftValue\":\"={{ $json.message.text }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2},{\"id\":\"5bd1788a-3d08-4eb3-8e03-3ce82f44d2a7\",\"name\":\"Speech to Text\",\"type\":\"@n8n/n8n-nodes-langchain.openAi\",\"position\":[1616,384],\"parameters\":{\"options\":{},\"resource\":\"audio\",\"operation\":\"transcribe\"},\"typeVersion\":1.3},{\"id\":\"b67a2a93-517b-469e-aaa4-32c422710743\",\"name\":\"Voice or Text\",\"type\":\"n8n-nodes-base.set\",\"position\":[1040,384],\"parameters\":{\"fields\":{\"values\":[{\"name\":\"text\",\"stringValue\":\"={{ $json?.message?.text || \\\"\\\" }}\"}]},\"options\":{}},\"typeVersion\":3.2},{\"id\":\"8105c39f-9e87-44c4-9215-b3777f0b4164\",\"name\":\"Get Voice File\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[1376,384],\"webhookId\":\"24273e7e-6133-415e-8627-a9d6dc0f107c\",\"parameters\":{\"fileId\":\"={{ $('Listen for incoming events').item.json.message.voice.file_id }}\",\"resource\":\"file\",\"additionalFields\":{}},\"typeVersion\":1.1},{\"id\":\"759b975f-d17c-4386-a5b3-12413f0361f4\",\"name\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[1776,384],\"parameters\":{\"text\":\"={{ $json.text }}\",\"options\":{\"systemMessage\":\"=You are a helpful assistant.\\n\\nToday's date is {{ $now }}.\\n\\nGuidelines:\\n- When fetching emails, filter out any promotional emails. \\n- When summarizing emails, include Sender, Message date, subject, and brief summary of email.\\n- if the user did not specify a date in the request assume they are asking for today\\n- Use baserow tool to answer questions about tasks\\n- When answering questions about calendar events, filter out events that don't apply to the question. For example, the question is about events for today, only reply with events for today. Don't mention future events if it's more than 1 week away\"},\"promptType\":\"define\"},\"typeVersion\":1.6},{\"id\":\"40e92679-b47a-4213-bb23-3f8d086459f2\",\"name\":\"Tasks\",\"type\":\"n8n-nodes-base.baserowTool\",\"position\":[2112,704],\"parameters\":{\"tableId\":372174,\"databaseId\":146496,\"additionalOptions\":{}},\"typeVersion\":1},{\"id\":\"570a0647-b571-4ebc-9dfe-40244b5a0b2a\",\"name\":\"Contacts\",\"type\":\"n8n-nodes-base.baserowTool\",\"position\":[2240,704],\"parameters\":{\"tableId\":372177,\"databaseId\":146496,\"descriptionType\":\"manual\",\"toolDescription\":\"Useful for getting contact information. For example emails or phone numbers.\",\"additionalOptions\":{}},\"typeVersion\":1}],\"connections\":{\"If\":{\"main\":[[{\"node\":\"Get Voice File\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"main\",\"index\":0}]]},\"Tasks\":{\"ai_tool\":[[{\"node\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"ai_tool\",\"index\":0}]]},\"Contacts\":{\"ai_tool\":[[{\"node\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"ai_tool\",\"index\":0}]]},\"Get Email\":{\"ai_tool\":[[{\"node\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"ai_tool\",\"index\":0}]]},\"Voice or Text\":{\"main\":[[{\"node\":\"If\",\"type\":\"main\",\"index\":0}]]},\"Get Voice File\":{\"main\":[[{\"node\":\"Speech to Text\",\"type\":\"main\",\"index\":0}]]},\"Speech to Text\":{\"main\":[[{\"node\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"main\",\"index\":0}]]},\"Google Calendar\":{\"ai_tool\":[[{\"node\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"ai_tool\",\"index\":0}]]},\"OpenAI Chat Model\":{\"ai_languageModel\":[[{\"node\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Window Buffer Memory\":{\"ai_memory\":[[{\"node\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"ai_memory\",\"index\":0}]]},\"Listen for incoming events\":{\"main\":[[{\"node\":\"Voice or Text\",\"type\":\"main\",\"index\":0}]]},\"Angie, AI Assistant 👩🏻‍🏫\":{\"main\":[[{\"node\":\"Telegram\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 13, "node_types": {"googleCalendarTool": 1, "memoryBufferWindow": 1, "gmailTool": 1, "lmChatOpenAi": 1, "telegramTrigger": 1, "telegram": 2, "if": 1, "openAi": 1, "set": 1, "agent": 1, "baserowTool": 2}, "services": ["ai", "google", "email"], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": false, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Angie, Personal AI Assistant with Telegram Voice and Text"}, {"role": "assistant", "content": "\n**Analyse du besoin**: How it works:\n\nThis project creates a personal AI assistant named Angie that operates through Telegram. Angie can summarize daily emails, look up calendar entries, remind users of upcoming tasks, and ...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 13 nodes utilisant ai, google, email.\nStructure: logique conditionnelle, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"meta\":{\"instanceId\":\"04ddf1130268840c229f501edc57936c3c131339e8b0cdd696fcf3a7c69e696e\",\"templateId\":\"2462\"},\"nodes\":[{\"id\":\"c70236ea-91ab-4e47-b6f6-63a70ede5d3c\",\"name\":\"Google Calendar\",\"type\":\"n8n-nodes-base.googleCalendarTool\",\"position\":[2000,704],\"parameters\":{\"options\":{\"fields\":\"=items(summary, start(dateTime))\",\"timeMin\":\"={{$fromAI(\\\"date\\\",\\\"the date after which to fetch the messages in format YYYY-MM-DDTHH:MM:SS\\\")}}\"},\"calendar\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"derekcheungsa@gmail.com\",\"cachedResultName\":\"derekcheungsa@gmail.com\"},\"operation\":\"getAll\"},\"typeVersion\":1.1},{\"id\":\"d2287bea-de47-4180-8ee6-55d4ab1a89da\",\"name\":\"Window Buffer Memory\",\"type\":\"@n8n/n8n-nodes-langchain.memoryBufferWindow\",\"position\":[1760,704],\"parameters\":{\"sessionKey\":\"={{ $('Listen for incoming events').first().json.message.from.id }}\",\"sessionIdType\":\"customKey\"},\"typeVersion\":1.2},{\"id\":\"fa955731-86f6-4e4d-8604-dab5f52dee87\",\"name\":\"Get Email\",\"type\":\"n8n-nodes-base.gmailTool\",\"position\":[1872,704],\"webhookId\":\"abf7e707-2eb8-4063-a920-b8ed975b0d70\",\"parameters\":{\"filters\":{\"labelIds\":[\"INBOX\",\"UNREAD\"],\"readStatus\":\"unread\",\"receivedAfter\":\"={{$fromAI(\\\"date\\\",\\\"the date after which to fetch the messages in format YYYY-MM-DDTHH:MM:SS\\\")}}\"},\"operation\":\"getAll\"},\"typeVersion\":2.1},{\"id\":\"46511f47-1687-4cbe-ae41-ceb205ed1f11\",\"name\":\"OpenAI Chat Model\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[1632,704],\"parameters\":{\"options\":{}},\"typeVersion\":1},{\"id\":\"64fe44db-af19-43eb-9ff1-de0a72a9e645\",\"name\":\"Listen for incoming events\",\"type\":\"n8n-nodes-base.telegramTrigger\",\"position\":[832,384],\"webhookId\":\"322dce18-f93e-4f86-b9b1-3305519b7834\",\"parameters\":{\"updates\":[\"message\"],\"additionalFields\":{}},\"typeVersion\":1},{\"id\":\"e35c04ff-a050-4564-8c1b-5b22b556872f\",\"name\":\"Telegram\",\"type\":\"n8n-nodes-base.telegram\",\"onError\":\"continueErrorOutput\",\"position\":[2272,384],\"webhookId\":\"e699405e-8e52-4d38-a06b-1fa8edf050bd\",\"parameters\":{\"text\":\"={{ $json.output }}\",\"chatId\":\"={{ $('Listen for incoming events').first().json.message.from.id }}\",\"additionalFields\":{\"parse_mode\":\"Markdown\",\"appendAttribution\":false}},\"typeVersion\":1.1},{\"id\":\"e791d4f8-2c19-4c14-a71e-39a04f22e944\",\"name\":\"If\",\"type\":\"n8n-nodes-base.if\",\"position\":[1200,384],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"a0bf9719-4272-46f6-ab3b-eda6f7b44fd8\",\"operator\":{\"type\":\"string\",\"operation\":\"empty\",\"singleValue\":true},\"leftValue\":\"={{ $json.message.text }}\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2},{\"id\":\"5bd1788a-3d08-4eb3-8e03-3ce82f44d2a7\",\"name\":\"Speech to Text\",\"type\":\"@n8n/n8n-nodes-langchain.openAi\",\"position\":[1616,384],\"parameters\":{\"options\":{},\"resource\":\"audio\",\"operation\":\"transcribe\"},\"typeVersion\":1.3},{\"id\":\"b67a2a93-517b-469e-aaa4-32c422710743\",\"name\":\"Voice or Text\",\"type\":\"n8n-nodes-base.set\",\"position\":[1040,384],\"parameters\":{\"fields\":{\"values\":[{\"name\":\"text\",\"stringValue\":\"={{ $json?.message?.text || \\\"\\\" }}\"}]},\"options\":{}},\"typeVersion\":3.2},{\"id\":\"8105c39f-9e87-44c4-9215-b3777f0b4164\",\"name\":\"Get Voice File\",\"type\":\"n8n-nodes-base.telegram\",\"position\":[1376,384],\"webhookId\":\"24273e7e-6133-415e-8627-a9d6dc0f107c\",\"parameters\":{\"fileId\":\"={{ $('Listen for incoming events').item.json.message.voice.file_id }}\",\"resource\":\"file\",\"additionalFields\":{}},\"typeVersion\":1.1},{\"id\":\"759b975f-d17c-4386-a5b3-12413f0361f4\",\"name\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[1776,384],\"parameters\":{\"text\":\"={{ $json.text }}\",\"options\":{\"systemMessage\":\"=You are a helpful assistant.\\n\\nToday's date is {{ $now }}.\\n\\nGuidelines:\\n- When fetching emails, filter out any promotional emails. \\n- When summarizing emails, include Sender, Message date, subject, and brief summary of email.\\n- if the user did not specify a date in the request assume they are asking for today\\n- Use baserow tool to answer questions about tasks\\n- When answering questions about calendar events, filter out events that don't apply to the question. For example, the question is about events for today, only reply with events for today. Don't mention future events if it's more than 1 week away\"},\"promptType\":\"define\"},\"typeVersion\":1.6},{\"id\":\"40e92679-b47a-4213-bb23-3f8d086459f2\",\"name\":\"Tasks\",\"type\":\"n8n-nodes-base.baserowTool\",\"position\":[2112,704],\"parameters\":{\"tableId\":372174,\"databaseId\":146496,\"additionalOptions\":{}},\"typeVersion\":1},{\"id\":\"570a0647-b571-4ebc-9dfe-40244b5a0b2a\",\"name\":\"Contacts\",\"type\":\"n8n-nodes-base.baserowTool\",\"position\":[2240,704],\"parameters\":{\"tableId\":372177,\"databaseId\":146496,\"descriptionType\":\"manual\",\"toolDescription\":\"Useful for getting contact information. For example emails or phone numbers.\",\"additionalOptions\":{}},\"typeVersion\":1}],\"connections\":{\"If\":{\"main\":[[{\"node\":\"Get Voice File\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"main\",\"index\":0}]]},\"Tasks\":{\"ai_tool\":[[{\"node\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"ai_tool\",\"index\":0}]]},\"Contacts\":{\"ai_tool\":[[{\"node\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"ai_tool\",\"index\":0}]]},\"Get Email\":{\"ai_tool\":[[{\"node\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"ai_tool\",\"index\":0}]]},\"Voice or Text\":{\"main\":[[{\"node\":\"If\",\"type\":\"main\",\"index\":0}]]},\"Get Voice File\":{\"main\":[[{\"node\":\"Speech to Text\",\"type\":\"main\",\"index\":0}]]},\"Speech to Text\":{\"main\":[[{\"node\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"main\",\"index\":0}]]},\"Google Calendar\":{\"ai_tool\":[[{\"node\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"ai_tool\",\"index\":0}]]},\"OpenAI Chat Model\":{\"ai_languageModel\":[[{\"node\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Window Buffer Memory\":{\"ai_memory\":[[{\"node\":\"Angie, AI Assistant 👩🏻‍🏫\",\"type\":\"ai_memory\",\"index\":0}]]},\"Listen for incoming events\":{\"main\":[[{\"node\":\"Voice or Text\",\"type\":\"main\",\"index\":0}]]},\"Angie, AI Assistant 👩🏻‍🏫\":{\"main\":[[{\"node\":\"Telegram\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 13, "node_types": {"googleCalendarTool": 1, "memoryBufferWindow": 1, "gmailTool": 1, "lmChatOpenAi": 1, "telegramTrigger": 1, "telegram": 2, "if": 1, "openAi": 1, "set": 1, "agent": 1, "baserowTool": 2}, "services": ["ai", "google", "email"], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": false, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: Overview This automation template is designed to streamline your payment processing by automatically triggering upon a successful Stripe payment. The workflow retrieves the complete payment session and filters the information to display only the customer name, customer email, and the purchased product details. This template is perfect for quickly integrating Stripe transactions into your inventory management, CRM, or notification systems. Step-by-Step Setup Instructions Stripe Account Configuration: Ensure you have an active Stripe account. Connect your Stripe Credentials. Retrieve Product and Customer Data: Utilize Stripe’s API within the automation to fetch the purchased product details. Retrieve customer information such as: email and full name. Integration and Response: Map the retriev"}, {"role": "assistant", "content": "\n**Analyse du besoin**: Overview\n\nThis automation template is designed to streamline your payment processing by automatically triggering upon a successful Stripe payment. The workflow retrieves the complete payment session a...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 3 nodes utilisant http.\nStructure: flux standard.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"YVNJOltj0jMQatGz\",\"meta\":{\"instanceId\":\"143d2ab55c8bffb06f8b9c7ad30335764fdc48bbbacecbe2218dadb998a32213\",\"templateCredsSetupCompleted\":true},\"name\":\"Stripe Payment Order Sync – Auto Retrieve Customer & Product Purchased\",\"tags\":[],\"nodes\":[{\"id\":\"90322fe5-5536-41c3-ac08-ea87a856781b\",\"name\":\"Stripe Trigger on Payment Event\",\"type\":\"n8n-nodes-base.stripeTrigger\",\"position\":[0,0],\"webhookId\":\"e85ac894-bb67-436c-ad39-308a00c8e922\",\"parameters\":{\"events\":[\"checkout.session.completed\"]},\"typeVersion\":1},{\"id\":\"3feb0b03-921e-4bfd-8a50-b2b6b47e9497\",\"name\":\"Extract Session Information\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[300,0],\"parameters\":{\"url\":\"=https://api.stripe.com/v1/checkout/sessions/{{ $json.data.object.id }}\",\"options\":{},\"sendQuery\":true,\"authentication\":\"predefinedCredentialType\",\"queryParameters\":{\"parameters\":[{\"name\":\"expand[]\",\"value\":\"line_items\"}]},\"nodeCredentialType\":\"stripeApi\"},\"typeVersion\":4.2},{\"id\":\"5a436d1c-88e9-492e-8fe0-33a5706de1b3\",\"name\":\"Filter Information\",\"type\":\"n8n-nodes-base.set\",\"position\":[560,0],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"95a68e0f-b74c-4ca2-8143-14b469aa6bfb\",\"name\":\"Customer Name\",\"type\":\"string\",\"value\":\"={{ $json.customer_details.name }}\"},{\"id\":\"7634efa6-04f3-4dac-8509-56aae29fcc79\",\"name\":\"Customer Email\",\"type\":\"string\",\"value\":\"={{ $json.customer_details.email }}\"},{\"id\":\"10e71e07-6dd3-410c-a774-1eeffe2be7a5\",\"name\":\"Product Purchased\",\"type\":\"string\",\"value\":\"={{ $json.line_items.data[0].description }}\"}]}},\"typeVersion\":3.4}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Extract Session Information\":{\"main\":[[{\"node\":\"Filter Information\",\"type\":\"main\",\"index\":0}]]},\"Stripe Trigger on Payment Event\":{\"main\":[[{\"node\":\"Extract Session Information\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 3, "node_types": {"stripeTrigger": 1, "httpRequest": 1, "set": 1}, "services": ["http"], "complexity": "simple", "has_conditions": false, "has_loops": false, "has_code": false, "has_ai": false}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Stripe Payment Order Sync – Auto Retrieve Customer & Product Purchased"}, {"role": "assistant", "content": "\n**Analyse du besoin**: Overview\n\nThis automation template is designed to streamline your payment processing by automatically triggering upon a successful Stripe payment. The workflow retrieves the complete payment session a...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 3 nodes utilisant http.\nStructure: flux standard.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"YVNJOltj0jMQatGz\",\"meta\":{\"instanceId\":\"143d2ab55c8bffb06f8b9c7ad30335764fdc48bbbacecbe2218dadb998a32213\",\"templateCredsSetupCompleted\":true},\"name\":\"Stripe Payment Order Sync – Auto Retrieve Customer & Product Purchased\",\"tags\":[],\"nodes\":[{\"id\":\"90322fe5-5536-41c3-ac08-ea87a856781b\",\"name\":\"Stripe Trigger on Payment Event\",\"type\":\"n8n-nodes-base.stripeTrigger\",\"position\":[0,0],\"webhookId\":\"e85ac894-bb67-436c-ad39-308a00c8e922\",\"parameters\":{\"events\":[\"checkout.session.completed\"]},\"typeVersion\":1},{\"id\":\"3feb0b03-921e-4bfd-8a50-b2b6b47e9497\",\"name\":\"Extract Session Information\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[300,0],\"parameters\":{\"url\":\"=https://api.stripe.com/v1/checkout/sessions/{{ $json.data.object.id }}\",\"options\":{},\"sendQuery\":true,\"authentication\":\"predefinedCredentialType\",\"queryParameters\":{\"parameters\":[{\"name\":\"expand[]\",\"value\":\"line_items\"}]},\"nodeCredentialType\":\"stripeApi\"},\"typeVersion\":4.2},{\"id\":\"5a436d1c-88e9-492e-8fe0-33a5706de1b3\",\"name\":\"Filter Information\",\"type\":\"n8n-nodes-base.set\",\"position\":[560,0],\"parameters\":{\"options\":{},\"assignments\":{\"assignments\":[{\"id\":\"95a68e0f-b74c-4ca2-8143-14b469aa6bfb\",\"name\":\"Customer Name\",\"type\":\"string\",\"value\":\"={{ $json.customer_details.name }}\"},{\"id\":\"7634efa6-04f3-4dac-8509-56aae29fcc79\",\"name\":\"Customer Email\",\"type\":\"string\",\"value\":\"={{ $json.customer_details.email }}\"},{\"id\":\"10e71e07-6dd3-410c-a774-1eeffe2be7a5\",\"name\":\"Product Purchased\",\"type\":\"string\",\"value\":\"={{ $json.line_items.data[0].description }}\"}]}},\"typeVersion\":3.4}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Extract Session Information\":{\"main\":[[{\"node\":\"Filter Information\",\"type\":\"main\",\"index\":0}]]},\"Stripe Trigger on Payment Event\":{\"main\":[[{\"node\":\"Extract Session Information\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 3, "node_types": {"stripeTrigger": 1, "httpRequest": 1, "set": 1}, "services": ["http"], "complexity": "simple", "has_conditions": false, "has_loops": false, "has_code": false, "has_ai": false}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: Automate video creation with Veo3 and auto-post to Instagram, TikTok via Blotato Who is this for? This template is ideal for content creators, social media managers, YouTubers, and digital marketers who want to generate high-quality videos daily using AI and distribute them effortlessly across multiple platforms. It’s perfect for anyone who wants to scale short-form content creation without video editing tools. What problem is this workflow solving? Creating and distributing consistent video content requires: Generating ideas Writing scripts and prompts Rendering videos Manually posting to platforms This workflow automates all of that. It transforms one prompt into a professional AI-generated video and publishes it automatically — saving time and increasing reach. What this workflow does T"}, {"role": "assistant", "content": "\n**Analyse du besoin**: Automate video creation with Veo3 and auto-post to Instagram, TikTok via Blotato\nWho is this for?\n\nThis template is ideal for content creators, social media managers, YouTubers, and digital marketers ...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 26 nodes utilisant ai, google, http.\nStructure: intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"eFkkWqS5KdrxZ43P\",\"meta\":{\"instanceId\":\"a2b23892dd6989fda7c1209b381f5850373a7d2b85609624d7c2b7a092671d44\",\"templateCredsSetupCompleted\":true},\"name\":\"Automate video creation with Veo3 and auto-post to Instagram, TikTok via Blotato - vide\",\"tags\":[],\"nodes\":[{\"id\":\"45a5a9f4-fe6a-43a7-a032-c69750826209\",\"name\":\"Assign Social Media IDs\",\"type\":\"n8n-nodes-base.set\",\"position\":[420,1680],\"parameters\":{\"mode\":\"raw\",\"options\":{},\"jsonOutput\":\"{\\n \\\"instagram_id\\\": \\\"1111\\\",\\n \\\"youtube_id\\\": \\\"1111\\\",\\n \\\"threads_id\\\": \\\"1111\\\",\\n \\\"tiktok_id\\\": \\\"1111\\\",\\n \\\"facebook_id\\\": \\\"1111\\\",\\n \\\"facebook_page_id\\\": \\\"1111\\\",\\n \\\"twitter_id\\\": \\\"1111\\\",\\n \\\"linkedin_id\\\": \\\"1111\\\",\\n \\\"pinterest_id\\\": \\\"1111\\\",\\n \\\"pinterest_board_id\\\": \\\"1111\\\",\\n \\\"bluesky_id\\\": \\\"1111\\\"\\n}\\n\"},\"typeVersion\":3.4},{\"id\":\"6d125a85-b626-4981-8cfc-bcac4ea0ca89\",\"name\":\"Get my video\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[520,1440],\"parameters\":{\"options\":{},\"sheetName\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"=\"},\"documentId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"=\"}},\"typeVersion\":4.5},{\"id\":\"779818a1-97bd-4bf9-ba17-995c1439df6f\",\"name\":\"Upload Video to Blotato\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[640,1680],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/media\",\"method\":\"POST\",\"options\":{},\"sendBody\":true,\"sendHeaders\":true,\"bodyParameters\":{\"parameters\":[{\"name\":\"url\",\"value\":\"={{ $('Get my video').item.json['final_output'] }}\"}]},\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"113d635c-bf8f-4ed3-801e-de78b0df9437\",\"name\":\"INSTAGRAM\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[920,1440],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.instagram_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"instagram\\\"\\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"instagram\\\",\\n \\\"mediaUrls\\\": [\\n \\\"{{ $json.url }}\\\"\\n ]\\n }\\n }\\n}\\n\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"02aa72ee-e5b9-44ee-9cbf-e8ddbc259570\",\"name\":\"YOUTUBE\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1140,1440],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.youtube_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"youtube\\\",\\n \\\"title\\\": \\\"{{ $('Get my video').item.json.Titre }}\\\",\\n \\\"privacyStatus\\\": \\\"unlisted\\\",\\n \\\"shouldNotifySubscribers\\\": \\\"false\\\"\\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"youtube\\\",\\n \\\"mediaUrls\\\": [\\n \\\"{{ $json.url }}\\\"\\n ]\\n }\\n }\\n}\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"b9e82889-b753-43e7-b417-213a99763802\",\"name\":\"TIKTOK\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1340,1440],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.tiktok_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"tiktok\\\",\\n \\\"isYourBrand\\\": \\\"false\\\", \\n \\\"disabledDuet\\\": \\\"false\\\",\\n \\\"privacyLevel\\\": \\\"PUBLIC_TO_EVERYONE\\\",\\n \\\"isAiGenerated\\\": \\\"true\\\",\\n \\\"disabledStitch\\\": \\\"false\\\",\\n \\\"disabledComments\\\": \\\"false\\\",\\n \\\"isBrandedContent\\\": \\\"false\\\"\\n \\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"tiktok\\\",\\n \\\"mediaUrls\\\": [\\n \\\"{{ $json.url }}\\\"\\n ]\\n }\\n }\\n}\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"=YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"edf4cd31-ae48-4996-816e-8a32ac411e75\",\"name\":\"FACEBOOK\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[920,1680],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.facebook_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"facebook\\\",\\n \\\"pageId\\\": \\\"{{ $('Assign Social Media IDs').item.json.facebook_page_id }}\\\"\\n\\n \\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"facebook\\\",\\n \\\"mediaUrls\\\": [\\n \\\"{{ $json.url }}\\\"\\n ]\\n }\\n }\\n}\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"=YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"edeb50af-020e-4118-af73-2a4fbb3bf6a2\",\"name\":\"THREADS\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1140,1680],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.threads_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"threads\\\"\\n \\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"threads\\\",\\n \\\"mediaUrls\\\": [\\n \\\"{{ $json.url }}\\\"\\n ]\\n }\\n }\\n}\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"210e36e9-8db2-403c-b72a-2ec45bce2eae\",\"name\":\"TWETTER\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1340,1680],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.twitter_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"twitter\\\"\\n \\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"twitter\\\",\\n \\\"mediaUrls\\\": [\\n \\\"{{ $json.url }}\\\"\\n ]\\n }\\n }\\n}\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"ac3069e4-4fe6-4146-a0e2-973b3c374c55\",\"name\":\"LINKEDIN\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[920,1920],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.linkedin_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"linkedin\\\"\\n \\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"linkedin\\\",\\n \\\"mediaUrls\\\": [\\n \\\"{{ $json.url }}\\\"\\n ]\\n }\\n }\\n}\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"d9c919d8-ae9c-47cf-9b6f-8cb3e7e1f500\",\"name\":\"BLUESKY\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1140,1920],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"= {\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.bluesky_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"bluesky\\\"\\n \\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"bluesky\\\",\\n \\\"mediaUrls\\\": [\\n \\\"https://pbs.twimg.com/media/GE8MgIiWEAAfsK3.jpg\\\"\\n ]\\n }\\n }\\n}\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"a0a0a8fe-f6b0-458c-846e-409200a7b12f\",\"name\":\"PINTEREST\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1340,1920],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.pinterest_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"pinterest\\\",\\n \\\"boardId\\\": \\\"{{ $('Assign Social Media IDs').item.json.pinterest_board_id }}\\\" \\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"pinterest\\\",\\n \\\"mediaUrls\\\": [\\n \\\"https://pbs.twimg.com/media/GE8MgIiWEAAfsK3.jpg\\\"\\n ]\\n }\\n }\\n}\\n\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"38c75425-36a5-45c7-98cb-ed5eb20af249\",\"name\":\"Google Sheets\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[640,1920],\"parameters\":{\"columns\":{\"value\":{\"STATUS\":\"Publish\",\"row_number\":\"={{ $('Get my video').item.json.row_number }}\"},\"schema\":[{\"id\":\"PROMPT\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"PROMPT\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"DESCRIPTION\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"DESCRIPTION\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"URL VIDEO\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"URL VIDEO\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"Titre\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"Titre\",\"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\":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\":\"id\",\"value\":\"=\"},\"documentId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"=\"}},\"typeVersion\":4.5},{\"id\":\"3ac616bc-67bb-494c-bd24-3753fc03e7dc\",\"name\":\"Trigger: Run Daily Script Generator\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"position\":[500,560],\"parameters\":{\"rule\":{\"interval\":[{}]}},\"typeVersion\":1.2},{\"id\":\"8ae30b31-2ac9-4b62-9094-ce36197d319d\",\"name\":\"AI Agent: Generate Video Concept\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[660,560],\"parameters\":{\"text\":\"Give me an idea about [a Yeti speaking to a camera and doing a Vlog through his selfie stick]. \",\"options\":{\"systemMessage\":\"=You are an AI designed to generate 1 immersive, realistic idea based on a user-provided topic. Your output must be formatted as a JSON array (single line) and follow all the rules below exactly.\\n\\nRULES:\\n\\nOnly return 1 idea at a time.\\n\\nThe user will provide a key topic (e.g. “urban farming,” “arctic survival,” “street food in Vietnam”).\\n\\nThe Idea must:\\n\\nBe under 13 words.\\n\\nDescribe an interesting and viral-worthy moment, action, or event related to the provided topic.\\n\\nCan be as surreal as you can get, doesn't have to be real-world!\\n\\nInvolves a character.\\n\\nThe Caption must be:\\n\\nShort, punchy, and viral-friendly.\\n\\nInclude one relevant emoji.\\n\\nInclude exactly 12 hashtags in this order:\\n** 4 topic-relevant hashtags\\n** 4 all-time most popular hashtags\\n** 4 currently trending hashtags (based on live research)\\n\\nAll hashtags must be lowercase.\\n\\nSet Status to \\\"for production\\\" (always).\\n\\nThe Environment must:\\n\\nBe under 20 words.\\n\\nMatch the action in the Idea exactly.\\n\\nClearly describe:\\n\\nWhere the event is happening (e.g. rooftop, jungle trail, city alley, frozen lake)\\n\\nKey visuals or background details (e.g. smoke rising, neon lights, fog, birds overhead)\\n\\nMain participants (e.g. farmer, cook, mechanic, rescue team, animal)\\n\\nStyle of scene (e.g. cinematic realism, handheld docu-style, aerial tracking shot, macro close-up)\\n\\nOk with fictional settings\\n\\nOUTPUT FORMAT (single-line JSON array):\\n\\n\\n[\\n {\\n \\\"Caption\\\": \\\"Short viral title with emoji #4_topic_hashtags #4_all_time_popular_hashtags #4_trending_hashtags\\\",\\n \\\"Idea\\\": \\\"Short idea under 13 words\\\",\\n \\\"Environment\\\": \\\"Brief vivid setting under 20 words matching the action\\\",\\n \\\"Status\\\": \\\"for production\\\"\\n }\\n]\\n\"},\"promptType\":\"define\",\"hasOutputParser\":true},\"typeVersion\":1.9},{\"id\":\"1685126b-bd11-4798-aae9-c676d6cf743d\",\"name\":\"Tool: Inject Creativity\",\"type\":\"@n8n/n8n-nodes-langchain.toolThink\",\"position\":[740,820],\"parameters\":{},\"typeVersion\":1},{\"id\":\"30b4a035-33df-4826-972d-0ed2dd8fbed9\",\"name\":\"LLM: Generate Idea & Caption (GPT-4.1)\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[580,820],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4.1\",\"cachedResultName\":\"gpt-4.1\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"c1e92152-aa05-43dd-8522-23f1514cf0ad\",\"name\":\"Parser: Extract JSON from Idea\",\"type\":\"@n8n/n8n-nodes-langchain.outputParserStructured\",\"position\":[900,820],\"parameters\":{\"jsonSchemaExample\":\"[\\n {\\n \\\"Caption\\\": \\\"Diver Removes Nets Off Whale 🐋 #whalerescue #marinelife #oceanrescue #seahelpers #love #nature #instagood #explore #viral #savenature #oceanguardians #cleanoceans\\\",\\n \\\"Idea\\\": \\\"Diver carefully cuts tangled net from distressed whale in open sea\\\",\\n \\\"Environment\\\": \\\"Open ocean, sunlight beams through water, diver and whale, cinematic realism\\\",\\n \\\"Status\\\": \\\"for production\\\"\\n }\\n]\\n\"},\"typeVersion\":1.2},{\"id\":\"432c7648-f9f9-4807-abf5-64d8f9a6bafb\",\"name\":\"Google Sheets: Save Script Idea\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[1020,560],\"parameters\":{\"columns\":{\"value\":{\"id\":\"==ROW()-1\",\"idea\":\"={{ $json.output[0].Idea }}\",\"caption\":\"={{ $json.output[0].Caption }}\",\"production\":\"={{ $json.output[0].Status }}\",\"environment_prompt\":\"={{ $json.output[0].Environment }}\"},\"schema\":[{\"id\":\"id\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"id\",\"defaultMatch\":true,\"canBeUsedToMatch\":true},{\"id\":\"idea\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"idea\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"caption\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"caption\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"production\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"production\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"environment_prompt\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"environment_prompt\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"final_output\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"final_output\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[\"id\"],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{},\"operation\":\"append\",\"sheetName\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"=\"},\"documentId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"=\"}},\"typeVersion\":4.5},{\"id\":\"02c2e969-0bb6-44fa-8707-37edc2cc77fd\",\"name\":\"AI Agent: Create Veo3-Compatible Prompt\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[1180,560],\"parameters\":{\"text\":\"=Give me a Veo3 prompt for this idea:\\n{{ $json.idea }}\\n\\nThis is the environment:\\n{{ $json.environment_prompt }}\\n\\n\",\"options\":{\"systemMessage\":\"=SYSTEM PROMPT FOR GOOGLE VEO3 PROMPT AGENT\\n\\nYou are an AI agent that writes hyper-realistic, cinematic video prompts for Google VEO3. Each prompt should describe a short, vivid selfie-style video clip featuring one unnamed character speaking or acting in a specific moment. The final video should look like found footage or documentary-style film — grounded, realistic, and immersive.\\n\\nREQUIRED STRUCTURE (FILL IN THE BRACKETS BELOW):\\n\\n[Scene paragraph prompt here]\\n\\nMain character: [description of character]\\nThey say: [insert one line of dialogue, fits the scene and mood].\\nThey [describe a physical action or subtle camera movement, e.g. pans the camera, shifts position, glances around].\\nTime of Day: [day / night / dusk / etc.]\\nLens: [describe lens]\\nAudio: (implied) [ambient sounds, e.g. lion growls, wind, distant traffic, birdsong]\\nBackground: [brief restatement of what is visible behind them]\\n\\nRULES FOR PROMPT GENERATION\\n\\nSingle paragraph only, 750–1500 characters. No line breaks or headings.\\n\\nOnly one human character. Never give them a name.\\n\\nInclude one spoken line of dialogue and describe how it’s delivered.\\n\\nCharacter must do something physical, even if subtle (e.g. glance, smirk, pan camera).\\n\\nUse selfie-style framing. Always describe the lens, stock, and camera behavior.\\n\\nScene must feel real and cinematic — like a short clip someone might record on a stylized camera.\\n\\nAlways include the five key technical elements: Time of Day, Lens, Film Stock, Audio, and Background.\\n\\nDO NOT DO THIS:\\n\\nDon’t name the character.\\n\\nDon’t include more than one character.\\n\\nDon’t describe subtitles or on-screen text.\\n\\nDon’t break the paragraph or use formatting.\\n\\nDon’t write vague or abstract scenes — always keep them grounded in physical detail.\"},\"promptType\":\"define\",\"hasOutputParser\":true},\"typeVersion\":1.9},{\"id\":\"010485e3-7b3f-496b-bcd5-05087a41805c\",\"name\":\"Tool: Build Prompt Structure\",\"type\":\"@n8n/n8n-nodes-langchain.toolThink\",\"position\":[1380,820],\"parameters\":{},\"typeVersion\":1},{\"id\":\"acec06a9-c36d-4bff-a152-4a5b8b73808d\",\"name\":\"LLM: Format Prompt for Veo3 (GPT-4.1)\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[1200,820],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4.1\",\"cachedResultName\":\"gpt-4.1\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"4f8e53f5-d0a1-46c1-a855-a7067b493d66\",\"name\":\"Call Veo3 API to Generate Video\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[520,1100],\"parameters\":{\"url\":\"https://queue.fal.run/fal-ai/veo3\",\"body\":\"={ \\\"prompt\\\": \\\"{{ $json.output }}\\\" }\\n\",\"method\":\"POST\",\"options\":{\"batching\":{\"batch\":{\"batchSize\":1,\"batchInterval\":2000}}},\"sendBody\":true,\"contentType\":\"raw\",\"authentication\":\"genericCredentialType\",\"rawContentType\":\"application/json\",\"genericAuthType\":\"httpHeaderAuth\"},\"typeVersion\":4.2},{\"id\":\"27881cbe-df1c-463d-8baa-5c482f0b1c04\",\"name\":\"Wait for Veo3 Processing (5 mins)\",\"type\":\"n8n-nodes-base.wait\",\"position\":[740,1100],\"webhookId\":\"861e2761-369b-407b-9e88-1b176e617cd8\",\"parameters\":{},\"typeVersion\":1.1},{\"id\":\"671eaf67-367a-41a0-b127-b06adbd5a3c9\",\"name\":\"Retrieve Final Video URL from Veo3\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1020,1100],\"parameters\":{\"url\":\"=https://queue.fal.run/fal-ai/veo3/requests/{{ $json.request_id }}\",\"options\":{},\"authentication\":\"genericCredentialType\",\"genericAuthType\":\"httpHeaderAuth\"},\"typeVersion\":4.2},{\"id\":\"3555e042-a420-49fe-889e-62455616ed7c\",\"name\":\"Google Sheets: Log Final Video Output\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[1340,1100],\"parameters\":{\"columns\":{\"value\":{\"idea\":\"={{ $('Google Sheets: Save Script Idea').first().json.idea }}\",\"production\":\"done\",\"final_output\":\"={{ $json.video.url }}\"},\"schema\":[{\"id\":\"id\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"id\",\"defaultMatch\":true,\"canBeUsedToMatch\":true},{\"id\":\"idea\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"idea\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"caption\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"caption\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"production\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"production\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"environment_prompt\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"environment_prompt\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"final_output\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"final_output\",\"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\":[\"idea\"],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{},\"operation\":\"update\",\"sheetName\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"=\"},\"documentId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"=\"}},\"typeVersion\":4.5}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Get my video\":{\"main\":[[{\"node\":\"Assign Social Media IDs\",\"type\":\"main\",\"index\":0}]]},\"Assign Social Media IDs\":{\"main\":[[{\"node\":\"Upload Video to Blotato\",\"type\":\"main\",\"index\":0}]]},\"Tool: Inject Creativity\":{\"ai_tool\":[[{\"node\":\"AI Agent: Generate Video Concept\",\"type\":\"ai_tool\",\"index\":0}]]},\"Upload Video to Blotato\":{\"main\":[[{\"node\":\"INSTAGRAM\",\"type\":\"main\",\"index\":0},{\"node\":\"YOUTUBE\",\"type\":\"main\",\"index\":0},{\"node\":\"TIKTOK\",\"type\":\"main\",\"index\":0},{\"node\":\"FACEBOOK\",\"type\":\"main\",\"index\":0},{\"node\":\"THREADS\",\"type\":\"main\",\"index\":0},{\"node\":\"TWETTER\",\"type\":\"main\",\"index\":0},{\"node\":\"LINKEDIN\",\"type\":\"main\",\"index\":0},{\"node\":\"BLUESKY\",\"type\":\"main\",\"index\":0},{\"node\":\"PINTEREST\",\"type\":\"main\",\"index\":0},{\"node\":\"Google Sheets\",\"type\":\"main\",\"index\":0}]]},\"Tool: Build Prompt Structure\":{\"ai_tool\":[[{\"node\":\"AI Agent: Create Veo3-Compatible Prompt\",\"type\":\"ai_tool\",\"index\":0}]]},\"Parser: Extract JSON from Idea\":{\"ai_outputParser\":[[{\"node\":\"AI Agent: Generate Video Concept\",\"type\":\"ai_outputParser\",\"index\":0}]]},\"Call Veo3 API to Generate Video\":{\"main\":[[{\"node\":\"Wait for Veo3 Processing (5 mins)\",\"type\":\"main\",\"index\":0}]]},\"Google Sheets: Save Script Idea\":{\"main\":[[{\"node\":\"AI Agent: Create Veo3-Compatible Prompt\",\"type\":\"main\",\"index\":0}]]},\"AI Agent: Generate Video Concept\":{\"main\":[[{\"node\":\"Google Sheets: Save Script Idea\",\"type\":\"main\",\"index\":0}]]},\"Wait for Veo3 Processing (5 mins)\":{\"main\":[[{\"node\":\"Retrieve Final Video URL from Veo3\",\"type\":\"main\",\"index\":0}]]},\"Retrieve Final Video URL from Veo3\":{\"main\":[[{\"node\":\"Google Sheets: Log Final Video Output\",\"type\":\"main\",\"index\":0}]]},\"Trigger: Run Daily Script Generator\":{\"main\":[[{\"node\":\"AI Agent: Generate Video Concept\",\"type\":\"main\",\"index\":0}]]},\"Google Sheets: Log Final Video Output\":{\"main\":[[{\"node\":\"Get my video\",\"type\":\"main\",\"index\":0}]]},\"LLM: Format Prompt for Veo3 (GPT-4.1)\":{\"ai_languageModel\":[[{\"node\":\"AI Agent: Create Veo3-Compatible Prompt\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"LLM: Generate Idea & Caption (GPT-4.1)\":{\"ai_languageModel\":[[{\"node\":\"AI Agent: Generate Video Concept\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"AI Agent: Create Veo3-Compatible Prompt\":{\"main\":[[{\"node\":\"Call Veo3 API to Generate Video\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 26, "node_types": {"set": 1, "googleSheets": 4, "httpRequest": 12, "scheduleTrigger": 1, "agent": 2, "toolThink": 2, "lmChatOpenAi": 2, "outputParserStructured": 1, "wait": 1}, "services": ["ai", "google", "http"], "complexity": "complex", "has_conditions": false, "has_loops": false, "has_code": false, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Generate & Auto-post AI Videos to Social Media with Veo3 and Blotato"}, {"role": "assistant", "content": "\n**Analyse du besoin**: Automate video creation with Veo3 and auto-post to Instagram, TikTok via Blotato\nWho is this for?\n\nThis template is ideal for content creators, social media managers, YouTubers, and digital marketers ...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 26 nodes utilisant ai, google, http.\nStructure: intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"eFkkWqS5KdrxZ43P\",\"meta\":{\"instanceId\":\"a2b23892dd6989fda7c1209b381f5850373a7d2b85609624d7c2b7a092671d44\",\"templateCredsSetupCompleted\":true},\"name\":\"Automate video creation with Veo3 and auto-post to Instagram, TikTok via Blotato - vide\",\"tags\":[],\"nodes\":[{\"id\":\"45a5a9f4-fe6a-43a7-a032-c69750826209\",\"name\":\"Assign Social Media IDs\",\"type\":\"n8n-nodes-base.set\",\"position\":[420,1680],\"parameters\":{\"mode\":\"raw\",\"options\":{},\"jsonOutput\":\"{\\n \\\"instagram_id\\\": \\\"1111\\\",\\n \\\"youtube_id\\\": \\\"1111\\\",\\n \\\"threads_id\\\": \\\"1111\\\",\\n \\\"tiktok_id\\\": \\\"1111\\\",\\n \\\"facebook_id\\\": \\\"1111\\\",\\n \\\"facebook_page_id\\\": \\\"1111\\\",\\n \\\"twitter_id\\\": \\\"1111\\\",\\n \\\"linkedin_id\\\": \\\"1111\\\",\\n \\\"pinterest_id\\\": \\\"1111\\\",\\n \\\"pinterest_board_id\\\": \\\"1111\\\",\\n \\\"bluesky_id\\\": \\\"1111\\\"\\n}\\n\"},\"typeVersion\":3.4},{\"id\":\"6d125a85-b626-4981-8cfc-bcac4ea0ca89\",\"name\":\"Get my video\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[520,1440],\"parameters\":{\"options\":{},\"sheetName\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"=\"},\"documentId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"=\"}},\"typeVersion\":4.5},{\"id\":\"779818a1-97bd-4bf9-ba17-995c1439df6f\",\"name\":\"Upload Video to Blotato\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[640,1680],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/media\",\"method\":\"POST\",\"options\":{},\"sendBody\":true,\"sendHeaders\":true,\"bodyParameters\":{\"parameters\":[{\"name\":\"url\",\"value\":\"={{ $('Get my video').item.json['final_output'] }}\"}]},\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"113d635c-bf8f-4ed3-801e-de78b0df9437\",\"name\":\"INSTAGRAM\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[920,1440],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.instagram_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"instagram\\\"\\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"instagram\\\",\\n \\\"mediaUrls\\\": [\\n \\\"{{ $json.url }}\\\"\\n ]\\n }\\n }\\n}\\n\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"02aa72ee-e5b9-44ee-9cbf-e8ddbc259570\",\"name\":\"YOUTUBE\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1140,1440],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.youtube_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"youtube\\\",\\n \\\"title\\\": \\\"{{ $('Get my video').item.json.Titre }}\\\",\\n \\\"privacyStatus\\\": \\\"unlisted\\\",\\n \\\"shouldNotifySubscribers\\\": \\\"false\\\"\\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"youtube\\\",\\n \\\"mediaUrls\\\": [\\n \\\"{{ $json.url }}\\\"\\n ]\\n }\\n }\\n}\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"b9e82889-b753-43e7-b417-213a99763802\",\"name\":\"TIKTOK\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1340,1440],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.tiktok_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"tiktok\\\",\\n \\\"isYourBrand\\\": \\\"false\\\", \\n \\\"disabledDuet\\\": \\\"false\\\",\\n \\\"privacyLevel\\\": \\\"PUBLIC_TO_EVERYONE\\\",\\n \\\"isAiGenerated\\\": \\\"true\\\",\\n \\\"disabledStitch\\\": \\\"false\\\",\\n \\\"disabledComments\\\": \\\"false\\\",\\n \\\"isBrandedContent\\\": \\\"false\\\"\\n \\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"tiktok\\\",\\n \\\"mediaUrls\\\": [\\n \\\"{{ $json.url }}\\\"\\n ]\\n }\\n }\\n}\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"=YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"edf4cd31-ae48-4996-816e-8a32ac411e75\",\"name\":\"FACEBOOK\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[920,1680],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.facebook_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"facebook\\\",\\n \\\"pageId\\\": \\\"{{ $('Assign Social Media IDs').item.json.facebook_page_id }}\\\"\\n\\n \\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"facebook\\\",\\n \\\"mediaUrls\\\": [\\n \\\"{{ $json.url }}\\\"\\n ]\\n }\\n }\\n}\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"=YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"edeb50af-020e-4118-af73-2a4fbb3bf6a2\",\"name\":\"THREADS\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1140,1680],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.threads_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"threads\\\"\\n \\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"threads\\\",\\n \\\"mediaUrls\\\": [\\n \\\"{{ $json.url }}\\\"\\n ]\\n }\\n }\\n}\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"210e36e9-8db2-403c-b72a-2ec45bce2eae\",\"name\":\"TWETTER\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1340,1680],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.twitter_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"twitter\\\"\\n \\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"twitter\\\",\\n \\\"mediaUrls\\\": [\\n \\\"{{ $json.url }}\\\"\\n ]\\n }\\n }\\n}\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"ac3069e4-4fe6-4146-a0e2-973b3c374c55\",\"name\":\"LINKEDIN\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[920,1920],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.linkedin_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"linkedin\\\"\\n \\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"linkedin\\\",\\n \\\"mediaUrls\\\": [\\n \\\"{{ $json.url }}\\\"\\n ]\\n }\\n }\\n}\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"d9c919d8-ae9c-47cf-9b6f-8cb3e7e1f500\",\"name\":\"BLUESKY\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1140,1920],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"= {\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.bluesky_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"bluesky\\\"\\n \\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"bluesky\\\",\\n \\\"mediaUrls\\\": [\\n \\\"https://pbs.twimg.com/media/GE8MgIiWEAAfsK3.jpg\\\"\\n ]\\n }\\n }\\n}\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"a0a0a8fe-f6b0-458c-846e-409200a7b12f\",\"name\":\"PINTEREST\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1340,1920],\"parameters\":{\"url\":\"https://backend.blotato.com/v2/posts\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"post\\\": {\\n \\\"accountId\\\": \\\"{{ $('Assign Social Media IDs').item.json.pinterest_id }}\\\",\\n \\\"target\\\": {\\n \\\"targetType\\\": \\\"pinterest\\\",\\n \\\"boardId\\\": \\\"{{ $('Assign Social Media IDs').item.json.pinterest_board_id }}\\\" \\n },\\n \\\"content\\\": {\\n \\\"text\\\": \\\"{{ $('Get my video').item.json.DESCRIPTION }}\\\",\\n \\\"platform\\\": \\\"pinterest\\\",\\n \\\"mediaUrls\\\": [\\n \\\"https://pbs.twimg.com/media/GE8MgIiWEAAfsK3.jpg\\\"\\n ]\\n }\\n }\\n}\\n\\n\",\"sendBody\":true,\"sendHeaders\":true,\"specifyBody\":\"json\",\"headerParameters\":{\"parameters\":[{\"name\":\"blotato-api-key\",\"value\":\"YOUR_API_HERE\"}]}},\"typeVersion\":4.2},{\"id\":\"38c75425-36a5-45c7-98cb-ed5eb20af249\",\"name\":\"Google Sheets\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[640,1920],\"parameters\":{\"columns\":{\"value\":{\"STATUS\":\"Publish\",\"row_number\":\"={{ $('Get my video').item.json.row_number }}\"},\"schema\":[{\"id\":\"PROMPT\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"PROMPT\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"DESCRIPTION\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"DESCRIPTION\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"URL VIDEO\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"URL VIDEO\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"Titre\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"Titre\",\"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\":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\":\"id\",\"value\":\"=\"},\"documentId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"=\"}},\"typeVersion\":4.5},{\"id\":\"3ac616bc-67bb-494c-bd24-3753fc03e7dc\",\"name\":\"Trigger: Run Daily Script Generator\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"position\":[500,560],\"parameters\":{\"rule\":{\"interval\":[{}]}},\"typeVersion\":1.2},{\"id\":\"8ae30b31-2ac9-4b62-9094-ce36197d319d\",\"name\":\"AI Agent: Generate Video Concept\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[660,560],\"parameters\":{\"text\":\"Give me an idea about [a Yeti speaking to a camera and doing a Vlog through his selfie stick]. \",\"options\":{\"systemMessage\":\"=You are an AI designed to generate 1 immersive, realistic idea based on a user-provided topic. Your output must be formatted as a JSON array (single line) and follow all the rules below exactly.\\n\\nRULES:\\n\\nOnly return 1 idea at a time.\\n\\nThe user will provide a key topic (e.g. “urban farming,” “arctic survival,” “street food in Vietnam”).\\n\\nThe Idea must:\\n\\nBe under 13 words.\\n\\nDescribe an interesting and viral-worthy moment, action, or event related to the provided topic.\\n\\nCan be as surreal as you can get, doesn't have to be real-world!\\n\\nInvolves a character.\\n\\nThe Caption must be:\\n\\nShort, punchy, and viral-friendly.\\n\\nInclude one relevant emoji.\\n\\nInclude exactly 12 hashtags in this order:\\n** 4 topic-relevant hashtags\\n** 4 all-time most popular hashtags\\n** 4 currently trending hashtags (based on live research)\\n\\nAll hashtags must be lowercase.\\n\\nSet Status to \\\"for production\\\" (always).\\n\\nThe Environment must:\\n\\nBe under 20 words.\\n\\nMatch the action in the Idea exactly.\\n\\nClearly describe:\\n\\nWhere the event is happening (e.g. rooftop, jungle trail, city alley, frozen lake)\\n\\nKey visuals or background details (e.g. smoke rising, neon lights, fog, birds overhead)\\n\\nMain participants (e.g. farmer, cook, mechanic, rescue team, animal)\\n\\nStyle of scene (e.g. cinematic realism, handheld docu-style, aerial tracking shot, macro close-up)\\n\\nOk with fictional settings\\n\\nOUTPUT FORMAT (single-line JSON array):\\n\\n\\n[\\n {\\n \\\"Caption\\\": \\\"Short viral title with emoji #4_topic_hashtags #4_all_time_popular_hashtags #4_trending_hashtags\\\",\\n \\\"Idea\\\": \\\"Short idea under 13 words\\\",\\n \\\"Environment\\\": \\\"Brief vivid setting under 20 words matching the action\\\",\\n \\\"Status\\\": \\\"for production\\\"\\n }\\n]\\n\"},\"promptType\":\"define\",\"hasOutputParser\":true},\"typeVersion\":1.9},{\"id\":\"1685126b-bd11-4798-aae9-c676d6cf743d\",\"name\":\"Tool: Inject Creativity\",\"type\":\"@n8n/n8n-nodes-langchain.toolThink\",\"position\":[740,820],\"parameters\":{},\"typeVersion\":1},{\"id\":\"30b4a035-33df-4826-972d-0ed2dd8fbed9\",\"name\":\"LLM: Generate Idea & Caption (GPT-4.1)\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[580,820],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4.1\",\"cachedResultName\":\"gpt-4.1\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"c1e92152-aa05-43dd-8522-23f1514cf0ad\",\"name\":\"Parser: Extract JSON from Idea\",\"type\":\"@n8n/n8n-nodes-langchain.outputParserStructured\",\"position\":[900,820],\"parameters\":{\"jsonSchemaExample\":\"[\\n {\\n \\\"Caption\\\": \\\"Diver Removes Nets Off Whale 🐋 #whalerescue #marinelife #oceanrescue #seahelpers #love #nature #instagood #explore #viral #savenature #oceanguardians #cleanoceans\\\",\\n \\\"Idea\\\": \\\"Diver carefully cuts tangled net from distressed whale in open sea\\\",\\n \\\"Environment\\\": \\\"Open ocean, sunlight beams through water, diver and whale, cinematic realism\\\",\\n \\\"Status\\\": \\\"for production\\\"\\n }\\n]\\n\"},\"typeVersion\":1.2},{\"id\":\"432c7648-f9f9-4807-abf5-64d8f9a6bafb\",\"name\":\"Google Sheets: Save Script Idea\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[1020,560],\"parameters\":{\"columns\":{\"value\":{\"id\":\"==ROW()-1\",\"idea\":\"={{ $json.output[0].Idea }}\",\"caption\":\"={{ $json.output[0].Caption }}\",\"production\":\"={{ $json.output[0].Status }}\",\"environment_prompt\":\"={{ $json.output[0].Environment }}\"},\"schema\":[{\"id\":\"id\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"id\",\"defaultMatch\":true,\"canBeUsedToMatch\":true},{\"id\":\"idea\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"idea\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"caption\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"caption\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"production\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"production\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"environment_prompt\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"environment_prompt\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"final_output\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"final_output\",\"defaultMatch\":false,\"canBeUsedToMatch\":true}],\"mappingMode\":\"defineBelow\",\"matchingColumns\":[\"id\"],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{},\"operation\":\"append\",\"sheetName\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"=\"},\"documentId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"=\"}},\"typeVersion\":4.5},{\"id\":\"02c2e969-0bb6-44fa-8707-37edc2cc77fd\",\"name\":\"AI Agent: Create Veo3-Compatible Prompt\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[1180,560],\"parameters\":{\"text\":\"=Give me a Veo3 prompt for this idea:\\n{{ $json.idea }}\\n\\nThis is the environment:\\n{{ $json.environment_prompt }}\\n\\n\",\"options\":{\"systemMessage\":\"=SYSTEM PROMPT FOR GOOGLE VEO3 PROMPT AGENT\\n\\nYou are an AI agent that writes hyper-realistic, cinematic video prompts for Google VEO3. Each prompt should describe a short, vivid selfie-style video clip featuring one unnamed character speaking or acting in a specific moment. The final video should look like found footage or documentary-style film — grounded, realistic, and immersive.\\n\\nREQUIRED STRUCTURE (FILL IN THE BRACKETS BELOW):\\n\\n[Scene paragraph prompt here]\\n\\nMain character: [description of character]\\nThey say: [insert one line of dialogue, fits the scene and mood].\\nThey [describe a physical action or subtle camera movement, e.g. pans the camera, shifts position, glances around].\\nTime of Day: [day / night / dusk / etc.]\\nLens: [describe lens]\\nAudio: (implied) [ambient sounds, e.g. lion growls, wind, distant traffic, birdsong]\\nBackground: [brief restatement of what is visible behind them]\\n\\nRULES FOR PROMPT GENERATION\\n\\nSingle paragraph only, 750–1500 characters. No line breaks or headings.\\n\\nOnly one human character. Never give them a name.\\n\\nInclude one spoken line of dialogue and describe how it’s delivered.\\n\\nCharacter must do something physical, even if subtle (e.g. glance, smirk, pan camera).\\n\\nUse selfie-style framing. Always describe the lens, stock, and camera behavior.\\n\\nScene must feel real and cinematic — like a short clip someone might record on a stylized camera.\\n\\nAlways include the five key technical elements: Time of Day, Lens, Film Stock, Audio, and Background.\\n\\nDO NOT DO THIS:\\n\\nDon’t name the character.\\n\\nDon’t include more than one character.\\n\\nDon’t describe subtitles or on-screen text.\\n\\nDon’t break the paragraph or use formatting.\\n\\nDon’t write vague or abstract scenes — always keep them grounded in physical detail.\"},\"promptType\":\"define\",\"hasOutputParser\":true},\"typeVersion\":1.9},{\"id\":\"010485e3-7b3f-496b-bcd5-05087a41805c\",\"name\":\"Tool: Build Prompt Structure\",\"type\":\"@n8n/n8n-nodes-langchain.toolThink\",\"position\":[1380,820],\"parameters\":{},\"typeVersion\":1},{\"id\":\"acec06a9-c36d-4bff-a152-4a5b8b73808d\",\"name\":\"LLM: Format Prompt for Veo3 (GPT-4.1)\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatOpenAi\",\"position\":[1200,820],\"parameters\":{\"model\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4.1\",\"cachedResultName\":\"gpt-4.1\"},\"options\":{}},\"typeVersion\":1.2},{\"id\":\"4f8e53f5-d0a1-46c1-a855-a7067b493d66\",\"name\":\"Call Veo3 API to Generate Video\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[520,1100],\"parameters\":{\"url\":\"https://queue.fal.run/fal-ai/veo3\",\"body\":\"={ \\\"prompt\\\": \\\"{{ $json.output }}\\\" }\\n\",\"method\":\"POST\",\"options\":{\"batching\":{\"batch\":{\"batchSize\":1,\"batchInterval\":2000}}},\"sendBody\":true,\"contentType\":\"raw\",\"authentication\":\"genericCredentialType\",\"rawContentType\":\"application/json\",\"genericAuthType\":\"httpHeaderAuth\"},\"typeVersion\":4.2},{\"id\":\"27881cbe-df1c-463d-8baa-5c482f0b1c04\",\"name\":\"Wait for Veo3 Processing (5 mins)\",\"type\":\"n8n-nodes-base.wait\",\"position\":[740,1100],\"webhookId\":\"861e2761-369b-407b-9e88-1b176e617cd8\",\"parameters\":{},\"typeVersion\":1.1},{\"id\":\"671eaf67-367a-41a0-b127-b06adbd5a3c9\",\"name\":\"Retrieve Final Video URL from Veo3\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[1020,1100],\"parameters\":{\"url\":\"=https://queue.fal.run/fal-ai/veo3/requests/{{ $json.request_id }}\",\"options\":{},\"authentication\":\"genericCredentialType\",\"genericAuthType\":\"httpHeaderAuth\"},\"typeVersion\":4.2},{\"id\":\"3555e042-a420-49fe-889e-62455616ed7c\",\"name\":\"Google Sheets: Log Final Video Output\",\"type\":\"n8n-nodes-base.googleSheets\",\"position\":[1340,1100],\"parameters\":{\"columns\":{\"value\":{\"idea\":\"={{ $('Google Sheets: Save Script Idea').first().json.idea }}\",\"production\":\"done\",\"final_output\":\"={{ $json.video.url }}\"},\"schema\":[{\"id\":\"id\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"id\",\"defaultMatch\":true,\"canBeUsedToMatch\":true},{\"id\":\"idea\",\"type\":\"string\",\"display\":true,\"removed\":false,\"required\":false,\"displayName\":\"idea\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"caption\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"caption\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"production\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"production\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"environment_prompt\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"environment_prompt\",\"defaultMatch\":false,\"canBeUsedToMatch\":true},{\"id\":\"final_output\",\"type\":\"string\",\"display\":true,\"required\":false,\"displayName\":\"final_output\",\"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\":[\"idea\"],\"attemptToConvertTypes\":false,\"convertFieldsToString\":false},\"options\":{},\"operation\":\"update\",\"sheetName\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"=\"},\"documentId\":{\"__rl\":true,\"mode\":\"id\",\"value\":\"=\"}},\"typeVersion\":4.5}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Get my video\":{\"main\":[[{\"node\":\"Assign Social Media IDs\",\"type\":\"main\",\"index\":0}]]},\"Assign Social Media IDs\":{\"main\":[[{\"node\":\"Upload Video to Blotato\",\"type\":\"main\",\"index\":0}]]},\"Tool: Inject Creativity\":{\"ai_tool\":[[{\"node\":\"AI Agent: Generate Video Concept\",\"type\":\"ai_tool\",\"index\":0}]]},\"Upload Video to Blotato\":{\"main\":[[{\"node\":\"INSTAGRAM\",\"type\":\"main\",\"index\":0},{\"node\":\"YOUTUBE\",\"type\":\"main\",\"index\":0},{\"node\":\"TIKTOK\",\"type\":\"main\",\"index\":0},{\"node\":\"FACEBOOK\",\"type\":\"main\",\"index\":0},{\"node\":\"THREADS\",\"type\":\"main\",\"index\":0},{\"node\":\"TWETTER\",\"type\":\"main\",\"index\":0},{\"node\":\"LINKEDIN\",\"type\":\"main\",\"index\":0},{\"node\":\"BLUESKY\",\"type\":\"main\",\"index\":0},{\"node\":\"PINTEREST\",\"type\":\"main\",\"index\":0},{\"node\":\"Google Sheets\",\"type\":\"main\",\"index\":0}]]},\"Tool: Build Prompt Structure\":{\"ai_tool\":[[{\"node\":\"AI Agent: Create Veo3-Compatible Prompt\",\"type\":\"ai_tool\",\"index\":0}]]},\"Parser: Extract JSON from Idea\":{\"ai_outputParser\":[[{\"node\":\"AI Agent: Generate Video Concept\",\"type\":\"ai_outputParser\",\"index\":0}]]},\"Call Veo3 API to Generate Video\":{\"main\":[[{\"node\":\"Wait for Veo3 Processing (5 mins)\",\"type\":\"main\",\"index\":0}]]},\"Google Sheets: Save Script Idea\":{\"main\":[[{\"node\":\"AI Agent: Create Veo3-Compatible Prompt\",\"type\":\"main\",\"index\":0}]]},\"AI Agent: Generate Video Concept\":{\"main\":[[{\"node\":\"Google Sheets: Save Script Idea\",\"type\":\"main\",\"index\":0}]]},\"Wait for Veo3 Processing (5 mins)\":{\"main\":[[{\"node\":\"Retrieve Final Video URL from Veo3\",\"type\":\"main\",\"index\":0}]]},\"Retrieve Final Video URL from Veo3\":{\"main\":[[{\"node\":\"Google Sheets: Log Final Video Output\",\"type\":\"main\",\"index\":0}]]},\"Trigger: Run Daily Script Generator\":{\"main\":[[{\"node\":\"AI Agent: Generate Video Concept\",\"type\":\"main\",\"index\":0}]]},\"Google Sheets: Log Final Video Output\":{\"main\":[[{\"node\":\"Get my video\",\"type\":\"main\",\"index\":0}]]},\"LLM: Format Prompt for Veo3 (GPT-4.1)\":{\"ai_languageModel\":[[{\"node\":\"AI Agent: Create Veo3-Compatible Prompt\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"LLM: Generate Idea & Caption (GPT-4.1)\":{\"ai_languageModel\":[[{\"node\":\"AI Agent: Generate Video Concept\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"AI Agent: Create Veo3-Compatible Prompt\":{\"main\":[[{\"node\":\"Call Veo3 API to Generate Video\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 26, "node_types": {"set": 1, "googleSheets": 4, "httpRequest": 12, "scheduleTrigger": 1, "agent": 2, "toolThink": 2, "lmChatOpenAi": 2, "outputParserStructured": 1, "wait": 1}, "services": ["ai", "google", "http"], "complexity": "complex", "has_conditions": false, "has_loops": false, "has_code": false, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: How it works: This n8n workflow automates communication with meeting invitees to decrease no-show rates by sending timely email and WhatsApp reminders, and a clarification request if more information is needed to prepare the meeting. Step-by-step: The workflow is triggered by an incoming email notification from Calendly about a newly scheduled meeting. It uses AI to extract key meeting data from the email content. It checks if the invitee didn't provide sufficient information, and, if there is a need for more information, sends a clarification request email. It calculates the waiting time required for the 24-hour and 1-hour reminders. It uses an If node to determine the correct waiting path based on the meeting time. It uses Wait nodes for timing the reminders correctly. Finally, it sends "}, {"role": "assistant", "content": "\n**Analyse du besoin**: How it works:\n\nThis n8n workflow automates communication with meeting invitees to decrease no-show rates by sending timely email and WhatsApp reminders, and a clarification request if more information...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 14 nodes utilisant ai, google.\nStructure: logique conditionnelle, code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"QpilLWi7ZJID0IK3\",\"meta\":{\"instanceId\":\"e0abec5d9b13345e424c0dbbc512271f89fb17de3b268697e13a797de2271404\",\"templateCredsSetupCompleted\":true},\"name\":\"Decrease No-Shows from Calendly Meetings (Template)\",\"tags\":[],\"nodes\":[{\"id\":\"1fb2d001-2f04-4f5e-8f93-0c7668f246e0\",\"name\":\"Send Reminder Email\",\"type\":\"n8n-nodes-base.emailSend\",\"position\":[1680,-80],\"webhookId\":\"e971be6e-d7e5-4146-b974-93aa5491c0ac\",\"parameters\":{\"text\":\"Hi {{$json[\\\"invitee_name\\\"]}},\\\\n\\\\nJust a quick reminder about our strategy call scheduled for {{$json[\\\"meeting_time\\\"]}}, {{$json[\\\"meeting_date\\\"]}} (EET).\\\\n\\\\nWe'll discuss how to scale smarter with AI and data-driven systems.\\\\n\\\\nJoin via: {{$json[\\\"meeting_link\\\"]}}\\\\n\\\\nTalk soon,\\\\n[HOST_NAME]\",\"options\":{},\"subject\":\"Reminder: Your AI Strategy Call {{ $json.type === '24h' ? 'Tomorrow' : 'in 1 hour' }}\",\"toEmail\":\"={{ $('extract from email').item.json.output.invitee_email }}\",\"fromEmail\":\"[HOST_EMAIL]\"},\"typeVersion\":2},{\"id\":\"4ca79811-a7eb-42af-b461-f4166824172b\",\"name\":\"Structured Output Parser\",\"type\":\"@n8n/n8n-nodes-langchain.outputParserStructured\",\"position\":[96,160],\"parameters\":{\"jsonSchemaExample\":\"{\\n \\\"invitee_name\\\": \\\"string\\\",\\n \\\"invitee_email\\\": \\\"string\\\",\\n \\\"phone_number\\\": \\\"string\\\",\\n \\\"meeting_date\\\": \\\"date\\\",\\n \\\"meeting_time\\\": \\\"time\\\",\\n \\\"meeting_link\\\": \\\"string\\\",\\n \\\"meeting_goal\\\": \\\"string\\\",\\n \\\"needs_more_info\\\": \\\"boolean\\\",\\n \\\"additional_info\\\": \\\"string\\\"\\n}\\n\"},\"typeVersion\":1.3},{\"id\":\"12c9c9e9-9d62-4f69-83fb-ad4f16947201\",\"name\":\"Calculator\",\"type\":\"@n8n/n8n-nodes-langchain.toolCalculator\",\"position\":[-32,160],\"parameters\":{},\"typeVersion\":1},{\"id\":\"54205d4e-0f6c-4f54-acb0-4f98a5d2b326\",\"name\":\"Notification received\",\"type\":\"n8n-nodes-base.emailReadImap\",\"position\":[-384,-64],\"parameters\":{\"options\":{},\"postProcessAction\":\"nothing\"},\"typeVersion\":2.1},{\"id\":\"3a212390-ff8a-4d0b-8db1-7290a5a348fa\",\"name\":\"LLM model\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatGoogleGemini\",\"position\":[-160,160],\"parameters\":{\"options\":{}},\"typeVersion\":1},{\"id\":\"f043a10a-ec90-4702-82fa-344ff68951be\",\"name\":\"Check if More Info is Needed\",\"type\":\"n8n-nodes-base.if\",\"position\":[304,-64],\"parameters\":{\"conditions\":{\"string\":[{\"value1\":\"={{ $json.output.needs_more_info }}\",\"value2\":\"true\"}]}},\"typeVersion\":1},{\"id\":\"252ae5b4-7342-41e1-861d-d9f091e391f2\",\"name\":\"Calculate Waiting Time\",\"type\":\"n8n-nodes-base.code\",\"position\":[800,-64],\"parameters\":{\"jsCode\":\"// === Parse email received date ===\\nconst emailReceivedStr = $('Notification received').first().json.date; // e.g., \\\"Tue, 28 Oct 2025 22:34:56 +0200\\\"\\nconst emailReceived = new Date(emailReceivedStr);\\n\\n// === Parse meeting date and time from Output Parser ===\\nconst meetingDateStr = $input.first().json.output.meeting_date; // e.g., \\\"2025-10-29\\\"\\nconst meetingTimeStr = $input.first().json.output.meeting_time; // e.g., \\\"16:00\\\"\\n\\n// === Combine meeting date and time with EET offset (+02:00) ===\\nconst meetingDateTime = new Date(`${meetingDateStr}T${meetingTimeStr}:00+02:00`);\\n\\n// === Calculate difference in hours between meeting and email received ===\\nconst diffHrs = (meetingDateTime - emailReceived) / (1000 * 60 * 60);\\n\\n// === Prepare wait times for reminders ===\\nconst waitOutput = {\\n wait_24h: 0, // Reminder 24h before meeting\\n wait_1h: 0 // Reminder 1h before meeting\\n};\\n\\n// If the difference is more than 24h, calculate 24h reminder\\nif (diffHrs > 24) {\\n waitOutput.wait_24h = Math.floor(diffHrs - 24);\\n}\\n\\n// If the difference is less than 24h, calculate 1h reminder\\nif (diffHrs < 24) {\\n waitOutput.wait_1h = Math.floor(diffHrs - 1);\\n}\\n\\n// Ensure both fields are numbers (null replaced with 0)\\nwaitOutput.wait_24h = waitOutput.wait_24h || 0;\\nwaitOutput.wait_1h = waitOutput.wait_1h || 0;\\n\\n// === Return JSON object ===\\nreturn [\\n {\\n json: waitOutput\\n }\\n];\\n\"},\"typeVersion\":2,\"alwaysOutputData\":true},{\"id\":\"edb48348-1a46-4486-8a2c-188bb8971b00\",\"name\":\"When to send\",\"type\":\"n8n-nodes-base.if\",\"position\":[1056,-64],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"5029e2f0-c526-4ff9-8b51-ce763c11bcba\",\"operator\":{\"type\":\"number\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.wait_24h }}\",\"rightValue\":0}]}},\"typeVersion\":2.2},{\"id\":\"902b64a0-ba2b-429e-af79-38327a4c6d7a\",\"name\":\"Wait to send 1h before meeting\",\"type\":\"n8n-nodes-base.wait\",\"position\":[1296,-256],\"webhookId\":\"45f9ddd0-f1a2-470e-b5fb-5cee857d81f6\",\"parameters\":{\"amount\":\"={{ $json.wait_24h }}\"},\"typeVersion\":1},{\"id\":\"841cafba-7dba-4fe7-adf3-57d68f00f51c\",\"name\":\"Wait to send 24h before meeting\",\"type\":\"n8n-nodes-base.wait\",\"position\":[1296,-16],\"webhookId\":\"588ef178-4da2-4808-91d3-7c02aa5f7a54\",\"parameters\":{\"amount\":\"={{ $('Calculate Waiting Time').item.json.wait_24h }}\"},\"typeVersion\":1},{\"id\":\"bcf10853-cb1b-43d7-b7b5-1a09ff272c08\",\"name\":\"Wait to send 1h before meeting after 24h\",\"type\":\"n8n-nodes-base.wait\",\"position\":[1296,224],\"webhookId\":\"f62dfee2-8297-431e-8c39-a6585b2bb7a5\",\"parameters\":{\"amount\":\"={{ $('Calculate Waiting Time').item.json.wait_1h }}+{{ $('Calculate Waiting Time').item.json.wait_24h }}\"},\"typeVersion\":1},{\"id\":\"8b82159a-c4ca-4efb-adc6-86b2df259d57\",\"name\":\"Send Clarification request\",\"type\":\"n8n-nodes-base.emailSend\",\"position\":[528,-80],\"webhookId\":\"74415f90-ca61-4aef-9a48-60ab3437519d\",\"parameters\":{\"text\":\"Hi {{$json[\\\"invitee_name\\\"]}},\\\\n\\\\nI noticed you mentioned '{{$json[\\\"additional_info\\\"]}}'. Could you please share more details before our call? This will help me tailor our session to your goals.\\\\n\\\\nLooking forward to our meeting,\\\\n\\\\n[HOST_NAME]\",\"options\":{},\"subject\":\"Quick question before our strategy call\",\"toEmail\":\"={{$json[\\\"invitee_email\\\"]}}\",\"fromEmail\":\"[HOST_EMAIL]\"},\"typeVersion\":2},{\"id\":\"cff10792-a670-4e93-983e-ecc3a5e4e664\",\"name\":\"Send WhatsApp Reminder\",\"type\":\"n8n-nodes-base.twilio\",\"position\":[1680,112],\"parameters\":{\"to\":\"=whatsapp:={{ $('extract from email').item.json.output.phone_number.replace(/\\\\s+/g,'').replace('+','') }}\",\"from\":\"whatsapp:[TWILIO_WHATSAPP_FROM]\",\"message\":\"Hi {{ $('analyze email').item.json.output.invitee_name }}, just a reminder that your AI strategy call is {{ $('analyze email').item.json.output.meeting_date }} @ {{ $('analyze email').item.json.output.meeting_time }} (EET).\\\\nJoin via: {{ $('analyze email').item.json.output.meeting_link }}\\\\nLooking forward! - [HOST_NAME]\",\"options\":{}},\"typeVersion\":1},{\"id\":\"3701bdb4-d51e-4e4c-b252-c8f6b1abfde6\",\"name\":\"extract from email\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[-112,-64],\"parameters\":{\"text\":\"=You are an AI assistant that extracts meeting information from Calendly booking emails.\\nRead the email and return a structured JSON with the following fields:\\n- invitee_name\\n- invitee_email\\n- phone_number\\n- meeting_date (format YYYY-MM-DD)\\n- meeting_time (HH:mm)\\n- meeting_link\\n- meeting_goal\\n- needs_more_info (true/false)\\n- additional_info (brief summary if attendee provided extra notes)\\n\\nTime zone is always Eastern European Time (EET).\\nKeep the output strictly in JSON format, no additional text.\\nemail: {{ $json.textPlain }}\",\"options\":{},\"promptType\":\"define\",\"hasOutputParser\":true},\"typeVersion\":2.2,\"alwaysOutputData\":true}],\"active\":false,\"settings\":{\"callerPolicy\":\"workflowsFromSameOwner\",\"availableInMCP\":false,\"executionOrder\":\"v1\",\"saveExecutionProgress\":true,\"timeSavedPerExecution\":4},\"connections\":{\"LLM model\":{\"ai_languageModel\":[[{\"node\":\"extract from email\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Calculator\":{\"ai_tool\":[[{\"node\":\"extract from email\",\"type\":\"ai_tool\",\"index\":0}]]},\"When to send\":{\"main\":[[{\"node\":\"Wait to send 1h before meeting\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Wait to send 24h before meeting\",\"type\":\"main\",\"index\":0},{\"node\":\"Wait to send 1h before meeting after 24h\",\"type\":\"main\",\"index\":0}]]},\"extract from email\":{\"main\":[[{\"node\":\"Check if More Info is Needed\",\"type\":\"main\",\"index\":0},{\"node\":\"Calculate Waiting Time\",\"type\":\"main\",\"index\":0}]]},\"Notification received\":{\"main\":[[{\"node\":\"extract from email\",\"type\":\"main\",\"index\":0}]]},\"Calculate Waiting Time\":{\"main\":[[{\"node\":\"When to send\",\"type\":\"main\",\"index\":0}]]},\"Structured Output Parser\":{\"ai_outputParser\":[[{\"node\":\"extract from email\",\"type\":\"ai_outputParser\",\"index\":0}]]},\"Check if More Info is Needed\":{\"main\":[[{\"node\":\"Send Clarification request\",\"type\":\"main\",\"index\":0}],[]]},\"Wait to send 1h before meeting\":{\"main\":[[{\"node\":\"Send Reminder Email\",\"type\":\"main\",\"index\":0},{\"node\":\"Send WhatsApp Reminder\",\"type\":\"main\",\"index\":0}]]},\"Wait to send 24h before meeting\":{\"main\":[[{\"node\":\"Send Reminder Email\",\"type\":\"main\",\"index\":0},{\"node\":\"Send WhatsApp Reminder\",\"type\":\"main\",\"index\":0}]]},\"Wait to send 1h before meeting after 24h\":{\"main\":[[{\"node\":\"Send Reminder Email\",\"type\":\"main\",\"index\":0},{\"node\":\"Send WhatsApp Reminder\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 14, "node_types": {"emailSend": 2, "outputParserStructured": 1, "toolCalculator": 1, "emailReadImap": 1, "lmChatGoogleGemini": 1, "if": 2, "code": 1, "wait": 3, "twilio": 1, "agent": 1}, "services": ["ai", "google"], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Reduce Meeting No-Shows with Gemini AI, Email & WhatsApp Reminders for Calendly"}, {"role": "assistant", "content": "\n**Analyse du besoin**: How it works:\n\nThis n8n workflow automates communication with meeting invitees to decrease no-show rates by sending timely email and WhatsApp reminders, and a clarification request if more information...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 14 nodes utilisant ai, google.\nStructure: logique conditionnelle, code personnalisé, intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"QpilLWi7ZJID0IK3\",\"meta\":{\"instanceId\":\"e0abec5d9b13345e424c0dbbc512271f89fb17de3b268697e13a797de2271404\",\"templateCredsSetupCompleted\":true},\"name\":\"Decrease No-Shows from Calendly Meetings (Template)\",\"tags\":[],\"nodes\":[{\"id\":\"1fb2d001-2f04-4f5e-8f93-0c7668f246e0\",\"name\":\"Send Reminder Email\",\"type\":\"n8n-nodes-base.emailSend\",\"position\":[1680,-80],\"webhookId\":\"e971be6e-d7e5-4146-b974-93aa5491c0ac\",\"parameters\":{\"text\":\"Hi {{$json[\\\"invitee_name\\\"]}},\\\\n\\\\nJust a quick reminder about our strategy call scheduled for {{$json[\\\"meeting_time\\\"]}}, {{$json[\\\"meeting_date\\\"]}} (EET).\\\\n\\\\nWe'll discuss how to scale smarter with AI and data-driven systems.\\\\n\\\\nJoin via: {{$json[\\\"meeting_link\\\"]}}\\\\n\\\\nTalk soon,\\\\n[HOST_NAME]\",\"options\":{},\"subject\":\"Reminder: Your AI Strategy Call {{ $json.type === '24h' ? 'Tomorrow' : 'in 1 hour' }}\",\"toEmail\":\"={{ $('extract from email').item.json.output.invitee_email }}\",\"fromEmail\":\"[HOST_EMAIL]\"},\"typeVersion\":2},{\"id\":\"4ca79811-a7eb-42af-b461-f4166824172b\",\"name\":\"Structured Output Parser\",\"type\":\"@n8n/n8n-nodes-langchain.outputParserStructured\",\"position\":[96,160],\"parameters\":{\"jsonSchemaExample\":\"{\\n \\\"invitee_name\\\": \\\"string\\\",\\n \\\"invitee_email\\\": \\\"string\\\",\\n \\\"phone_number\\\": \\\"string\\\",\\n \\\"meeting_date\\\": \\\"date\\\",\\n \\\"meeting_time\\\": \\\"time\\\",\\n \\\"meeting_link\\\": \\\"string\\\",\\n \\\"meeting_goal\\\": \\\"string\\\",\\n \\\"needs_more_info\\\": \\\"boolean\\\",\\n \\\"additional_info\\\": \\\"string\\\"\\n}\\n\"},\"typeVersion\":1.3},{\"id\":\"12c9c9e9-9d62-4f69-83fb-ad4f16947201\",\"name\":\"Calculator\",\"type\":\"@n8n/n8n-nodes-langchain.toolCalculator\",\"position\":[-32,160],\"parameters\":{},\"typeVersion\":1},{\"id\":\"54205d4e-0f6c-4f54-acb0-4f98a5d2b326\",\"name\":\"Notification received\",\"type\":\"n8n-nodes-base.emailReadImap\",\"position\":[-384,-64],\"parameters\":{\"options\":{},\"postProcessAction\":\"nothing\"},\"typeVersion\":2.1},{\"id\":\"3a212390-ff8a-4d0b-8db1-7290a5a348fa\",\"name\":\"LLM model\",\"type\":\"@n8n/n8n-nodes-langchain.lmChatGoogleGemini\",\"position\":[-160,160],\"parameters\":{\"options\":{}},\"typeVersion\":1},{\"id\":\"f043a10a-ec90-4702-82fa-344ff68951be\",\"name\":\"Check if More Info is Needed\",\"type\":\"n8n-nodes-base.if\",\"position\":[304,-64],\"parameters\":{\"conditions\":{\"string\":[{\"value1\":\"={{ $json.output.needs_more_info }}\",\"value2\":\"true\"}]}},\"typeVersion\":1},{\"id\":\"252ae5b4-7342-41e1-861d-d9f091e391f2\",\"name\":\"Calculate Waiting Time\",\"type\":\"n8n-nodes-base.code\",\"position\":[800,-64],\"parameters\":{\"jsCode\":\"// === Parse email received date ===\\nconst emailReceivedStr = $('Notification received').first().json.date; // e.g., \\\"Tue, 28 Oct 2025 22:34:56 +0200\\\"\\nconst emailReceived = new Date(emailReceivedStr);\\n\\n// === Parse meeting date and time from Output Parser ===\\nconst meetingDateStr = $input.first().json.output.meeting_date; // e.g., \\\"2025-10-29\\\"\\nconst meetingTimeStr = $input.first().json.output.meeting_time; // e.g., \\\"16:00\\\"\\n\\n// === Combine meeting date and time with EET offset (+02:00) ===\\nconst meetingDateTime = new Date(`${meetingDateStr}T${meetingTimeStr}:00+02:00`);\\n\\n// === Calculate difference in hours between meeting and email received ===\\nconst diffHrs = (meetingDateTime - emailReceived) / (1000 * 60 * 60);\\n\\n// === Prepare wait times for reminders ===\\nconst waitOutput = {\\n wait_24h: 0, // Reminder 24h before meeting\\n wait_1h: 0 // Reminder 1h before meeting\\n};\\n\\n// If the difference is more than 24h, calculate 24h reminder\\nif (diffHrs > 24) {\\n waitOutput.wait_24h = Math.floor(diffHrs - 24);\\n}\\n\\n// If the difference is less than 24h, calculate 1h reminder\\nif (diffHrs < 24) {\\n waitOutput.wait_1h = Math.floor(diffHrs - 1);\\n}\\n\\n// Ensure both fields are numbers (null replaced with 0)\\nwaitOutput.wait_24h = waitOutput.wait_24h || 0;\\nwaitOutput.wait_1h = waitOutput.wait_1h || 0;\\n\\n// === Return JSON object ===\\nreturn [\\n {\\n json: waitOutput\\n }\\n];\\n\"},\"typeVersion\":2,\"alwaysOutputData\":true},{\"id\":\"edb48348-1a46-4486-8a2c-188bb8971b00\",\"name\":\"When to send\",\"type\":\"n8n-nodes-base.if\",\"position\":[1056,-64],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"5029e2f0-c526-4ff9-8b51-ce763c11bcba\",\"operator\":{\"type\":\"number\",\"operation\":\"equals\"},\"leftValue\":\"={{ $json.wait_24h }}\",\"rightValue\":0}]}},\"typeVersion\":2.2},{\"id\":\"902b64a0-ba2b-429e-af79-38327a4c6d7a\",\"name\":\"Wait to send 1h before meeting\",\"type\":\"n8n-nodes-base.wait\",\"position\":[1296,-256],\"webhookId\":\"45f9ddd0-f1a2-470e-b5fb-5cee857d81f6\",\"parameters\":{\"amount\":\"={{ $json.wait_24h }}\"},\"typeVersion\":1},{\"id\":\"841cafba-7dba-4fe7-adf3-57d68f00f51c\",\"name\":\"Wait to send 24h before meeting\",\"type\":\"n8n-nodes-base.wait\",\"position\":[1296,-16],\"webhookId\":\"588ef178-4da2-4808-91d3-7c02aa5f7a54\",\"parameters\":{\"amount\":\"={{ $('Calculate Waiting Time').item.json.wait_24h }}\"},\"typeVersion\":1},{\"id\":\"bcf10853-cb1b-43d7-b7b5-1a09ff272c08\",\"name\":\"Wait to send 1h before meeting after 24h\",\"type\":\"n8n-nodes-base.wait\",\"position\":[1296,224],\"webhookId\":\"f62dfee2-8297-431e-8c39-a6585b2bb7a5\",\"parameters\":{\"amount\":\"={{ $('Calculate Waiting Time').item.json.wait_1h }}+{{ $('Calculate Waiting Time').item.json.wait_24h }}\"},\"typeVersion\":1},{\"id\":\"8b82159a-c4ca-4efb-adc6-86b2df259d57\",\"name\":\"Send Clarification request\",\"type\":\"n8n-nodes-base.emailSend\",\"position\":[528,-80],\"webhookId\":\"74415f90-ca61-4aef-9a48-60ab3437519d\",\"parameters\":{\"text\":\"Hi {{$json[\\\"invitee_name\\\"]}},\\\\n\\\\nI noticed you mentioned '{{$json[\\\"additional_info\\\"]}}'. Could you please share more details before our call? This will help me tailor our session to your goals.\\\\n\\\\nLooking forward to our meeting,\\\\n\\\\n[HOST_NAME]\",\"options\":{},\"subject\":\"Quick question before our strategy call\",\"toEmail\":\"={{$json[\\\"invitee_email\\\"]}}\",\"fromEmail\":\"[HOST_EMAIL]\"},\"typeVersion\":2},{\"id\":\"cff10792-a670-4e93-983e-ecc3a5e4e664\",\"name\":\"Send WhatsApp Reminder\",\"type\":\"n8n-nodes-base.twilio\",\"position\":[1680,112],\"parameters\":{\"to\":\"=whatsapp:={{ $('extract from email').item.json.output.phone_number.replace(/\\\\s+/g,'').replace('+','') }}\",\"from\":\"whatsapp:[TWILIO_WHATSAPP_FROM]\",\"message\":\"Hi {{ $('analyze email').item.json.output.invitee_name }}, just a reminder that your AI strategy call is {{ $('analyze email').item.json.output.meeting_date }} @ {{ $('analyze email').item.json.output.meeting_time }} (EET).\\\\nJoin via: {{ $('analyze email').item.json.output.meeting_link }}\\\\nLooking forward! - [HOST_NAME]\",\"options\":{}},\"typeVersion\":1},{\"id\":\"3701bdb4-d51e-4e4c-b252-c8f6b1abfde6\",\"name\":\"extract from email\",\"type\":\"@n8n/n8n-nodes-langchain.agent\",\"position\":[-112,-64],\"parameters\":{\"text\":\"=You are an AI assistant that extracts meeting information from Calendly booking emails.\\nRead the email and return a structured JSON with the following fields:\\n- invitee_name\\n- invitee_email\\n- phone_number\\n- meeting_date (format YYYY-MM-DD)\\n- meeting_time (HH:mm)\\n- meeting_link\\n- meeting_goal\\n- needs_more_info (true/false)\\n- additional_info (brief summary if attendee provided extra notes)\\n\\nTime zone is always Eastern European Time (EET).\\nKeep the output strictly in JSON format, no additional text.\\nemail: {{ $json.textPlain }}\",\"options\":{},\"promptType\":\"define\",\"hasOutputParser\":true},\"typeVersion\":2.2,\"alwaysOutputData\":true}],\"active\":false,\"settings\":{\"callerPolicy\":\"workflowsFromSameOwner\",\"availableInMCP\":false,\"executionOrder\":\"v1\",\"saveExecutionProgress\":true,\"timeSavedPerExecution\":4},\"connections\":{\"LLM model\":{\"ai_languageModel\":[[{\"node\":\"extract from email\",\"type\":\"ai_languageModel\",\"index\":0}]]},\"Calculator\":{\"ai_tool\":[[{\"node\":\"extract from email\",\"type\":\"ai_tool\",\"index\":0}]]},\"When to send\":{\"main\":[[{\"node\":\"Wait to send 1h before meeting\",\"type\":\"main\",\"index\":0}],[{\"node\":\"Wait to send 24h before meeting\",\"type\":\"main\",\"index\":0},{\"node\":\"Wait to send 1h before meeting after 24h\",\"type\":\"main\",\"index\":0}]]},\"extract from email\":{\"main\":[[{\"node\":\"Check if More Info is Needed\",\"type\":\"main\",\"index\":0},{\"node\":\"Calculate Waiting Time\",\"type\":\"main\",\"index\":0}]]},\"Notification received\":{\"main\":[[{\"node\":\"extract from email\",\"type\":\"main\",\"index\":0}]]},\"Calculate Waiting Time\":{\"main\":[[{\"node\":\"When to send\",\"type\":\"main\",\"index\":0}]]},\"Structured Output Parser\":{\"ai_outputParser\":[[{\"node\":\"extract from email\",\"type\":\"ai_outputParser\",\"index\":0}]]},\"Check if More Info is Needed\":{\"main\":[[{\"node\":\"Send Clarification request\",\"type\":\"main\",\"index\":0}],[]]},\"Wait to send 1h before meeting\":{\"main\":[[{\"node\":\"Send Reminder Email\",\"type\":\"main\",\"index\":0},{\"node\":\"Send WhatsApp Reminder\",\"type\":\"main\",\"index\":0}]]},\"Wait to send 24h before meeting\":{\"main\":[[{\"node\":\"Send Reminder Email\",\"type\":\"main\",\"index\":0},{\"node\":\"Send WhatsApp Reminder\",\"type\":\"main\",\"index\":0}]]},\"Wait to send 1h before meeting after 24h\":{\"main\":[[{\"node\":\"Send Reminder Email\",\"type\":\"main\",\"index\":0},{\"node\":\"Send WhatsApp Reminder\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 14, "node_types": {"emailSend": 2, "outputParserStructured": 1, "toolCalculator": 1, "emailReadImap": 1, "lmChatGoogleGemini": 1, "if": 2, "code": 1, "wait": 3, "twilio": 1, "agent": 1}, "services": ["ai", "google"], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": true, "has_ai": true}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: 🔐 Advanced SSL Health Monitor 👤 Who is this for? This workflow is designed for DevOps engineers, IT administrators, and security professionals who need comprehensive SSL certificate monitoring and health assessment across multiple domains — featuring dual verification and professional reporting without relying on expensive monitoring services. 🧩 What It Does Daily Trigger runs the workflow every morning for proactive monitoring. URL Collection fetches the list of website URLs to monitor from your data source. Dual SSL Analysis: Free SSL Assessment Script — Get from sysadmin-toolkit on Github SSL-Checker.io API — External verification for cross-validation Comprehensive Health Check: Certificate expiration monitoring (customizable threshold) SSL configuration security assessment Protocol sup"}, {"role": "assistant", "content": "\n**Analyse du besoin**: 🔐 Advanced SSL Health Monitor\n👤 Who is this for?\nThis workflow is designed for DevOps engineers, IT administrators, and security professionals who need comprehensive SSL certificate monitoring and hea...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 8 nodes utilisant http.\nStructure: logique conditionnelle, code personnalisé, flux standard.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"REwp6JdhNjvbGQ1J\",\"meta\":{\"instanceId\":\"0728bbcb360bfc31668af41e0b3086e417a4d7ae6718b1f1eb6ce6f25309b188\"},\"name\":\"My workflow\",\"tags\":[],\"nodes\":[{\"id\":\"106c2b40-43f5-432d-9fdd-446e7309abc7\",\"name\":\"Check SSL\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[2300,580],\"parameters\":{\"url\":\"=https://ssl-checker.io/api/v1/check/{{ $json[\\\"property_domains\\\"].replace(/^https?:\\\\/\\\\//, \\\"\\\").replace(/\\\\/$/, \\\"\\\") }}\",\"options\":{}},\"typeVersion\":4.2},{\"id\":\"92e421ce-6f88-44d4-9018-8b39e9fad396\",\"name\":\"Expiry Alert\",\"type\":\"n8n-nodes-base.if\",\"position\":[2660,580],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"ee6e2ce8-569a-4f1f-91b5-2c55f605a16b\",\"operator\":{\"type\":\"number\",\"operation\":\"lte\"},\"leftValue\":\"={{ $json.result.days_left }}\",\"rightValue\":7},{\"id\":\"d82f8203-0908-4a48-9eb7-48e11555c1c2\",\"operator\":{\"name\":\"filter.operator.equals\",\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2},{\"id\":\"bafe935b-b283-428f-934a-49d03de5d38f\",\"name\":\"Daily Trigger\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"position\":[1620,960],\"parameters\":{\"rule\":{\"interval\":[{\"triggerAtHour\":10}]}},\"typeVersion\":1.2},{\"id\":\"e5ef4591-f45c-4712-97b4-0d7a520c238d\",\"name\":\"SSH - Analyze system\",\"type\":\"n8n-nodes-base.ssh\",\"position\":[2380,1340],\"parameters\":{\"command\":\"=node /opt/sysadmin-toolkit/scripts/ssl/ssl-health-assessment.js {{ $json.property_domains }} --json\",\"authentication\":\"privateKey\"},\"typeVersion\":1,\"alwaysOutputData\":true},{\"id\":\"240f78ee-96ab-4f53-bb9c-c40e0f8d0961\",\"name\":\"Discord\",\"type\":\"n8n-nodes-base.discord\",\"position\":[2980,1340],\"webhookId\":\"6e1014b5-d89d-4939-a1f3-b74c280ae73b\",\"parameters\":{\"content\":\"={{ $json.discord.title }}\\n\\n{{ $json.discord.fullDescription }}\",\"guildId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1254730427805990942\",\"cachedResultUrl\":\"https://discord.com/channels/1254730427805990942\",\"cachedResultName\":\"b0ld8\"},\"options\":{},\"resource\":\"message\",\"channelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1254730427805990945\",\"cachedResultUrl\":\"https://discord.com/channels/1254730427805990942/1254730427805990945\",\"cachedResultName\":\"general\"}},\"typeVersion\":2},{\"id\":\"edc63e4c-8a87-4fbb-ba61-195b3e587965\",\"name\":\"Discord1\",\"type\":\"n8n-nodes-base.discord\",\"position\":[3000,560],\"webhookId\":\"6e1014b5-d89d-4939-a1f3-b74c280ae73b\",\"parameters\":{\"content\":\"=SSL Expiry - {{ $json.result.days_left }} days Left - {{ $json.result.host }}\",\"guildId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1254730427805990942\",\"cachedResultUrl\":\"https://discord.com/channels/1254730427805990942\",\"cachedResultName\":\"b0ld8\"},\"options\":{},\"resource\":\"message\",\"channelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1254730427805990945\",\"cachedResultUrl\":\"https://discord.com/channels/1254730427805990942/1254730427805990945\",\"cachedResultName\":\"general\"}},\"typeVersion\":2},{\"id\":\"c58aad29-de35-46e1-b43a-dfcfac0cffc2\",\"name\":\"Fetch domains to check SSL\",\"type\":\"n8n-nodes-base.notion\",\"position\":[1920,960],\"parameters\":{\"options\":{},\"resource\":\"databasePage\",\"operation\":\"getAll\",\"returnAll\":true,\"databaseId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"22612359-20f8-80f4-897f-eae0ad313057\",\"cachedResultUrl\":\"https://www.notion.so/2261235920f880f4897feae0ad313057\",\"cachedResultName\":\"n8n flow - SSL Certificate Expiry Monitoring\"},\"filterType\":\"manual\"},\"typeVersion\":2.2},{\"id\":\"b544b226-ceb6-439d-b350-4e77b39e2fde\",\"name\":\"Code - Format output\",\"type\":\"n8n-nodes-base.code\",\"position\":[2620,1340],\"parameters\":{\"jsCode\":\"// n8n Code Node - Parse SSL Scanner Output\\n// This code processes the SSH node output and formats it for Discord notifications\\n\\nconst results = [];\\n\\nfor (const item of $input.all()) {\\n try {\\n // Extract the stdout from SSH response\\n const sshOutput = item.json;\\n \\n // Check if SSH command was successful\\n if (sshOutput.code !== 0) {\\n results.push({\\n json: {\\n hostname: 'unknown',\\n status: 'error',\\n error: sshOutput.stderr || 'SSH command failed',\\n alert: true,\\n alertLevel: 'critical'\\n }\\n });\\n continue;\\n }\\n \\n // Parse the JSON output from stdout\\n let sslData;\\n try {\\n sslData = JSON.parse(sshOutput.stdout);\\n } catch (parseError) {\\n results.push({\\n json: {\\n hostname: 'unknown',\\n status: 'error',\\n error: 'Failed to parse SSL scanner output',\\n alert: true,\\n alertLevel: 'critical'\\n }\\n });\\n continue;\\n }\\n \\n // Extract key information for Discord notification\\n const parsedResult = {\\n // Basic info\\n hostname: sslData.hostname,\\n port: sslData.port || 443,\\n scanTime: sslData.scanTime,\\n scanDuration: sslData.scanDuration,\\n \\n // Overall status\\n overallGrade: sslData.overallGrade,\\n connectionStatus: sslData.connectionStatus || 'unknown',\\n success: sslData.success || false,\\n \\n // Certificate info\\n certificate: {\\n subject: sslData.certificate?.subject || 'unknown',\\n issuer: sslData.certificate?.issuer || 'unknown',\\n validUntil: sslData.certificate?.validUntil,\\n daysUntilExpiry: sslData.certificate?.daysUntilExpiry,\\n isValid: sslData.certificate?.isValid || false,\\n issues: sslData.certificate?.issues || [],\\n hostnameMatch: sslData.certificate?.hostnameMatch || false\\n },\\n \\n // Protocol support\\n protocols: {\\n tls13: sslData.protocols?.tls13 || false,\\n tls12: sslData.protocols?.tls12 || false,\\n tls11: sslData.protocols?.tls11 || false,\\n tls10: sslData.protocols?.tls10 || false,\\n ssl3: sslData.protocols?.ssl3 || false\\n },\\n \\n // Security info\\n vulnerabilities: {\\n hasVulnerabilities: sslData.vulnerabilities?.hasVulnerabilities || false,\\n poodle: sslData.vulnerabilities?.poodle || false,\\n freak: sslData.vulnerabilities?.freak || false,\\n details: sslData.vulnerabilities || {}\\n },\\n \\n // Grades breakdown\\n grades: sslData.grades || {},\\n \\n // Recommendations\\n recommendations: sslData.recommendations || [],\\n \\n // Error handling\\n error: sslData.error,\\n \\n // Alert logic\\n alert: false,\\n alertLevel: 'info',\\n alertReasons: []\\n };\\n \\n // Determine if this needs an alert\\n const alertReasons = [];\\n let alertLevel = 'info';\\n \\n // Critical alerts\\n if (sslData.error) {\\n alertReasons.push(`Scan failed: ${sslData.error}`);\\n alertLevel = 'critical';\\n }\\n \\n if (!parsedResult.certificate.isValid) {\\n alertReasons.push('Certificate is invalid');\\n alertLevel = 'critical';\\n }\\n \\n if (parsedResult.certificate.daysUntilExpiry <= 0) {\\n alertReasons.push('Certificate has expired');\\n alertLevel = 'critical';\\n }\\n \\n // High priority alerts\\n if (parsedResult.certificate.daysUntilExpiry <= 7 && parsedResult.certificate.daysUntilExpiry > 0) {\\n alertReasons.push(`Certificate expires in ${parsedResult.certificate.daysUntilExpiry} days`);\\n if (alertLevel === 'info') alertLevel = 'high';\\n }\\n \\n if (parsedResult.vulnerabilities.hasVulnerabilities) {\\n alertReasons.push('Security vulnerabilities detected');\\n if (alertLevel === 'info') alertLevel = 'high';\\n }\\n \\n if (!parsedResult.certificate.hostnameMatch) {\\n alertReasons.push('Hostname mismatch detected');\\n if (alertLevel === 'info') alertLevel = 'high';\\n }\\n \\n // Medium priority alerts\\n if (parsedResult.certificate.daysUntilExpiry <= 30 && parsedResult.certificate.daysUntilExpiry > 7) {\\n alertReasons.push(`Certificate expires in ${parsedResult.certificate.daysUntilExpiry} days`);\\n if (alertLevel === 'info') alertLevel = 'medium';\\n }\\n \\n if (['C', 'D', 'F'].includes(parsedResult.overallGrade)) {\\n alertReasons.push(`Poor SSL grade: ${parsedResult.overallGrade}`);\\n if (alertLevel === 'info') alertLevel = 'medium';\\n }\\n \\n if (parsedResult.protocols.ssl3 || parsedResult.protocols.tls10) {\\n alertReasons.push('Deprecated protocols enabled');\\n if (alertLevel === 'info') alertLevel = 'medium';\\n }\\n \\n // Low priority alerts\\n if (parsedResult.recommendations && parsedResult.recommendations.length > 0) {\\n alertReasons.push(`${parsedResult.recommendations.length} recommendations available`);\\n if (alertLevel === 'info') alertLevel = 'low';\\n }\\n \\n // Set alert status\\n parsedResult.alert = alertReasons.length > 0;\\n parsedResult.alertLevel = alertLevel;\\n parsedResult.alertReasons = alertReasons;\\n \\n // Add Discord formatting helpers\\n parsedResult.discord = {\\n color: getDiscordColor(alertLevel, parsedResult.overallGrade),\\n title: `SSL Health Check: ${parsedResult.hostname}`,\\n description: getDiscordDescription(parsedResult),\\n fields: getDiscordFields(parsedResult),\\n timestamp: new Date().toISOString(),\\n \\n // Pre-formatted content for easy Discord input\\n content: alertLevel === 'critical' ? '@here 🚨 SSL Health Monitor Alert' : '🔐 SSL Health Monitor Alert',\\n \\n // Simple descriptions without complex logic\\n simpleDescription: parsedResult.alert \\n ? `⚠️ SSL issues detected for ${parsedResult.hostname}`\\n : `✅ SSL looks healthy for ${parsedResult.hostname}`,\\n \\n // Detailed info as simple strings\\n certificateInfo: `Grade: ${parsedResult.overallGrade} | Expires in ${parsedResult.certificate.daysUntilExpiry} days`,\\n \\n // Alert details as simple string\\n alertSummary: parsedResult.alert \\n ? `Issues: ${parsedResult.alertReasons.join(', ')}`\\n : `Certificate expires ${parsedResult.certificate.validUntil}`,\\n \\n // Complete formatted description\\n fullDescription: getFullDiscordDescription(parsedResult)\\n };\\n \\n results.push({ json: parsedResult });\\n \\n } catch (error) {\\n // Handle any unexpected errors\\n results.push({\\n json: {\\n hostname: 'unknown',\\n status: 'error',\\n error: `Processing error: ${error.message}`,\\n alert: true,\\n alertLevel: 'critical'\\n }\\n });\\n }\\n}\\n\\n// Helper functions for Discord formatting\\nfunction getDiscordColor(alertLevel, grade) {\\n // Color mapping for Discord embeds\\n const colors = {\\n critical: 15158332, // Red\\n high: 15105570, // Orange\\n medium: 15844367, // Yellow\\n low: 5763719, // Blue\\n info: 5763719 // Blue\\n };\\n \\n // Grade-based colors for non-alerts\\n const gradeColors = {\\n 'A+': 5763719, // Green\\n 'A': 3066993, // Green\\n 'B': 15844367, // Yellow\\n 'C': 15105570, // Orange\\n 'D': 15158332, // Red\\n 'F': 10038562 // Dark Red\\n };\\n \\n if (alertLevel !== 'info') {\\n return colors[alertLevel] || colors.info;\\n }\\n \\n return gradeColors[grade] || colors.info;\\n}\\n\\nfunction getFullDiscordDescription(result) {\\n if (result.error) {\\n return `❌ SSL scan failed: ${result.error}`;\\n }\\n \\n if (result.alert) {\\n let description = `⚠️ SSL issues detected for ${result.hostname}\\\\n`;\\n description += `Grade: ${result.overallGrade} | Expires in ${result.certificate.daysUntilExpiry} days\\\\n\\\\n`;\\n description += `Issues found:\\\\n`;\\n result.alertReasons.forEach(reason => {\\n description += `• ${reason}\\\\n`;\\n });\\n return description.trim();\\n }\\n \\n return `✅ SSL configuration looks good for ${result.hostname}\\\\nGrade: ${result.overallGrade} | Certificate expires in ${result.certificate.daysUntilExpiry} days`;\\n}\\n\\nfunction getDiscordDescription(result) {\\n if (result.error) {\\n return `❌ SSL scan failed: ${result.error}`;\\n }\\n \\n if (result.alert) {\\n // Create simple alert description\\n let description = \\\"⚠️ SSL issues detected:\\\\n\\\";\\n result.alertReasons.forEach(reason => {\\n description += `• ${reason}\\\\n`;\\n });\\n return description.trim();\\n }\\n \\n return `✅ SSL configuration looks good\\\\nGrade: ${result.overallGrade} | Expires in ${result.certificate.daysUntilExpiry} days`;\\n}\\n\\nfunction getDiscordFields(result) {\\n const fields = [];\\n \\n // Certificate info\\n fields.push({\\n name: \\\"📜 Certificate\\\",\\n value: [\\n `**Subject:** ${result.certificate.subject}`,\\n `**Issuer:** ${result.certificate.issuer}`,\\n `**Expires:** ${new Date(result.certificate.validUntil).toLocaleDateString()}`,\\n `**Days Left:** ${result.certificate.daysUntilExpiry}`\\n ].join('\\\\n'),\\n inline: true\\n });\\n \\n // Security info\\n fields.push({\\n name: \\\"🔐 Security\\\",\\n value: [\\n `**Overall Grade:** ${result.overallGrade}`,\\n `**TLS 1.2:** ${result.protocols.tls12 ? '✅' : '❌'}`,\\n `**TLS 1.3:** ${result.protocols.tls13 ? '✅' : '❌'}`,\\n `**Vulnerabilities:** ${result.vulnerabilities.hasVulnerabilities ? '⚠️ Found' : '✅ None'}`\\n ].join('\\\\n'),\\n inline: true\\n });\\n \\n // Add recommendations if any\\n if (result.recommendations.length > 0) {\\n fields.push({\\n name: \\\"💡 Recommendations\\\",\\n value: result.recommendations.slice(0, 3).map(rec => `• ${rec.message || rec}`).join('\\\\n') + \\n (result.recommendations.length > 3 ? `\\\\n... and ${result.recommendations.length - 3} more` : ''),\\n inline: false\\n });\\n }\\n \\n return fields;\\n}\\n\\nreturn results;\"},\"typeVersion\":2}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Check SSL\":{\"main\":[[{\"node\":\"Expiry Alert\",\"type\":\"main\",\"index\":0}]]},\"Expiry Alert\":{\"main\":[[{\"node\":\"Discord1\",\"type\":\"main\",\"index\":0}]]},\"Daily Trigger\":{\"main\":[[{\"node\":\"Fetch domains to check SSL\",\"type\":\"main\",\"index\":0}]]},\"Code - Format output\":{\"main\":[[{\"node\":\"Discord\",\"type\":\"main\",\"index\":0}]]},\"SSH - Analyze system\":{\"main\":[[{\"node\":\"Code - Format output\",\"type\":\"main\",\"index\":0}]]},\"Fetch domains to check SSL\":{\"main\":[[{\"node\":\"SSH - Analyze system\",\"type\":\"main\",\"index\":0},{\"node\":\"Check SSL\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 8, "node_types": {"httpRequest": 1, "if": 1, "scheduleTrigger": 1, "ssh": 1, "discord": 2, "notion": 1, "code": 1}, "services": ["http"], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": true, "has_ai": false}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Génère un workflow n8n: Comprehensive SSL Certificate Monitoring with Discord Alerts and Notion Integration"}, {"role": "assistant", "content": "\n**Analyse du besoin**: 🔐 Advanced SSL Health Monitor\n👤 Who is this for?\nThis workflow is designed for DevOps engineers, IT administrators, and security professionals who need comprehensive SSL certificate monitoring and hea...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 8 nodes utilisant http.\nStructure: logique conditionnelle, code personnalisé, flux standard.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"id\":\"REwp6JdhNjvbGQ1J\",\"meta\":{\"instanceId\":\"0728bbcb360bfc31668af41e0b3086e417a4d7ae6718b1f1eb6ce6f25309b188\"},\"name\":\"My workflow\",\"tags\":[],\"nodes\":[{\"id\":\"106c2b40-43f5-432d-9fdd-446e7309abc7\",\"name\":\"Check SSL\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[2300,580],\"parameters\":{\"url\":\"=https://ssl-checker.io/api/v1/check/{{ $json[\\\"property_domains\\\"].replace(/^https?:\\\\/\\\\//, \\\"\\\").replace(/\\\\/$/, \\\"\\\") }}\",\"options\":{}},\"typeVersion\":4.2},{\"id\":\"92e421ce-6f88-44d4-9018-8b39e9fad396\",\"name\":\"Expiry Alert\",\"type\":\"n8n-nodes-base.if\",\"position\":[2660,580],\"parameters\":{\"options\":{},\"conditions\":{\"options\":{\"version\":2,\"leftValue\":\"\",\"caseSensitive\":true,\"typeValidation\":\"strict\"},\"combinator\":\"and\",\"conditions\":[{\"id\":\"ee6e2ce8-569a-4f1f-91b5-2c55f605a16b\",\"operator\":{\"type\":\"number\",\"operation\":\"lte\"},\"leftValue\":\"={{ $json.result.days_left }}\",\"rightValue\":7},{\"id\":\"d82f8203-0908-4a48-9eb7-48e11555c1c2\",\"operator\":{\"name\":\"filter.operator.equals\",\"type\":\"string\",\"operation\":\"equals\"},\"leftValue\":\"\",\"rightValue\":\"\"}]}},\"typeVersion\":2.2},{\"id\":\"bafe935b-b283-428f-934a-49d03de5d38f\",\"name\":\"Daily Trigger\",\"type\":\"n8n-nodes-base.scheduleTrigger\",\"position\":[1620,960],\"parameters\":{\"rule\":{\"interval\":[{\"triggerAtHour\":10}]}},\"typeVersion\":1.2},{\"id\":\"e5ef4591-f45c-4712-97b4-0d7a520c238d\",\"name\":\"SSH - Analyze system\",\"type\":\"n8n-nodes-base.ssh\",\"position\":[2380,1340],\"parameters\":{\"command\":\"=node /opt/sysadmin-toolkit/scripts/ssl/ssl-health-assessment.js {{ $json.property_domains }} --json\",\"authentication\":\"privateKey\"},\"typeVersion\":1,\"alwaysOutputData\":true},{\"id\":\"240f78ee-96ab-4f53-bb9c-c40e0f8d0961\",\"name\":\"Discord\",\"type\":\"n8n-nodes-base.discord\",\"position\":[2980,1340],\"webhookId\":\"6e1014b5-d89d-4939-a1f3-b74c280ae73b\",\"parameters\":{\"content\":\"={{ $json.discord.title }}\\n\\n{{ $json.discord.fullDescription }}\",\"guildId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1254730427805990942\",\"cachedResultUrl\":\"https://discord.com/channels/1254730427805990942\",\"cachedResultName\":\"b0ld8\"},\"options\":{},\"resource\":\"message\",\"channelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1254730427805990945\",\"cachedResultUrl\":\"https://discord.com/channels/1254730427805990942/1254730427805990945\",\"cachedResultName\":\"general\"}},\"typeVersion\":2},{\"id\":\"edc63e4c-8a87-4fbb-ba61-195b3e587965\",\"name\":\"Discord1\",\"type\":\"n8n-nodes-base.discord\",\"position\":[3000,560],\"webhookId\":\"6e1014b5-d89d-4939-a1f3-b74c280ae73b\",\"parameters\":{\"content\":\"=SSL Expiry - {{ $json.result.days_left }} days Left - {{ $json.result.host }}\",\"guildId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1254730427805990942\",\"cachedResultUrl\":\"https://discord.com/channels/1254730427805990942\",\"cachedResultName\":\"b0ld8\"},\"options\":{},\"resource\":\"message\",\"channelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"1254730427805990945\",\"cachedResultUrl\":\"https://discord.com/channels/1254730427805990942/1254730427805990945\",\"cachedResultName\":\"general\"}},\"typeVersion\":2},{\"id\":\"c58aad29-de35-46e1-b43a-dfcfac0cffc2\",\"name\":\"Fetch domains to check SSL\",\"type\":\"n8n-nodes-base.notion\",\"position\":[1920,960],\"parameters\":{\"options\":{},\"resource\":\"databasePage\",\"operation\":\"getAll\",\"returnAll\":true,\"databaseId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"22612359-20f8-80f4-897f-eae0ad313057\",\"cachedResultUrl\":\"https://www.notion.so/2261235920f880f4897feae0ad313057\",\"cachedResultName\":\"n8n flow - SSL Certificate Expiry Monitoring\"},\"filterType\":\"manual\"},\"typeVersion\":2.2},{\"id\":\"b544b226-ceb6-439d-b350-4e77b39e2fde\",\"name\":\"Code - Format output\",\"type\":\"n8n-nodes-base.code\",\"position\":[2620,1340],\"parameters\":{\"jsCode\":\"// n8n Code Node - Parse SSL Scanner Output\\n// This code processes the SSH node output and formats it for Discord notifications\\n\\nconst results = [];\\n\\nfor (const item of $input.all()) {\\n try {\\n // Extract the stdout from SSH response\\n const sshOutput = item.json;\\n \\n // Check if SSH command was successful\\n if (sshOutput.code !== 0) {\\n results.push({\\n json: {\\n hostname: 'unknown',\\n status: 'error',\\n error: sshOutput.stderr || 'SSH command failed',\\n alert: true,\\n alertLevel: 'critical'\\n }\\n });\\n continue;\\n }\\n \\n // Parse the JSON output from stdout\\n let sslData;\\n try {\\n sslData = JSON.parse(sshOutput.stdout);\\n } catch (parseError) {\\n results.push({\\n json: {\\n hostname: 'unknown',\\n status: 'error',\\n error: 'Failed to parse SSL scanner output',\\n alert: true,\\n alertLevel: 'critical'\\n }\\n });\\n continue;\\n }\\n \\n // Extract key information for Discord notification\\n const parsedResult = {\\n // Basic info\\n hostname: sslData.hostname,\\n port: sslData.port || 443,\\n scanTime: sslData.scanTime,\\n scanDuration: sslData.scanDuration,\\n \\n // Overall status\\n overallGrade: sslData.overallGrade,\\n connectionStatus: sslData.connectionStatus || 'unknown',\\n success: sslData.success || false,\\n \\n // Certificate info\\n certificate: {\\n subject: sslData.certificate?.subject || 'unknown',\\n issuer: sslData.certificate?.issuer || 'unknown',\\n validUntil: sslData.certificate?.validUntil,\\n daysUntilExpiry: sslData.certificate?.daysUntilExpiry,\\n isValid: sslData.certificate?.isValid || false,\\n issues: sslData.certificate?.issues || [],\\n hostnameMatch: sslData.certificate?.hostnameMatch || false\\n },\\n \\n // Protocol support\\n protocols: {\\n tls13: sslData.protocols?.tls13 || false,\\n tls12: sslData.protocols?.tls12 || false,\\n tls11: sslData.protocols?.tls11 || false,\\n tls10: sslData.protocols?.tls10 || false,\\n ssl3: sslData.protocols?.ssl3 || false\\n },\\n \\n // Security info\\n vulnerabilities: {\\n hasVulnerabilities: sslData.vulnerabilities?.hasVulnerabilities || false,\\n poodle: sslData.vulnerabilities?.poodle || false,\\n freak: sslData.vulnerabilities?.freak || false,\\n details: sslData.vulnerabilities || {}\\n },\\n \\n // Grades breakdown\\n grades: sslData.grades || {},\\n \\n // Recommendations\\n recommendations: sslData.recommendations || [],\\n \\n // Error handling\\n error: sslData.error,\\n \\n // Alert logic\\n alert: false,\\n alertLevel: 'info',\\n alertReasons: []\\n };\\n \\n // Determine if this needs an alert\\n const alertReasons = [];\\n let alertLevel = 'info';\\n \\n // Critical alerts\\n if (sslData.error) {\\n alertReasons.push(`Scan failed: ${sslData.error}`);\\n alertLevel = 'critical';\\n }\\n \\n if (!parsedResult.certificate.isValid) {\\n alertReasons.push('Certificate is invalid');\\n alertLevel = 'critical';\\n }\\n \\n if (parsedResult.certificate.daysUntilExpiry <= 0) {\\n alertReasons.push('Certificate has expired');\\n alertLevel = 'critical';\\n }\\n \\n // High priority alerts\\n if (parsedResult.certificate.daysUntilExpiry <= 7 && parsedResult.certificate.daysUntilExpiry > 0) {\\n alertReasons.push(`Certificate expires in ${parsedResult.certificate.daysUntilExpiry} days`);\\n if (alertLevel === 'info') alertLevel = 'high';\\n }\\n \\n if (parsedResult.vulnerabilities.hasVulnerabilities) {\\n alertReasons.push('Security vulnerabilities detected');\\n if (alertLevel === 'info') alertLevel = 'high';\\n }\\n \\n if (!parsedResult.certificate.hostnameMatch) {\\n alertReasons.push('Hostname mismatch detected');\\n if (alertLevel === 'info') alertLevel = 'high';\\n }\\n \\n // Medium priority alerts\\n if (parsedResult.certificate.daysUntilExpiry <= 30 && parsedResult.certificate.daysUntilExpiry > 7) {\\n alertReasons.push(`Certificate expires in ${parsedResult.certificate.daysUntilExpiry} days`);\\n if (alertLevel === 'info') alertLevel = 'medium';\\n }\\n \\n if (['C', 'D', 'F'].includes(parsedResult.overallGrade)) {\\n alertReasons.push(`Poor SSL grade: ${parsedResult.overallGrade}`);\\n if (alertLevel === 'info') alertLevel = 'medium';\\n }\\n \\n if (parsedResult.protocols.ssl3 || parsedResult.protocols.tls10) {\\n alertReasons.push('Deprecated protocols enabled');\\n if (alertLevel === 'info') alertLevel = 'medium';\\n }\\n \\n // Low priority alerts\\n if (parsedResult.recommendations && parsedResult.recommendations.length > 0) {\\n alertReasons.push(`${parsedResult.recommendations.length} recommendations available`);\\n if (alertLevel === 'info') alertLevel = 'low';\\n }\\n \\n // Set alert status\\n parsedResult.alert = alertReasons.length > 0;\\n parsedResult.alertLevel = alertLevel;\\n parsedResult.alertReasons = alertReasons;\\n \\n // Add Discord formatting helpers\\n parsedResult.discord = {\\n color: getDiscordColor(alertLevel, parsedResult.overallGrade),\\n title: `SSL Health Check: ${parsedResult.hostname}`,\\n description: getDiscordDescription(parsedResult),\\n fields: getDiscordFields(parsedResult),\\n timestamp: new Date().toISOString(),\\n \\n // Pre-formatted content for easy Discord input\\n content: alertLevel === 'critical' ? '@here 🚨 SSL Health Monitor Alert' : '🔐 SSL Health Monitor Alert',\\n \\n // Simple descriptions without complex logic\\n simpleDescription: parsedResult.alert \\n ? `⚠️ SSL issues detected for ${parsedResult.hostname}`\\n : `✅ SSL looks healthy for ${parsedResult.hostname}`,\\n \\n // Detailed info as simple strings\\n certificateInfo: `Grade: ${parsedResult.overallGrade} | Expires in ${parsedResult.certificate.daysUntilExpiry} days`,\\n \\n // Alert details as simple string\\n alertSummary: parsedResult.alert \\n ? `Issues: ${parsedResult.alertReasons.join(', ')}`\\n : `Certificate expires ${parsedResult.certificate.validUntil}`,\\n \\n // Complete formatted description\\n fullDescription: getFullDiscordDescription(parsedResult)\\n };\\n \\n results.push({ json: parsedResult });\\n \\n } catch (error) {\\n // Handle any unexpected errors\\n results.push({\\n json: {\\n hostname: 'unknown',\\n status: 'error',\\n error: `Processing error: ${error.message}`,\\n alert: true,\\n alertLevel: 'critical'\\n }\\n });\\n }\\n}\\n\\n// Helper functions for Discord formatting\\nfunction getDiscordColor(alertLevel, grade) {\\n // Color mapping for Discord embeds\\n const colors = {\\n critical: 15158332, // Red\\n high: 15105570, // Orange\\n medium: 15844367, // Yellow\\n low: 5763719, // Blue\\n info: 5763719 // Blue\\n };\\n \\n // Grade-based colors for non-alerts\\n const gradeColors = {\\n 'A+': 5763719, // Green\\n 'A': 3066993, // Green\\n 'B': 15844367, // Yellow\\n 'C': 15105570, // Orange\\n 'D': 15158332, // Red\\n 'F': 10038562 // Dark Red\\n };\\n \\n if (alertLevel !== 'info') {\\n return colors[alertLevel] || colors.info;\\n }\\n \\n return gradeColors[grade] || colors.info;\\n}\\n\\nfunction getFullDiscordDescription(result) {\\n if (result.error) {\\n return `❌ SSL scan failed: ${result.error}`;\\n }\\n \\n if (result.alert) {\\n let description = `⚠️ SSL issues detected for ${result.hostname}\\\\n`;\\n description += `Grade: ${result.overallGrade} | Expires in ${result.certificate.daysUntilExpiry} days\\\\n\\\\n`;\\n description += `Issues found:\\\\n`;\\n result.alertReasons.forEach(reason => {\\n description += `• ${reason}\\\\n`;\\n });\\n return description.trim();\\n }\\n \\n return `✅ SSL configuration looks good for ${result.hostname}\\\\nGrade: ${result.overallGrade} | Certificate expires in ${result.certificate.daysUntilExpiry} days`;\\n}\\n\\nfunction getDiscordDescription(result) {\\n if (result.error) {\\n return `❌ SSL scan failed: ${result.error}`;\\n }\\n \\n if (result.alert) {\\n // Create simple alert description\\n let description = \\\"⚠️ SSL issues detected:\\\\n\\\";\\n result.alertReasons.forEach(reason => {\\n description += `• ${reason}\\\\n`;\\n });\\n return description.trim();\\n }\\n \\n return `✅ SSL configuration looks good\\\\nGrade: ${result.overallGrade} | Expires in ${result.certificate.daysUntilExpiry} days`;\\n}\\n\\nfunction getDiscordFields(result) {\\n const fields = [];\\n \\n // Certificate info\\n fields.push({\\n name: \\\"📜 Certificate\\\",\\n value: [\\n `**Subject:** ${result.certificate.subject}`,\\n `**Issuer:** ${result.certificate.issuer}`,\\n `**Expires:** ${new Date(result.certificate.validUntil).toLocaleDateString()}`,\\n `**Days Left:** ${result.certificate.daysUntilExpiry}`\\n ].join('\\\\n'),\\n inline: true\\n });\\n \\n // Security info\\n fields.push({\\n name: \\\"🔐 Security\\\",\\n value: [\\n `**Overall Grade:** ${result.overallGrade}`,\\n `**TLS 1.2:** ${result.protocols.tls12 ? '✅' : '❌'}`,\\n `**TLS 1.3:** ${result.protocols.tls13 ? '✅' : '❌'}`,\\n `**Vulnerabilities:** ${result.vulnerabilities.hasVulnerabilities ? '⚠️ Found' : '✅ None'}`\\n ].join('\\\\n'),\\n inline: true\\n });\\n \\n // Add recommendations if any\\n if (result.recommendations.length > 0) {\\n fields.push({\\n name: \\\"💡 Recommendations\\\",\\n value: result.recommendations.slice(0, 3).map(rec => `• ${rec.message || rec}`).join('\\\\n') + \\n (result.recommendations.length > 3 ? `\\\\n... and ${result.recommendations.length - 3} more` : ''),\\n inline: false\\n });\\n }\\n \\n return fields;\\n}\\n\\nreturn results;\"},\"typeVersion\":2}],\"active\":false,\"settings\":{\"executionOrder\":\"v1\"},\"connections\":{\"Check SSL\":{\"main\":[[{\"node\":\"Expiry Alert\",\"type\":\"main\",\"index\":0}]]},\"Expiry Alert\":{\"main\":[[{\"node\":\"Discord1\",\"type\":\"main\",\"index\":0}]]},\"Daily Trigger\":{\"main\":[[{\"node\":\"Fetch domains to check SSL\",\"type\":\"main\",\"index\":0}]]},\"Code - Format output\":{\"main\":[[{\"node\":\"Discord\",\"type\":\"main\",\"index\":0}]]},\"SSH - Analyze system\":{\"main\":[[{\"node\":\"Code - Format output\",\"type\":\"main\",\"index\":0}]]},\"Fetch domains to check SSL\":{\"main\":[[{\"node\":\"SSH - Analyze system\",\"type\":\"main\",\"index\":0},{\"node\":\"Check SSL\",\"type\":\"main\",\"index\":0}]]}}}"}], "metadata": {"node_count": 8, "node_types": {"httpRequest": 1, "if": 1, "scheduleTrigger": 1, "ssh": 1, "discord": 2, "notion": 1, "code": 1}, "services": ["http"], "complexity": "medium", "has_conditions": true, "has_loops": false, "has_code": true, "has_ai": false}} {"task_type": "generate", "messages": [{"role": "system", "content": "Tu es un expert n8n. Crée des workflows JSON complets et fonctionnels.\nUtilise pour expliquer ton raisonnement avant de générer le JSON.\nStructure ton thinking: analyse du besoin, choix du trigger, architecture, flux de données, points d'attention."}, {"role": "user", "content": "Crée un workflow n8n pour: Overview Stop spending hours formatting proposals. This workflow turns a short post-call form into a high-converting, fully-personalized PandaDoc proposal—plus updates your CRM and drafts the follow-up email for you. After a sales call, just fill out a 3-minute form summarizing key pain points, solutions pitched, and the price. The workflow uses AI to generate polished proposal copy, then builds a PandaDoc draft using dynamic data mapped into the JSON body (which you can fully customize per business). It also updates the lead record in ClickUp with the proposal link, company name, and quote—then creates an email draft in Gmail, ready to send. Who’s it for Freelancers and consultants sending service proposals Agencies closing deals over sales calls Sales reps who want to automate proposal f"}, {"role": "assistant", "content": "\n**Analyse du besoin**: Overview\n\nStop spending hours formatting proposals. This workflow turns a short post-call form into a high-converting, fully-personalized PandaDoc proposal—plus updates your CRM and drafts the follow-...\n\n**Choix du trigger**: Sélection basée sur le cas d'usage décrit.\n\n**Architecture**: 8 nodes utilisant ai, email, http.\nStructure: intégration IA.\n\n**Flux de données**: Connexions définies entre les nodes pour assurer le passage des données.\n\n**Points d'attention**: Vérifier les credentials, tester chaque node individuellement.\n\n\n{\"meta\":{\"instanceId\":\"a88d54d0dc140647df8f628579b3d5aae0dedb13c983a1f5c11ee14f54f18774\",\"templateCredsSetupCompleted\":true},\"nodes\":[{\"id\":\"7d32401a-90d3-462d-ab44-435e92371afb\",\"name\":\"Generate Proposal Copy\",\"type\":\"@n8n/n8n-nodes-langchain.openAi\",\"position\":[220,0],\"parameters\":{\"modelId\":{\"__rl\":true,\"mode\":\"list\",\"value\":\"gpt-4o\",\"cachedResultName\":\"GPT-4O\"},\"options\":{},\"messages\":{\"values\":[{\"role\":\"system\",\"content\":\"You are a helpful, intelligent writing assistant.\"},{\"content\":\"=Your task is to generate a proposal using input data from a form. This proposal should be highly customized, specific, and high-quality, considering we're going to be sending it immediately after you're done.\\n\\nContext: we are an automation/no-code agency that develops systems revolving around growth, revenue ops, etc.\\n\\nThe proposal template we're using has many fields. You must return these fields in one JSON object.\\n\\nUse this format:\\n\\n{\\n \\\"proposalTitle\\\": \\\"\\\",\\n \\\"problemTitle\\\": \\\"\\\",\\n \\\"problemText\\\": \\\"\\\",\\n \\\"solutionTitle\\\": \\\"\\\",\\n \\\"solutionText\\\": \\\"\\\",\\n \\\"scope1\\\": \\\"\\\",\\n \\\"scope2\\\": \\\"\\\",\\n \\\"scope3\\\": \\\"\\\",\\n \\\"scope4\\\": \\\"\\\",\\n\\\"deliverable1\\\":\\\"\\\",\\n\\\"deliverable2\\\":\\\"\\\",\\n\\\"deliverable3\\\":\\\"\\\",\\n \\\"timeline1\\\": \\\"\\\",\\n \\\"timeline2\\\": \\\"\\\",\\n \\\"timeline3\\\": \\\"\\\"\\n}\\n\\nRules:\\n1. Use a spartan, casual tone of voice.\\n2. Be to-the-point but professional—assume you're writing to a sophisticated audience.\\n3. Ensure that all fields are filled out. Do not miss a field or leave any variables empty.\\n4. For problemText and solutionText, make sure to number the responses (usually 3, make sure they're inside of the string).\\n5. There will only ever be 4 scoping bullet points, 3 timeline and 3 deliverable bullet points—stick to this precisely. For the timelines, only say the amount of days (\\\"x days\\\")\"},{\"content\":\"={\\\"problem\\\":\\\"Right now they're managing all of their leads & projects in a massive Google Sheet. The key issues: their system is disorganized, incapable of scaling, and provides little in the way of accountability. Team members are manually updating fields, copying and pasting data, and there is no single source of truth.\\\",\\n\\\"solution\\\":\\\"Migration to a dedicated CRM & project management solution like Monday.com, and a bespoke setup that includes a CRM board to handle new leads, alongside a PM board to handle new and ongoing projects. The creation of new records, and various administrative tasks alongside them, will be handled using both built in Monday automations and third party tools. I'll also create a process library of SOPs to improve operations more generally.\\\",\\n\\\"deliverables\\\":\\\"completed Monday CRM, PM boards, process library of SOPs, training materials, video\\\",\\n\\\"timeline\\\":\\\"two weeks\\\",\\n\\\"companyDescription\\\":\\\"Robert Half is an executive recruiting firm that works primarily out of NYC.\\\"}\"},{\"role\":\"assistant\",\"content\":\"={\\n \\\"proposalTitle\\\": \\\"Scalable Project Management system for Robert Half\\\",\\n \\\"problem\\\": {\\n \\\"title\\\": \\\"Your systems don't scale & you're paying too much\\\",\\n \\\"text\\\": \\\"1. You're using systems that don't scale\\\\n\\\\nCurrently, your team spends a ridiculous amount of time manually updating fields in a Google Sheet. This is resource-intensive, inefficient, and tedious—it's easy for a small mistake to cascade into a large one, and this has happened multiple times. Perhaps more importantly, there's no accountability, so when said problems inevitably arise, it's impossible to trace it back to its root and solve it.\\\\n\\\\n2. You're doing (and paying) too much\\\\n\\\\nGoogle Sheets is free. But the impact on your business has been costly. Given the archaic nature of your current setup, specific daily tasks are difficult to operationalize—leading to a large chunk of your employee/contractor costs going to admin tasks that are easily automatable.\\\\n\\\\n3. You're missing a ton of functionality\\\\n\\\\nGoogle Sheets is primarily textual, and misses the rich functionality afforded by more intentional CRMs. For instance, you can't assign owners to records, or automatically notify team members when something needs to happen (instead, everyone has to be online all the time \\\"just in case\\\"), or take advantage of more effective views to represent data flow.\\\"\\n },\\n \\\"solution\\\": {\\n \\\"title\\\": \\\"Scalable systems & built-in project management\\\",\\n \\\"text\\\": \\\"1. First, I'll migrate & build you a scalable system:\\\\n\\\\nI'll help you migrate to Monday.com, a dedicated CRM and project management platform. This will address many of the scalability issues inherent to Google Sheets—your team will be able to assign owners to records, receive notifications on important tasks, and communicate with eachother in a public, accountable way. \\\\n\\\\nIn addition, I'll build bespoke automations (both in Monday and using a third party tool, Make.com) to eliminate the need for manual record creation and related administrative functions. This will improve cycle time, better the quality of life of your staff, and decrease the likelihood of a costly error.\\\\n\\\\n2. Then, I'll help you improve cost efficiency:\\\\n\\\\nNext, we'll operationalize your procedures, add them to a library of SOPs, and begin scoping automated solutions to improve the effectiveness of each task. Much of the knowledge in your company currently exists in conversation or hidden direct messages and threads—turning this into a central, accessible knowledge base will streamline new hire onboarding, significantly improve margins on tasks, and make your team much more flexible.\\\"\\n },\\n \\\"scope\\\": {\\n \\\"1\\\": \\\"We'll migrate your current Google Sheets set-up to Monday.com, a scalable CRM & project management system\\\",\\n \\\"2\\\": \\\"We'll create two boards—a CRM board and a Project Management board—which will be your single source of truth for business operations moving forward.\\\",\\n \\\"3\\\": \\\"We'll build you a process library that exhaustively covers your business SOPs, which will let your team train faster and delegate work more effectively.\\\",\\n \\\"4\\\": \\\"We'll produce an end-to-end piece of video documentation of the system upon delivery.\\\"},\\n\\\"deliverable\\\": {\\n \\\"1\\\": \\\"Sheets -> Monday Migration\\\",\\n \\\"2\\\": \\\"SOPs & Process Library\\\",\\n \\\"3\\\": \\\"Video Documentation\\\"\\n }\\n \\\"timeline\\\": {\\n \\\"1\\\": \\\"5 business days\\\",\\n \\\"2\\\": \\\"3 business days\\\",\\n \\\"3\\\": \\\"1 business day\\\"\\n }\\n}\"},{\"content\":\"={\\\"problem\\\":\\\"{{ $json.form_response.answers[5].text }}\\\",\\n\\\"solutionIPitched\\\":\\\"{{ $json.form_response.answers[6].text }}\\\"\\\"\\n\\\"deliverables\\\":\\\"{{ $json.form_response.answers[7].text }}\\\",\\n\\\"timeline\\\":\\\"{{ $json.form_response.answers[8].text }}\\\",\\n\\\"companyDescription\\\":\\\"{{ $json.form_response.answers[4].text }}\\\"}\"}]},\"jsonOutput\":true},\"typeVersion\":1.8},{\"id\":\"2526fb73-6b90-4434-93d6-d605fdd702b8\",\"name\":\"Create PandaDoc Proposal\",\"type\":\"n8n-nodes-base.httpRequest\",\"position\":[620,0],\"parameters\":{\"url\":\"https://api.pandadoc.com/public/v1/documents\",\"method\":\"POST\",\"options\":{},\"jsonBody\":\"={\\n \\\"owner\\\": {\\n \\\"email\\\": \\\"abdul@builtbyabdul.com\\\"\\n },\\n \\\"template_uuid\\\": \\\"