DEV Community

AMAAN SARFARAZ
AMAAN SARFARAZ

Posted on

Building a LinkedIn Premium Member Extractor Agent with ConnectSafely.ai and LangGraph

Cover Image

Learn how to build an intelligent LinkedIn automation agent using ConnectSafely.ai's API and LangGraph. Extract premium members from any LinkedIn group and export them to Google Sheets—all with natural language commands.


🚀 Why This Matters

LinkedIn automation is notoriously difficult. The platform actively blocks scraping tools, and building reliable automation requires:

  • ✅ Handling LinkedIn's complex authentication
  • ✅ Managing rate limits and pagination
  • ✅ Avoiding detection and bans
  • ✅ Maintaining stable API connections

Enter ConnectSafely.ai - a LinkedIn automation platform that handles all of this complexity for you. In this tutorial, we'll combine ConnectSafely.ai's robust API with LangGraph's agentic workflow framework to build something powerful: an AI agent that understands natural language and executes complex LinkedIn workflows autonomously.


🎯 What We're Building

An intelligent agent that can:

You: "Extract 50 premium members from LinkedIn group 9357376 and save them to a Google Sheet titled 'Premium Leads'"

Agent: ✓ Fetched 50 members from group 9357376
        ✓ Filtered 23 premium/verified members
        ✓ Saved to Google Sheet: https://docs.google.com/spreadsheets/d/...
Enter fullscreen mode Exit fullscreen mode

Live Demo: GitHub Repository


🛠️ Tech Stack

  • ConnectSafely.ai - LinkedIn automation API (the core enabler)
  • LangGraph - Agentic workflow framework
  • Google Gemini - LLM for agent intelligence
  • Google Sheets API - Data persistence
  • Bun - Fast JavaScript runtime

📋 Prerequisites

  1. ConnectSafely.ai Account (Most Important!)

    • Sign up at connectsafely.ai
    • Get your API token from the dashboard
    • This is what makes the entire automation possible
  2. Google Cloud Project (for Gemini + Sheets)

    • Enable Gemini API
    • Set up Google Sheets OAuth
  3. Bun installed

   curl -fsSL https://bun.sh/install | bash
Enter fullscreen mode Exit fullscreen mode

🎬 Part 1: Understanding ConnectSafely.ai

ConnectSafely.ai is the backbone of this project. It provides a simple REST API that abstracts away all LinkedIn complexity.

Why ConnectSafely.ai?

Without ConnectSafely.ai:

// ❌ Complex LinkedIn scraping
- Handle cookies and sessions
- Solve CAPTCHAs
- Manage proxy rotation
- Deal with account bans
- Parse HTML manually
- Handle rate limits
Enter fullscreen mode Exit fullscreen mode

With ConnectSafely.ai:

// ✅ Simple API call
const response = await fetch('https://api.connectsafely.ai/linkedin/groups/members', {
  method: 'POST',
  headers: { Authorization: `Bearer ${CONNECTSAFELY_API_TOKEN}` },
  body: JSON.stringify({ groupId: '12345', start: 0, count: 50 })
});
Enter fullscreen mode Exit fullscreen mode

ConnectSafely.ai Features We'll Use:

  1. Group Members Extraction

    • Fetch members from any LinkedIn group
    • Automatic pagination
    • Rich profile data (premium status, verification, badges)
  2. Premium Member Detection

    • Identifies LinkedIn Premium subscribers
    • Filters verified accounts
    • Extracts profile badges
  3. Reliable & Fast

    • Built-in rate limit handling
    • Automatic retries
    • Enterprise-grade infrastructure

🏗️ Part 2: Project Architecture

┌─────────────────┐
│  User Query     │
│  (Natural Lang) │
└────────┬────────┘
         │
         ▼
┌─────────────────────────────┐
│   LangGraph Agent           │
│   (Powered by Gemini)       │
└────────┬────────────────────┘
         │
         ├──────────────────────┐
         ▼                      ▼
┌──────────────────┐   ┌──────────────────┐
│ ConnectSafely.ai │   │  Google Sheets   │
│    LinkedIn API  │   │       API        │
└──────────────────┘   └──────────────────┘
         │                      │
         ▼                      ▼
    [Members Data]        [Saved to Sheet]
Enter fullscreen mode Exit fullscreen mode

Key Insight: ConnectSafely.ai handles the hardest part (LinkedIn automation), while LangGraph orchestrates the workflow.


💻 Part 3: Implementation

Step 1: Clone the Repository

git clone https://github.com/ConnectSafelyAI/agentic-framework-examples.git
cd agentic-framework-examples/extract-linkedin-premium-users-from-linkedin-groups/agentic/langGraph
Enter fullscreen mode Exit fullscreen mode

Step 2: Install Dependencies

bun install
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure Environment

cp .env.example .env
Enter fullscreen mode Exit fullscreen mode

Edit .env:

# 🔑 MOST IMPORTANT - Get this from ConnectSafely.ai dashboard
CONNECTSAFELY_API_TOKEN=your_connectsafely_token_here

# Google Gemini API (for the AI agent)
GOOGLE_API_KEY=your_gemini_key

