{
  "id": "d23vz3qcBf6KfuZA",
  "meta": {
    "instanceId": "31e69f7f4a77bf465b805824e303232f0227212ae922d12133a0f96ffeab4fef",
    "templateCredsSetupCompleted": true
  },
  "name": "🎦🚀 YouTube Video Comment Analysis Agent",
  "tags": [],
  "nodes": [
    {
      "id": "6661e7c3-ec1e-43b0-8bc6-44abbefbbcea",
      "name": "When Executed by Another Workflow",
      "type": "n8n-nodes-base.executeWorkflowTrigger",
      "disabled": true,
      "position": [
        -160,
        80
      ],
      "parameters": {
        "inputSource": "jsonExample",
        "jsonExample": "{\n  \"query\": {\n\t\"videoId\": \"YouTube video id\"\n  }\n}"
      },
      "typeVersion": 1.1
    },
    {
      "id": "729edcc9-7eda-4ad0-b168-5e5a57cdbf6a",
      "name": "Sticky Note10",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -300,
        -80
      ],
      "parameters": {
        "color": 7,
        "width": 1730,
        "height": 760,
        "content": "## 🛠️YouTube Video Details & Comments Processing Tool"
      },
      "typeVersion": 1
    },
    {
      "id": "454c3494-9808-475d-ad53-decd54d99783",
      "name": "Create YouTube API URL",
      "type": "n8n-nodes-base.code",
      "position": [
        500,
        100
      ],
      "parameters": {
        "jsCode": "// Define the base URL for the YouTube Data API\nconst BASE_URL = 'https://www.googleapis.com/youtube/v3/videos';\n\n// Get the first input item\nconst item = $input.first();\n\n// Extract the videoId and google_api_key from the input JSON\nconst VIDEO_ID = item.json.VIDEO_ID;\nconst GOOGLE_API_KEY = item.json.GOOGLE_API_KEY; // Dynamically retrieve API key\n\nif (!VIDEO_ID) {\n  throw new Error('The video ID parameter is empty.');\n}\n\nif (!GOOGLE_API_KEY) {\n  throw new Error('The Google API Key is missing.');\n}\n\n// Construct the API URL with the video ID and dynamically retrieved API key\nconst youtubeUrl = `${BASE_URL}?part=snippet,contentDetails,status,statistics,player,topicDetails&id=${VIDEO_ID}&key=${GOOGLE_API_KEY}`;\n\n// Return the constructed URL\nreturn [\n  {\n    json: {\n      youtubeUrl: youtubeUrl,\n    },\n  },\n];\n"
      },
      "typeVersion": 2
    },
    {
      "id": "d715b012-7842-498c-8fda-1b2812b7bc1e",
      "name": "Get YouTube Video Details",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        700,
        100
      ],
      "parameters": {
        "url": "={{ $json.youtubeUrl }}",
        "options": {}
      },
      "typeVersion": 4.2
    },
    {
      "id": "2c6598c4-11d1-4952-929e-2d08c439dee3",
      "name": "Merge YouTube Details & Transcript",
      "type": "n8n-nodes-base.merge",
      "position": [
        1200,
        120
      ],
      "parameters": {
        "mode": "combine",
        "options": {},
        "combineBy": "combineByPosition"
      },
      "typeVersion": 3
    },
    {
      "id": "60eea409-6744-4415-b9e8-e505f6406cd7",
      "name": "Create One JSON Object",
      "type": "n8n-nodes-base.aggregate",
      "position": [
        1200,
        440
      ],
      "parameters": {
        "options": {},
        "aggregate": "aggregateAllItemData"
      },
      "typeVersion": 1
    },
    {
      "id": "666e5a60-3c0e-4f70-8689-a1fdfb688ca4",
      "name": "Workflow Variables",
      "type": "n8n-nodes-base.set",
      "position": [
        160,
        260
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "e656b8ef-4266-4f50-bd41-703b4bdb04df",
              "name": "GOOGLE_API_KEY",
              "type": "string",
              "value": "[YOUR_GOOGLE_API_KEY_GOES_HERE]"
            },
            {
              "id": "32db428d-a2e2-48a0-92c6-3880e744d140",
              "name": "VIDEO_ID",
              "type": "string",
              "value": "=c5dw_jsGNBk"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "a3d12a1c-8d9f-4afa-83a2-e61aaddc3977",
      "name": "Sticky Note12",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        60,
        20
      ],
      "parameters": {
        "width": 300,
        "height": 460,
        "content": "## 💡 Workflow Variables\nhttps://cloud.google.com/docs/get-started/access-apis\n\n- GOOGLE_API_KEY\n- VIDEO_ID - 🖐️CHANGE THIS!!!"
      },
      "typeVersion": 1
    },
    {
      "id": "fa87b1d0-368c-4d14-9138-2102df8fd285",
      "name": "Sticky Note14",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        400,
        -20
      ],
      "parameters": {
        "color": 3,
        "width": 500,
        "height": 300,
        "content": "## YouTube Video Details\nhttps://developers.google.com/youtube/v3/docs\nhttps://www.googleapis.com/youtube/v3/videos"
      },
      "typeVersion": 1
    },
    {
      "id": "846dc463-f989-4834-ab67-fc9d911b7cbd",
      "name": "Sticky Note15",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        400,
        320
      ],
      "parameters": {
        "color": 5,
        "width": 700,
        "height": 320,
        "content": "## YouTube Video Comments\nhttps://developers.google.com/youtube/v3/docs\nhttps://www.googleapis.com/youtube/v3/commentThreads"
      },
      "typeVersion": 1
    },
    {
      "id": "321c7aba-d22c-428c-ba0c-20852d80ad39",
      "name": "Combine Comments",
      "type": "n8n-nodes-base.summarize",
      "position": [
        900,
        440
      ],
      "parameters": {
        "options": {},
        "fieldsToSummarize": {
          "values": [
            {
              "field": "comments",
              "aggregation": "concatenate"
            }
          ]
        }
      },
      "typeVersion": 1
    },
    {
      "id": "28cc7f86-bd17-41a6-bf75-fc0a72b37b79",
      "name": "Split Out Comments",
      "type": "n8n-nodes-base.splitOut",
      "position": [
        700,
        440
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "comments"
      },
      "typeVersion": 1
    },
    {
      "id": "3a62fd7f-9185-4243-b9fd-34e0ad2046e6",
      "name": "Get YouTube Video Comments",
      "type": "n8n-nodes-base.httpRequest",
      "disabled": true,
      "position": [
        1200,
        820
      ],
      "parameters": {
        "url": "={{ $json.url }}",
        "options": {}
      },
      "typeVersion": 4.2
    },
    {
      "id": "4698558c-c50a-43b0-a027-fbbf37a69092",
      "name": "When clicking ‘Test workflow’",
      "type": "n8n-nodes-base.manualTrigger",
      "position": [
        -160,
        400
      ],
      "parameters": {},
      "typeVersion": 1
    },
    {
      "id": "ad68e98c-b870-4b7a-af3c-7d09c6bff29f",
      "name": "Create YouTube API URL for Comments",
      "type": "n8n-nodes-base.code",
      "disabled": true,
      "position": [
        980,
        820
      ],
      "parameters": {
        "jsCode": "// Define the base URL for the YouTube Data API\nconst BASE_URL = 'https://www.googleapis.com/youtube/v3/commentThreads';\n\n// Get the first input item\nconst item = $input.first();\n\n// Extract the videoId and google_api_key from the input JSON\nconst VIDEO_ID = item.json.VIDEO_ID;\nconst GOOGLE_API_KEY = item.json.GOOGLE_API_KEY; // Dynamically retrieve API key\nconst MAX_RESULTS = 100;  //item.json.MAX_RESULTS;\n\nconst url = `${BASE_URL}?part=snippet&videoId=${encodeURIComponent(VIDEO_ID)}&key=${encodeURIComponent(GOOGLE_API_KEY)}&maxResults=${encodeURIComponent(MAX_RESULTS)}`;\n\n// Now you can send this URL to the HTTP node for the GET request.\nreturn { json: { url } };\n"
      },
      "typeVersion": 2
    },
    {
      "id": "ccb00ab2-07cb-4f61-84ce-f51a45a6d2e9",
      "name": "Gmail Report",
      "type": "n8n-nodes-base.gmail",
      "position": [
        520,
        800
      ],
      "webhookId": "2bad33f7-38f8-40ca-9bcd-2f51179c8db5",
      "parameters": {
        "sendTo": "joe@example.com",
        "message": "={{ $json.html }}",
        "options": {
          "appendAttribution": false
        },
        "subject": "YouTube Video Report"
      },
      "credentials": {
        "gmailOAuth2": {
          "id": "1xpVDEQ1yx8gV022",
          "name": "Gmail account"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "74b921e3-0a72-4af8-9b10-2488e479f999",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -300,
        720
      ],
      "parameters": {
        "color": 6,
        "width": 1100,
        "height": 500,
        "content": "## 📽️ YouTube Video Comment Reporting Agent"
      },
      "typeVersion": 1
    },
    {
      "id": "511827aa-aa4a-4e39-9795-cc5d8c21e661",
      "name": "gpt-4o-mini",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        -120,
        1040
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4o-mini"
        },
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "id": "jEMSvKmtYfzAkhe6",
          "name": "OpenAi account"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "006d50a7-33a1-4ca1-969e-a266b2567452",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -240,
        320
      ],
      "parameters": {
        "color": 4,
        "width": 260,
        "height": 260,
        "content": "## 👍 Try Me!"
      },
      "typeVersion": 1
    },
    {
      "id": "1c054aa7-9b97-464b-a0d6-b514e4a2c7df",
      "name": "Markdown to HTML",
      "type": "n8n-nodes-base.markdown",
      "position": [
        280,
        860
      ],
      "parameters": {
        "mode": "markdownToHtml",
        "options": {},
        "markdown": "={{ $json.output }}",
        "destinationKey": "html"
      },
      "typeVersion": 1
    },
    {
      "id": "b84a52db-01d0-4711-8014-743b90b6c1b4",
      "name": "YouTube Video Report Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        -100,
        860
      ],
      "parameters": {
        "text": "=This is the YouTube video detals and comments: {{ $json.data.toJsonString() }}",
        "agent": "conversationalAgent",
        "options": {
          "systemMessage": "**Objective:**  \nAnalyze the provided YouTube video data and comments to generate a **comprehensive and detailed report**. The report should help YouTube creators identify trends, viewer interests, and actionable insights for creating similar or related content that resonates with audiences. The report must provide **in-depth explanations, examples, and recommendations** to guide creators in producing engaging content.\n\n**Instructions for AI:**  \nYou are an advanced AI agent tasked with analyzing YouTube video details and comments. Your goal is to produce a **detailed and insightful report** based on the following structure. Use the provided data to extract meaningful insights, trends, and actionable recommendations. Ensure each section is thorough, well-explained, and includes examples where applicable.\n\n---\n\n### Report Structure\n\n#### 1. Video Overview\n   - Provide a summary of the video's title, description, and key topics.\n   - Highlight the video’s performance metrics (e.g., views, likes, comments) and explain what these metrics suggest about its success.\n   - Identify the primary themes or subjects discussed in the video. Explain why these themes might have resonated with viewers (e.g., relevance to current trends, novelty of the topic).\n\n#### 2. Comment Analysis\n   - **Sentiment Analysis:**  \n     Perform sentiment analysis on the comments to determine the overall tone (e.g., positive, negative, neutral). Provide percentages or counts for each sentiment category. Include examples of representative comments for each sentiment type.\n   - **Common Themes:**  \n     Identify recurring topics or questions in the comments (e.g., viewers asking for tutorials, expressing excitement, or suggesting improvements). Explain why these themes are significant and how they reflect viewer interests or needs.\n   - **Engagement Drivers:**  \n     Highlight specific aspects of the video that generated high engagement (e.g., unique features, clear explanations). Provide detailed examples of what viewers appreciated most.\n   - **Viewer Pain Points:**  \n     Extract comments that express confusion, issues, or requests for clarification. For example:\n       - Questions about technical aspects or processes covered in the video.\n       - Requests for additional details or resources.\n       - Critiques or suggestions for improvement.\n\n#### 3. Content Opportunities\n   - Based on comment analysis, suggest topics for future videos:\n     - Tutorials addressing unresolved questions (e.g., step-by-step guides on complex tasks).\n     - Deep dives into related tools or concepts mentioned in comments.\n     - Solutions for specific use cases requested by viewers.\n   - Highlight any niche interests or emerging trends observed in viewer feedback. Explain why these opportunities are valuable and how they align with audience preferences.\n   - Provide examples of potential video titles or formats (e.g., \"Top 5 Tools for Web Scraping Beginners\" or \"How to Scrape Dynamic Pages Without Coding\").\n\n#### 4. Audience Profile\n   - Infer characteristics of the audience based on their comments:\n     - Level of expertise (e.g., beginners asking basic questions vs. advanced users discussing technical details).\n     - Interests (e.g., AI tools, web scraping techniques).\n     - Geographic or cultural indicators if applicable (e.g., language used in comments).\n   - Explain how understanding this audience profile can help creators tailor their content.\n\n#### 5. Actionable Recommendations\n   - Provide a list of actionable steps for content creators with detailed explanations:\n     1. Create follow-up videos addressing common questions raised in comments. Explain how addressing these questions can build trust and engagement with viewers.\n     2. Develop content around highly praised aspects of the video. For example, if viewers appreciated a particular tool demonstration, suggest creating a series exploring similar tools.\n     3. Explore collaborations with other creators in similar niches to expand reach and tap into overlapping audiences.\n     4. Promote ethical practices (if relevant) to build credibility and trust with viewers.\n   - Include specific strategies for improving engagement (e.g., encouraging viewers to comment their questions or ideas for future videos).\n\n#### 6. Keywords and Tags\n   - Extract frequently mentioned terms from comments to suggest keywords/tags for optimization.\n   - Provide a list of suggested tags based on both video content and comment analysis.\n   - Explain how these tags can improve discoverability on YouTube.\n\n#### 7. Potential Collaborations\n   - Identify opportunities for partnerships based on viewer suggestions or related channels/topics mentioned in comments.\n   - Suggest creators or channels that align with the video's themes and audience interests.\n\n#### 8. Detailed Suggestions for Similar Content\n   - Analyze what made this video engaging (e.g., storytelling techniques, visuals, pacing) and explain how these elements can be replicated in future videos.\n   - Suggest new angles or formats that build on this video's success (e.g., live Q&A sessions, behind-the-scenes content).\n   - Recommend experimenting with different styles or approaches based on viewer feedback (e.g., shorter videos for quick tips vs. longer deep-dive tutorials).\n\n---\n\n**Data Input Format:**  \nProvide the AI with structured data containing:\n- Video details: title, description, tags, views, likes, comments.\n- Comment data: text of each comment, timestamp, likes/replies on each comment.\n\n**Output Requirements:**  \nThe AI should generate a well-organized report in natural language formatted with Markdown with clear headings and bullet points where appropriate. Ensure all insights are actionable and relevant to YouTube creators aiming to replicate the video's success. Each suggestion should include detailed explanations and examples to guide creators effectively.\n"
        },
        "promptType": "define"
      },
      "typeVersion": 1.7
    },
    {
      "id": "55ff5bae-1939-46e1-afe3-76bfeab98243",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        840,
        720
      ],
      "parameters": {
        "color": 5,
        "width": 580,
        "height": 320,
        "content": "## YouTube Video Comments (Alternate)\nGet latest 100 comments without pagination"
      },
      "typeVersion": 1
    },
    {
      "id": "347ff6dd-db5c-4d3a-8552-fb24cdd371e0",
      "name": "Get Video Comments with Pagination",
      "type": "n8n-nodes-base.code",
      "position": [
        500,
        440
      ],
      "parameters": {
        "jsCode": "// Define a helper function to build a query string from an object\nfunction buildQueryString(params) {\n\treturn Object.keys(params)\n\t\t.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)\n\t\t.join('&');\n}\n\n// Define the base URL for the YouTube Data API\nconst BASE_URL = \"https://www.googleapis.com/youtube/v3/commentThreads\";\n\n// Get the first input item\nconst item = $input.first();\n\n// Extract the videoId and google_api_key from the input JSON\nconst videoId = item.json.VIDEO_ID;\nconst apiKey = item.json.GOOGLE_API_KEY; // Dynamically retrieve API key\n\nconst comments = [];\nlet nextPageToken = undefined;\n\nwhile (true) {\n    // Construct URL parameters using an object literal\n    const params = {\n        part: \"snippet\",\n        videoId: videoId,\n        key: apiKey\n    };\n\n    if (nextPageToken) {\n        params.pageToken = nextPageToken;\n    }\n\n    // Build the full URL without using URLSearchParams\n    const queryString = buildQueryString(params);\n    const url = `${BASE_URL}?${queryString}`;\n    \n    // Set up the options for the HTTP request helper\n    const options = {\n        method: \"GET\",\n        uri: url,\n        json: true\n    };\n\n    // Use n8n's built-in HTTP request helper instead of fetch\n    const data = await this.helpers.request(options);\n\n    // console.log(data.items)\n\n    // Process each comment in the response\n    data.items.forEach(item => {\n        comments.push(item.snippet.topLevelComment.snippet.textOriginal);\n    });\n\n    // console.log(data.nextPageToken)\n\n    // Exit loop if no further pages exist\n    if (!data.nextPageToken) {\n        break;\n    }\n    nextPageToken = data.nextPageToken;\n}\n\n// Return the collected comments as an item output for n8n\nreturn [{ json: { comments } }];\n"
      },
      "typeVersion": 2
    },
    {
      "id": "91869f81-8d98-4221-9205-44e18c1ff9b8",
      "name": "Save Report to Google Drive",
      "type": "n8n-nodes-base.googleDrive",
      "position": [
        520,
        1000
      ],
      "parameters": {
        "name": "=YouTube Video Report - {{ $('Merge YouTube Details & Transcript').item.json.items.first().snippet.title }}",
        "content": "={{ $json.output }}",
        "driveId": {
          "__rl": true,
          "mode": "list",
          "value": "My Drive"
        },
        "options": {},
        "folderId": {
          "__rl": true,
          "mode": "list",
          "value": "root",
          "cachedResultName": "/ (Root folder)"
        },
        "operation": "createFromText"
      },
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "UhdXGYLTAJbsa0xX",
          "name": "Google Drive account"
        }
      },
      "typeVersion": 3
    },
    {
      "id": "3629f058-7034-4530-a6a1-f30f611a05bf",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -860,
        -80
      ],
      "parameters": {
        "width": 520,
        "height": 760,
        "content": "# YouTube Video Comment Analysis Agent\n\nThis agent is designed to analyze YouTube video details and comments to generate a **comprehensive and actionable report** for content creators. The report provides insights into:\n\n- **Video performance**: Metrics such as views, likes, and comments.\n- **Audience engagement**: Identifying what resonates with viewers.\n- **Viewer feedback**: Highlighting trends, interests, and areas for improvement.\n\n### Key Features:\n1. **Sentiment Analysis**: Evaluates the tone of comments (positive, negative, neutral) to understand audience sentiment.\n2. **Recurring Themes**: Identifies common topics or questions in comments.\n3. **Engagement Drivers**: Highlights video elements that sparked high engagement.\n4. **Actionable Recommendations**: Offers specific strategies for improving content and addressing viewer needs.\n5. **Keyword Suggestions**: Extracts frequently mentioned terms for better discoverability.\n6. **Collaboration Opportunities**: Suggests potential partnerships based on viewer feedback or related channels.\n7. **Audience Profiling**: Infers audience characteristics such as expertise level and interests.\n\n### Objective:\nThe goal is to empower YouTube creators with **data-driven insights** to create engaging content that resonates with their audience while addressing viewer needs and preferences."
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "pinData": {
    "When Executed by Another Workflow": [
      {
        "json": {
          "query": {
            "videoId": "JWfNLF_g_V0"
          }
        }
      }
    ]
  },
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "929375b3-ca7e-49c3-9e7b-241864d27f62",
  "connections": {
    "gpt-4o-mini": {
      "ai_languageModel": [
        [
          {
            "node": "YouTube Video Report Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Combine Comments": {
      "main": [
        [
          {
            "node": "Merge YouTube Details & Transcript",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Markdown to HTML": {
      "main": [
        [
          {
            "node": "Gmail Report",
            "type": "main",
            "index": 0
          },
          {
            "node": "Save Report to Google Drive",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Out Comments": {
      "main": [
        [
          {
            "node": "Combine Comments",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Workflow Variables": {
      "main": [
        [
          {
            "node": "Create YouTube API URL",
            "type": "main",
            "index": 0
          },
          {
            "node": "Get Video Comments with Pagination",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create One JSON Object": {
      "main": [
        [
          {
            "node": "YouTube Video Report Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create YouTube API URL": {
      "main": [
        [
          {
            "node": "Get YouTube Video Details",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get YouTube Video Details": {
      "main": [
        [
          {
            "node": "Merge YouTube Details & Transcript",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get YouTube Video Comments": {
      "main": [
        []
      ]
    },
    "YouTube Video Report Agent": {
      "main": [
        [
          {
            "node": "Markdown to HTML",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When Executed by Another Workflow": {
      "main": [
        [
          {
            "node": "Workflow Variables",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When clicking ‘Test workflow’": {
      "main": [
        [
          {
            "node": "Workflow Variables",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Video Comments with Pagination": {
      "main": [
        [
          {
            "node": "Split Out Comments",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge YouTube Details & Transcript": {
      "main": [
        [
          {
            "node": "Create One JSON Object",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create YouTube API URL for Comments": {
      "main": [
        [
          {
            "node": "Get YouTube Video Comments",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}