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/...
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
-
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
-
Google Cloud Project (for Gemini + Sheets)
- Enable Gemini API
- Set up Google Sheets OAuth
Bun installed
curl -fsSL https://bun.sh/install | bash
🎬 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
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 })
});
ConnectSafely.ai Features We'll Use:
-
Group Members Extraction
- Fetch members from any LinkedIn group
- Automatic pagination
- Rich profile data (premium status, verification, badges)
-
Premium Member Detection
- Identifies LinkedIn Premium subscribers
- Filters verified accounts
- Extracts profile badges
-
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]
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
Step 2: Install Dependencies
bun install
Step 3: Configure Environment
cp .env.example .env
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
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(),
}),
}
);
What's happening:
- ✅ ConnectSafely.ai handles LinkedIn authentication
- ✅ ConnectSafely.ai fetches group members
- ✅ ConnectSafely.ai provides rich profile data
- ✅ 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();
}
The Magic: LangGraph orchestrates, ConnectSafely.ai executes!
🎮 Part 5: Running the Agent
Interactive Mode (Chat with the Agent)
bun start
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
One-Shot Mode (Single Command)
bun start "Extract 50 premium members from group 9357376 and save to Google Sheets"
🔍 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
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
📊 Real-World Use Cases
1. Lead Generation
You: "Extract all premium members from the 'B2B SaaS Founders' group and save to sheets"
→ Instant qualified lead list
2. Competitor Analysis
You: "Get premium members from group 555 and group 666, combine them"
→ Identify key players in your industry
3. Community Building
You: "Extract verified members from 5 different AI/ML groups"
→ Find potential community members
4. Recruitment
You: "Get premium members with 'CTO' or 'Engineering Manager' in headline from group 12345"
→ 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
});
Batch Processing
Process multiple groups:
const groupIds = ['111', '222', '333'];
for (const groupId of groupIds) {
const members = await fetchFromConnectSafely(groupId);
// Process each group
}
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
Solution: Check your ConnectSafely.ai API token
# Verify token is set
echo $CONNECTSAFELY_API_TOKEN
# Get new token from connectsafely.ai dashboard
Issue 2: "No premium members found"
✓ Fetched 100 members
✓ Filtered 0 premium members
Solution: The group might not have premium members, or try a larger sample:
You: "Extract 500 members from group 12345"
📈 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:
- For Small Groups (< 500 members):
You: "Extract all premium members from group 12345"
- For Large Groups (> 1000 members):
You: "Extract premium members from group 12345, max 200"
- For Multiple Groups: Use batch processing or run multiple agents in parallel
🔮 What's Next?
Potential Enhancements:
-
Multi-Account Support
- Use ConnectSafely.ai's multi-account features
- Rotate between accounts for higher limits
-
Enrichment Pipeline
- Fetch member profiles with ConnectSafely.ai
- Enrich with additional APIs
- Score leads automatically
-
Automated Outreach
- Use ConnectSafely.ai's messaging features
- Send personalized connection requests
- Track response rates
-
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
💡 Key Takeaways
-
ConnectSafely.ai eliminates LinkedIn automation complexity
- No scraping required
- No account bans
- Enterprise-ready infrastructure
-
LangGraph enables agentic workflows
- Natural language interface
- Multi-step automation
- Extensible architecture
-
Together, they're powerful
- Build complex workflows in hours, not months
- Focus on business logic, not infrastructure
- Scale reliably
📚 Official Documentation
💬 Support Channels
- Email Support: support@connectsafely.ai
- Custom Workflows: Contact us for custom automation
🌐 Connect With Us
Stay updated with the latest automation tips, LinkedIn strategies, and platform updates:
Top comments (0)