{
  "id": "fnSWZ5XCdbq6snzS",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "name": "AI-Powered LinkedIn Connection Recommender",
  "tags": [],
  "nodes": [
    {
      "id": "ef9e2f3b-c06a-484a-8903-2f37b35728f3",
      "name": "Search LinkedIn Profiles",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        -600,
        4.76293103448279
      ],
      "parameters": {
        "url": "https://serpapi.com/search.json",
        "options": {},
        "sendQuery": true,
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBasicAuth",
        "queryParameters": {
          "parameters": [
            {
              "name": "engine",
              "value": "google"
            },
            {
              "name": "q",
              "value": "=site:linkedin.com/in \"{{ $json.Position }}\" \"{{ $json.Location }}\" {{ $json.Skills.split(',')[0] }}"
            },
            {
              "name": "api_key",
              "value": "="
            },
            {
              "name": "num",
              "value": "200"
            },
            {
              "name": "start",
              "value": "0"
            }
          ]
        }
      },
      "credentials": {
        "httpBasicAuth": {
          "name": "<your credential>"
        },
        "httpQueryAuth": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4
    },
    {
      "id": "34999f59-ae4b-4ef6-9603-bc5f6b2798d0",
      "name": "AI Profile Analysis",
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "position": [
        -160,
        4.76293103448279
      ],
      "parameters": {
        "text": "=You are a LinkedIn networking expert. Analyze the following user profile and potential connections to provide intelligent networking recommendations.\n\nUser Profile:\n- Name: {{ $json.userProfile.name }}\n- Position: {{ $json.userProfile.current_position }}\n- Industry: {{ $json.userProfile.industry }}\n- Location: {{ $json.userProfile.location }}\n- Skills: {{ $json.userProfile.skills }}\n- Interests: {{ $json.userProfile.interests }}\n- Target Roles: {{ $json.userProfile.target_roles }}\n- Preferred Companies: {{ $json.userProfile.company_types }}\n\nPotential Connections Found:\n{{ $json.foundProfiles.map(p => `- ${p.name}: ${p.headline}`).join('\\n') }}\n\nPlease provide a JSON response with the following structure:\n{\n  \"scored_profiles\": [\n    {\n      \"name\": \"Profile Name\",\n      \"score\": 8.5,\n      \"reasons\": [\"Similar role\", \"Same industry\", \"Skill overlap\"]\n    }\n  ],\n  \"top_connections\": [\n    // Top 10 recommended profiles with full details\n  ],\n  \"connection_strategies\": [\n    \"Personalized connection message suggestion for each top profile\"\n  ],\n  \"networking_insights\": \"Key insights about networking opportunities and industry trends\"\n}\n\nScore profiles from 1-10 based on:\n- Role alignment with user's target positions\n- Industry relevance\n- Skill complementarity\n- Networking value\n- Career growth potential\n\nFocus on quality connections that could provide mutual value.",
        "batching": {},
        "promptType": "define"
      },
      "typeVersion": 1.7
    },
    {
      "id": "d8205e9b-e176-477c-a8e7-2f1eb94bc3cb",
      "name": "Ollama Model1",
      "type": "@n8n/n8n-nodes-langchain.lmOllama",
      "position": [
        -72,
        224.7629310344828
      ],
      "parameters": {
        "model": "llama3.2-16000:latest",
        "options": {
          "topP": 0.9,
          "temperature": 0.7
        }
      },
      "credentials": {
        "ollamaApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "482f65e9-4075-4d60-8bc8-3c078f8c7acc",
      "name": "Send email",
      "type": "n8n-nodes-base.emailSend",
      "position": [
        656,
        4.76293103448279
      ],
      "parameters": {
        "text": "={{ $json.body }}",
        "options": {},
        "subject": "={{ $json.subject }}",
        "toEmail": "{{ $json.from }}",
        "fromEmail": "user@example.com",
        "emailFormat": "text"
      },
      "credentials": {
        "smtp": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "c759dfb7-9935-41e0-9d38-e41ff48c8b0b",
      "name": "Create Email",
      "type": "n8n-nodes-base.code",
      "position": [
        436,
        4.76293103448279
      ],
      "parameters": {
        "jsCode": "// Get the input data (your JSON)\nconst data = items[0].json;\n\n// Build the email text\nlet emailText = `\ud83d\udcca Networking Report for ${data.user_profile.name}\\n`;\nemailText += `\\nInterests: ${data.user_profile.interests}`;\nemailText += `\\nTarget Industry: ${data.user_profile.target_industry}\\n`;\n\nemailText += `\\nSummary:\\n`;\nemailText += `- Total Profiles Found: ${data.summary.total_profiles_found}\\n`;\nemailText += `- Analyzed Connections: ${data.summary.analyzed_connections}\\n`;\nemailText += `- High Priority: ${data.summary.high_priority}\\n`;\nemailText += `- Medium Priority: ${data.summary.medium_priority}\\n`;\nemailText += `- Average Score: ${data.summary.average_score}\\n`;\n\nemailText += `\\nTop Connection Recommendations:\\n`;\ndata.connection_recommendations.forEach((rec, index) => {\n    emailText += `\\n${index + 1}. ${rec.name} (${rec.priority} Priority, Score: ${rec.aiScore})`;\n    emailText += `\\n   ${rec.description}`;\n    emailText += `\\n   Mutual Connections: ${rec.mutual_connections}`;\n    emailText += `\\n   Reason: ${rec.connectionReason}`;\n    emailText += `\\n   Suggested Message: \"${rec.suggestedMessage}\"\\n`;\n});\n\nemailText += `\\nNext Steps:\\n`;\ndata.next_steps.forEach((step, i) => {\n    emailText += `- ${step}\\n`;\n});\n\nemailText += `\\nAI Insights:\\n${data.ai_insights}\\n`;\n\nemailText += `\\nBest Networking Times:\\nDays: ${data.networking_strategy.best_days.join(\", \")}\\nTimes: ${data.networking_strategy.best_times.join(\", \")}\\n`;\n\nreturn [{\n    json: {\n        subject: `Networking Report - ${data.user_profile.name}`,\n        body: emailText\n    }\n}];\n"
      },
      "typeVersion": 2
    },
    {
      "id": "7e27272d-1c4e-4e15-b7be-f0ef85937c13",
      "name": "Your Profile Information",
      "type": "n8n-nodes-base.set",
      "position": [
        -820,
        4.76293103448279
      ],
      "parameters": {
        "fields": {
          "values": [
            {
              "name": "Name"
            },
            {
              "name": "Position"
            },
            {
              "name": "Industry"
            },
            {
              "name": "Location"
            },
            {
              "name": "Skills"
            },
            {
              "name": "Interests"
            },
            {
              "name": "Target Roles"
            },
            {
              "name": "Company Types"
            }
          ]
        },
        "options": {}
      },
      "typeVersion": 3
    },
    {
      "id": "a9d1762a-aaf2-45a5-a5fc-381ec2d174c5",
      "name": "Process LinkedIn Search Results",
      "type": "n8n-nodes-base.code",
      "position": [
        -380,
        4.76293103448279
      ],
      "parameters": {
        "jsCode": "// Process search results and extract LinkedIn profiles\nconst results = $json.organic_results || [];\n\n// Get user profile from the previous node\nconst userProfile = $input.first().json || {};\n\n// Filter and process LinkedIn profiles\nconst linkedinProfiles = results\n  .filter(result => {\n    const link = result.link || '';\n    return link.includes('linkedin.com/in/') && \n           !link.includes('/posts/') && \n           !link.includes('/activity/');\n  })\n  .map(result => {\n    let name = result.title || 'Unknown';\n    // Clean up the title to extract just the name\n    name = name.replace(/\\s*[-|]\\s*LinkedIn.*$/i, '').trim();\n    \n    return {\n      name: name,\n      headline: result.snippet || result.title || '',\n      link: result.link,\n      description: result.snippet || '',\n      source: 'Google Search via SerpAPI'\n    };\n  })\n  .slice(0, 15); // Limit to top 15 results\n\n// Safely extract skills - handle undefined/null values\nconst getFirstSkill = (skills) => {\n  if (!skills || typeof skills !== 'string') {\n    return '';\n  }\n  const skillsArray = skills.split(',');\n  return skillsArray.length > 0 ? skillsArray[0].trim() : '';\n};\n\n// Build search query with safe property access\nconst buildSearchQuery = () => {\n  const position = userProfile.Position || '';\n  const location = userProfile.Location || '';\n  const firstSkill = getFirstSkill(userProfile.Skills);\n  \n  return `site:linkedin.com/in \"${position}\" \"${location}\" ${firstSkill}`.trim();\n};\n\n// Return structured data for AI analysis\nreturn {\n  json: {\n    userProfile: {\n      name: $('Your Profile Information').first().json.Name || '',\n      current_position: $('Your Profile Information').first().json.Position || '',\n      industry: $('Your Profile Information').first().json.Industry || '',\n      location:  $('Your Profile Information').first().json.Location|| '',\n      skills: $('Your Profile Information').first().json.Skills|| '',\n      interests: $('Your Profile Information').first().json.Interests || '',\n      target_roles: $('Your Profile Information').first().json['Target Roles']|| '',\n      company_types: $('Your Profile Information').first().json['Company Types'] || ''\n    },\n    foundProfiles: linkedinProfiles,\n    totalFound: linkedinProfiles.length,\n    searchQuery: buildSearchQuery()\n  }\n};"
      },
      "typeVersion": 2,
      "alwaysOutputData": true
    },
    {
      "id": "808cb1fa-9970-4d0e-8d34-37eea340fdb4",
      "name": "Create Final Recommendations",
      "type": "n8n-nodes-base.code",
      "position": [
        216,
        4.76293103448279
      ],
      "parameters": {
        "jsCode": "// Process AI recommendations and create final output\nconst inputData = $input.first();\nconst inputText = inputData.json?.text || inputData.json || inputData;\n\nlet aiRecommendations = {};\ntry {\n  // Extract JSON from the text content\n  const content = typeof inputText === 'string' ? inputText : JSON.stringify(inputText);\n  \n  // Try to parse JSON from the AI response\n  const jsonMatch = content.match(/```json\\n([\\s\\S]*?)\\n```/) || content.match(/\\{[\\s\\S]*\\}/);\n  if (jsonMatch) {\n    const jsonString = jsonMatch[1] || jsonMatch[0];\n    aiRecommendations = JSON.parse(jsonString);\n  } else {\n    throw new Error('No JSON found in response');\n  }\n} catch (error) {\n  console.log('Could not parse AI response:', error.message);\n  console.log('Input data:', inputData);\n  \n  // Create fallback recommendations if parsing fails\n  aiRecommendations = {\n    scored_profiles: [],\n    top_connections: [],\n    connection_strategies: [],\n    networking_insights: 'Focus on building meaningful professional relationships in your industry.'\n  };\n}\n\n// Helper function to safely split and get first element\nfunction safeGetFirst(str, delimiter = ',') {\n  if (!str || typeof str !== 'string') return '';\n  const parts = str.split(delimiter);\n  return parts.length > 0 ? parts[0].trim() : '';\n}\n\n// Helper function to safely split string\nfunction safeSplit(str, delimiter = ',') {\n  if (!str || typeof str !== 'string') return [];\n  return str.split(delimiter).map(item => item.trim()).filter(item => item);\n}\n\n// Helper function to generate connection message\nfunction generateConnectionMessage(profile, index) {\n  if (!profile || !profile.name) return 'Hi! I\\'d love to connect and share professional insights.';\n  \n  const firstName = safeGetFirst(profile.name, ' ');\n  const description = profile.description || '';\n  \n  // Create personalized messages based on profile\n  if (description.toLowerCase().includes('devops')) {\n    return `Hi ${firstName}, I'm interested in DevOps and cloud technologies. I'd love to connect and learn from your experience!`;\n  } else if (description.toLowerCase().includes('aws') || description.toLowerCase().includes('cloud')) {\n    return `Hi ${firstName}, I noticed your expertise in cloud computing. Would love to connect and share insights about the industry!`;\n  } else {\n    return `Hi ${firstName}, I'd love to connect with a fellow professional and learn from your experience in the industry.`;\n  }\n}\n\n// Helper function to extract tags from description\nfunction extractTags(description) {\n  if (!description) return ['Professional Contact'];\n  \n  const tags = [];\n  const descText = description.toLowerCase();\n  \n  // Add technology tags\n  const techs = ['aws', 'azure', 'gcp', 'devops', 'terraform', 'ansible', 'jenkins', 'kubernetes', 'docker'];\n  techs.forEach(tech => {\n    if (descText.includes(tech)) {\n      tags.push(tech.toUpperCase());\n    }\n  });\n  \n  // Add role tags\n  if (descText.includes('senior') || descText.includes('lead')) {\n    tags.push('Senior Level');\n  }\n  \n  if (descText.includes('mentor') || descText.includes('enthusiast')) {\n    tags.push('Mentor');\n  }\n  \n  return tags.length > 0 ? tags : ['Professional Contact'];\n}\n\n// Process the connections from AI recommendations\nconst connections = aiRecommendations.top_connections || [];\nconst scoredProfiles = aiRecommendations.scored_profiles || [];\n\nconst enhancedConnections = connections.map((profile, index) => {\n  // Find matching score data\n  const scoreData = scoredProfiles.find(p => \n    p.name && profile.name && \n    p.name.toLowerCase().trim() === profile.name.toLowerCase().trim()\n  );\n  \n  const score = scoreData?.score || (9.5 - index * 0.3); // Fallback scoring\n  \n  return {\n    name: profile.name || 'Unknown',\n    description: profile.description || '',\n    connections: profile.connections || 0,\n    mutual_connections: profile.mutual_connections || 0,\n    priority: score >= 8.5 ? 'High' : score >= 7.5 ? 'Medium' : 'Low',\n    aiScore: score,\n    connectionReason: scoreData?.reasons?.join(', ') || 'Professional networking opportunity',\n    suggestedMessage: generateConnectionMessage(profile, index),\n    tags: extractTags(profile.description),\n    estimatedResponseRate: score >= 8.5 ? 'High (70-90%)' : score >= 7.5 ? 'Medium (40-70%)' : 'Low (20-40%)',\n    link: profile.link || '#'\n  };\n}).sort((a, b) => b.aiScore - a.aiScore); // Sort by AI score\n\n// Create individual connection strategies\nconst connectionStrategies = enhancedConnections.map(conn => {\n  const firstName = safeGetFirst(conn.name, ' ');\n  return `${firstName}: ${conn.suggestedMessage.replace(`Hi ${firstName}, `, '')}`;\n});\n\nreturn {\n  json: {\n    summary: {\n      total_profiles_found: scoredProfiles.length,\n      analyzed_connections: enhancedConnections.length,\n      high_priority: enhancedConnections.filter(c => c.priority === 'High').length,\n      medium_priority: enhancedConnections.filter(c => c.priority === 'Medium').length,\n      low_priority: enhancedConnections.filter(c => c.priority === 'Low').length,\n      average_score: enhancedConnections.length > 0 ? \n        (enhancedConnections.reduce((sum, c) => sum + c.aiScore, 0) / enhancedConnections.length).toFixed(1) : 0\n    },\n    user_profile: {\n      name: \"Vrushti Sukhadiya\", // Extracted from the analysis text\n      interests: \"DevOps, Cloud Computing, Automation\",\n      target_industry: \"IT, Tech Startups, Cloud Companies\"\n    },\n    connection_recommendations: enhancedConnections,\n    connection_strategies: connectionStrategies,\n    ai_insights: aiRecommendations.networking_insights || 'Focus on building meaningful professional relationships in your industry.',\n    networking_strategy: {\n      weekly_goal: '5-10 new connections',\n      best_days: ['Tuesday', 'Wednesday', 'Thursday'],\n      best_times: ['9-11 AM', '2-4 PM'],\n      follow_up_schedule: 'Within 48 hours of connection acceptance',\n      focus_areas: ['DevOps professionals', 'Cloud Computing experts', 'AI/ML enthusiasts']\n    },\n    next_steps: [\n      'Start with highest-scored profiles (Mihir Suthar - 9.5, Muneeswaran M - 9.2)',\n      'Check for mutual connections before reaching out',\n      'Engage with their recent posts about DevOps/Cloud topics',\n      'Send personalized connection requests highlighting common interests',\n      'Follow up with thoughtful messages about industry trends',\n      'Consider attending DevOps/Cloud computing events where they might be present'\n    ],\n    top_recommendations: enhancedConnections.slice(0, 3).map(conn => ({\n      name: conn.name,\n      why_connect: conn.connectionReason,\n      action_item: `Connect with ${safeGetFirst(conn.name, ' ')} focusing on ${conn.tags.slice(0, 2).join(' and ')} expertise`\n    }))\n  }\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "e1b30786-455f-414f-9577-36634a0c1cd9",
      "name": "Get User Data From Email ",
      "type": "n8n-nodes-base.emailReadImap",
      "position": [
        -1040,
        4.76293103448279
      ],
      "parameters": {
        "options": {}
      },
      "credentials": {
        "imap": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2
    },
    {
      "id": "02259afc-6178-49f4-b08c-82dc7667bd06",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -940,
        -420
      ],
      "parameters": {
        "width": 680,
        "height": 340,
        "content": "## System Architecture\n- **Profile Analysis Pipeline**:\n  - **Get User Data from Email**: Initiates with manual user input.\n  - **Your Profile Information**: Provides initial data.\n  - **Search LinkedIn Profiles**: Fetches profile data via API.\n  - **Process LinkedIn Search Results**: Extracts relevant information.\n- **AI Recommendation Flow**:\n  - **AI Profile Analysis**: Analyzes data with AI.\n  - **Create Recommendations**: Generates initial connection list.\n  - **Create Final Recommendations**: Refines the list.\n- **Delivery Flow**:\n  - **Create Email**: Prepares the email content.\n  - **Send Email**: Sends the curated list to the user."
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "9073190a-946e-4f57-998d-365de4ec3ae8",
  "connections": {
    "Create Email": {
      "main": [
        [
          {
            "node": "Send email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ollama Model1": {
      "ai_languageModel": [
        [
          {
            "node": "AI Profile Analysis",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "AI Profile Analysis": {
      "main": [
        [
          {
            "node": "Create Final Recommendations",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Search LinkedIn Profiles": {
      "main": [
        [
          {
            "node": "Process LinkedIn Search Results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Your Profile Information": {
      "main": [
        [
          {
            "node": "Search LinkedIn Profiles",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get User Data From Email ": {
      "main": [
        [
          {
            "node": "Your Profile Information",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Final Recommendations": {
      "main": [
        [
          {
            "node": "Create Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Process LinkedIn Search Results": {
      "main": [
        [
          {
            "node": "AI Profile Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}