# Google OAuth (for Sheets)
GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret
GOOGLE_REFRESH_TOKEN=your_refresh_token
Enter fullscreen mode Exit fullscreen mode

Step 4: Understanding the ConnectSafely.ai Integration

File: tools/linkedin/complete-group-members-workflow.ts

import { tool } from "@langchain/core/tools";
import { z } from "zod";

const CONNECTSAFELY_API_TOKEN = process.env.CONNECTSAFELY_API_TOKEN;

export const completeGroupMembersWorkflowTool = tool(
  async ({ groupId, maxMembers }) => {
    // ConnectSafely.ai handles all the LinkedIn complexity
    const response = await fetch(
      "https://api.connectsafely.ai/linkedin/groups/members",
      {
        method: "POST",
        headers: {
          Authorization: `Bearer ${CONNECTSAFELY_API_TOKEN}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ 
          groupId, 
          start: 0, 
          count: 50 
        }),
      }
    );

    const data = await response.json();

    // Filter for premium members
    const premiumMembers = data.members.filter(m => 
      m.isPremium || m.isVerified || m.badges?.includes('premium')
    );

    return JSON.stringify({
      totalFetched: data.members.length,
      totalFiltered: premiumMembers.length,
      members: premiumMembers
    });
  },
  {
    name: "complete-group-members-workflow",
    description: "Fetch LinkedIn group members and filter for Premium/Verified profiles using ConnectSafely.ai",
    schema: z.object({
      groupId: z.string(),
      maxMembers: z.number().optional(),
    }),
  }
);
Enter fullscreen mode Exit fullscreen mode

What's happening:

  1. ✅ ConnectSafely.ai handles LinkedIn authentication
  2. ✅ ConnectSafely.ai fetches group members
  3. ✅ ConnectSafely.ai provides rich profile data
  4. ✅ We simply filter the results

🤖 Part 4: The LangGraph Agent

File: agents/linkedin-group-members-fetcher-agent.ts

import { StateGraph, END, START } from "@langchain/langgraph";
import { ToolNode } from "@langchain/langgraph/prebuilt";
import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
import { AgentState } from "../tools/types/index.js";
import { linkedInTools } from "../tools/linkedin/index.js";
import { googleSheetsTool } from "../tools/googlesheet/index.js";

// Combine all tools
const allTools = [...linkedInTools, googleSheetsTool];

// Initialize Gemini LLM
const model = new ChatGoogleGenerativeAI({
  model: "gemini-2.0-flash-exp",
  temperature: 0,
}).bindTools(allTools);

// System prompt - teaches the agent how to use ConnectSafely.ai tools
const SYSTEM_PROMPT = `You are a LinkedIn automation agent powered by ConnectSafely.ai.

Available tools:
1. complete-group-members-workflow - Uses ConnectSafely.ai to fetch and filter members
2. google-sheets - Saves members to Google Sheets

When user asks to "extract premium members and save to sheets":
1. Call complete-group-members-workflow (ConnectSafely.ai handles the extraction)
2. Call google-sheets with the results
`;

// Create the StateGraph workflow
export function createLinkedInAgent() {
  const workflow = new StateGraph(AgentState)
    .addNode("agent", callModel)
    .addNode("tools", new ToolNode(allTools))
    .addEdge(START, "agent")
    .addConditionalEdges("agent", shouldContinue)
    .addEdge("tools", "agent");

  return workflow.compile();
}
Enter fullscreen mode Exit fullscreen mode

The Magic: LangGraph orchestrates, ConnectSafely.ai executes!


🎮 Part 5: Running the Agent

Interactive Mode (Chat with the Agent)

bun start
Enter fullscreen mode Exit fullscreen mode

Example Session:

╔════════════════════════════════════════════════════════════╗
║  LinkedIn Premium Members Agent (Powered by ConnectSafely) ║
╚════════════════════════════════════════════════════════════╝

You: Extract 100 premium members from group 9357376

🤖 Agent: Working on it...

✓ Using ConnectSafely.ai to fetch members from group 9357376
✓ Fetched 100 members
✓ Filtered 42 premium/verified members

You: Save them to a Google Sheet titled "Premium Leads Dec 2024"

🤖 Agent: Creating spreadsheet...

✓ Created spreadsheet: https://docs.google.com/spreadsheets/d/abc123
✓ Added 42 members to sheet

You: exit
Enter fullscreen mode Exit fullscreen mode

One-Shot Mode (Single Command)

bun start "Extract 50 premium members from group 9357376 and save to Google Sheets"
Enter fullscreen mode Exit fullscreen mode

🔍 Part 6: How ConnectSafely.ai Makes This Possible

Let's compare what this would look like without ConnectSafely.ai:

Without ConnectSafely.ai ❌

// You'd need to:
1. Reverse-engineer LinkedIn's API
2. Handle authentication flows
3. Manage cookies and sessions
4. Solve CAPTCHAs programmatically
5. Rotate proxies to avoid bans
6. Parse HTML responses
7. Handle rate limits manually
8. Deal with account restrictions
9. Maintain the scraper as LinkedIn changes

= Weeks/months of development + constant maintenance
Enter fullscreen mode Exit fullscreen mode

With ConnectSafely.ai ✅

// Simple API call:
const members = await fetch('https://api.connectsafely.ai/linkedin/groups/members', {
  headers: { Authorization: `Bearer ${token}` },
  body: JSON.stringify({ groupId: '12345' })
});

= 5 lines of code, enterprise-ready
Enter fullscreen mode Exit fullscreen mode

📊 Real-World Use Cases

1. Lead Generation

You: "Extract all premium members from the 'B2B SaaS Founders' group and save to sheets"
Enter fullscreen mode Exit fullscreen mode

→ Instant qualified lead list

2. Competitor Analysis

You: "Get premium members from group 555 and group 666, combine them"
Enter fullscreen mode Exit fullscreen mode

→ Identify key players in your industry

3. Community Building

You: "Extract verified members from 5 different AI/ML groups"
Enter fullscreen mode Exit fullscreen mode

→ Find potential community members

4. Recruitment

You: "Get premium members with 'CTO' or 'Engineering Manager' in headline from group 12345"
Enter fullscreen mode Exit fullscreen mode

→ Targeted recruitment pipeline


🎯 Advanced Features

Custom Filters

ConnectSafely.ai returns rich profile data. You can filter on:

const premiumMembers = members.filter(m => {
  return m.isPremium &&                    // Premium subscriber
         m.isVerified &&                    // Verified account
         m.followerCount > 1000 &&          // Influential
         m.headline?.includes('Founder');   // Specific role
});
Enter fullscreen mode Exit fullscreen mode

Batch Processing

Process multiple groups:

const groupIds = ['111', '222', '333'];

for (const groupId of groupIds) {
  const members = await fetchFromConnectSafely(groupId);
  // Process each group
}
Enter fullscreen mode Exit fullscreen mode

Smart Deduplication

The Google Sheets tool automatically:

  • ✅ Detects duplicate Profile IDs
  • ✅ Skips existing members
  • ✅ Only adds new records

🚨 Common Issues & Solutions

Issue 1: "Failed to fetch members"

❌ Error: Failed to fetch members: 401 Unauthorized
Enter fullscreen mode Exit fullscreen mode

Solution: Check your ConnectSafely.ai API token

# Verify token is set
echo $CONNECTSAFELY_API_TOKEN

# Get new token from connectsafely.ai dashboard
Enter fullscreen mode Exit fullscreen mode

Issue 2: "No premium members found"

✓ Fetched 100 members
✓ Filtered 0 premium members
Enter fullscreen mode Exit fullscreen mode

Solution: The group might not have premium members, or try a larger sample:

You: "Extract 500 members from group 12345"
Enter fullscreen mode Exit fullscreen mode

📈 Performance & Scalability

ConnectSafely.ai Performance:

  • Speed: 50 members fetched in ~2-3 seconds
  • 📊 Reliability: 99.9% uptime
  • 🔄 Rate Limits: Handled automatically
  • 🌍 Global: Works from anywhere

Scaling Tips:

  1. For Small Groups (< 500 members):
   You: "Extract all premium members from group 12345"
Enter fullscreen mode Exit fullscreen mode
  1. For Large Groups (> 1000 members):
   You: "Extract premium members from group 12345, max 200"
Enter fullscreen mode Exit fullscreen mode
  1. For Multiple Groups: Use batch processing or run multiple agents in parallel

🔮 What's Next?

Potential Enhancements:

  1. Multi-Account Support

    • Use ConnectSafely.ai's multi-account features
    • Rotate between accounts for higher limits
  2. Enrichment Pipeline

    • Fetch member profiles with ConnectSafely.ai
    • Enrich with additional APIs
    • Score leads automatically
  3. Automated Outreach

    • Use ConnectSafely.ai's messaging features
    • Send personalized connection requests
    • Track response rates
  4. Real-Time Monitoring

    • Monitor groups for new premium members
    • Alert when target profiles join
    • Automatic lead capture

🎁 Complete Code

Full implementation: GitHub Repository

Quick Start Commands:

# Clone
git clone https://github.com/ConnectSafelyAI/agentic-framework-examples.git
cd agentic-framework-examples/extract-linkedin-premium-users-from-linkedin-groups/agentic/langGraph

# Install
bun install

# Configure
cp .env.example .env
# Edit .env with your ConnectSafely.ai token

# Run
bun start
Enter fullscreen mode Exit fullscreen mode

💡 Key Takeaways

  1. ConnectSafely.ai eliminates LinkedIn automation complexity

    • No scraping required
    • No account bans
    • Enterprise-ready infrastructure
  2. LangGraph enables agentic workflows

    • Natural language interface
    • Multi-step automation
    • Extensible architecture
  3. Together, they're powerful

    • Build complex workflows in hours, not months
    • Focus on business logic, not infrastructure
    • Scale reliably

📚 Official Documentation

💬 Support Channels

🌐 Connect With Us

Stay updated with the latest automation tips, LinkedIn strategies, and platform updates:


Top comments (0)