SocialAPIs
Sources
PricingBlogFAQContact
← Back to blog
ai-agentslangchaintutorial

Build an AI Social Media Agent with LangChain

Step-by-step build of an AI social agent that monitors Facebook pages, summarizes activity, and alerts on changes — using LangChain, the SocialAPIs REST API, and a small Python harness.

SocialAPIs Team·January 15, 2025

Learn how to build a powerful AI agent that can analyze social media data using LangChain and SocialAPIs.

Introduction

AI agents are transforming how we interact with data. In this tutorial, we'll build an agent that can:

  • Fetch social media metrics on demand
  • Analyze engagement patterns
  • Generate insights and recommendations
  • Answer questions about social media performance

Prerequisites

Before we start, make sure you have:

  • Python 3.9+
  • A SocialAPIs API key (get one free)
  • Basic knowledge of Python and APIs

Architecture Overview

Our AI agent will use a simple but powerful architecture:

  1. User Input → Natural language query
  2. LangChain Agent → Interprets the query and decides which tools to use
  3. SocialAPIs Tools → Fetch data from social media platforms
  4. Response Generation → Format and present the results

Step 1: Install Dependencies

bash
1pip install langchain openai requests python-dotenv

Step 2: Set Up Environment

Create a

bash
1.env
file:

bash
1OPENAI_API_KEY=your_openai_key
2SOCIALAPIS_API_KEY=your_socialapis_key

Step 3: Create the SocialAPIs Tool

python
1import os
2import requests
3from langchain.tools import BaseTool
4from dotenv import load_dotenv
5
6load_dotenv()
7
8class FacebookPageTool(BaseTool):
9    name = "facebook_page_details"
10    description = "Get details about a Facebook page including followers, likes, and engagement metrics. Input should be a Facebook page URL."
11
12    def _run(self, url: str) -> str:
13        api_key = os.getenv("SOCIALAPIS_API_KEY")
14        response = requests.get(
15            "https://api.socialapis.io/facebook/pages/details",
16            params={"link": url},
17            headers={"x-api-token": api_key}
18        )
19        
20        if response.ok:
21            data = response.json()
22            return f"""
23            Page: {data.get('name')}
24            Followers: {data.get('followers', 0):,}
25            Likes: {data.get('likes', 0):,}
26            Category: {data.get('category', 'N/A')}
27            """
28        return f"Error: {response.text}"
29
30    def _arun(self, url: str):
31        raise NotImplementedError("Async not supported")

Step 4: Create the Agent

python
1from langchain.agents import initialize_agent, AgentType
2from langchain.chat_models import ChatOpenAI
3
4# Initialize the LLM
5llm = ChatOpenAI(temperature=0, model="gpt-4")
6
7# Create tools
8tools = [FacebookPageTool()]
9
10# Initialize agent
11agent = initialize_agent(
12    tools,
13    llm,
14    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
15    verbose=True
16)

Step 5: Run the Agent

python
1# Ask the agent questions
2response = agent.run("What are the follower counts for Nike's Facebook page?")
3print(response)
4
5# More complex queries
6response = agent.run("Compare the engagement of Nike and Adidas on Facebook")
7print(response)

Example Output

bash
1> Entering new AgentExecutor chain...
2I need to get the Facebook page details for Nike.
3Action: facebook_page_details
4Action Input: https://facebook.com/nike
5Observation: 
6Page: Nike
7Followers: 38,500,000
8Likes: 38,400,000
9Category: Sports & Recreation
10
11Final Answer: Nike's Facebook page has 38.5 million followers and 38.4 million likes.

Adding More Tools

You can extend the agent with more SocialAPIs tools:

python
1class FacebookPostsTool(BaseTool):
2    name = "facebook_page_posts"
3    description = "Get recent posts from a Facebook page. Input should be a Facebook page URL."
4
5    def _run(self, url: str) -> str:
6        api_key = os.getenv("SOCIALAPIS_API_KEY")
7        response = requests.get(
8            "https://api.socialapis.io/facebook/pages/posts",
9            params={"link": url},
10            headers={"x-api-token": api_key}
11        )
12        
13        if response.ok:
14            data = response.json()
15            posts = data.get('posts', [])[:5]
16            result = "Recent posts:\n"
17            for i, post in enumerate(posts, 1):
18                result += f"{i}. {post.get('text', '')[:100]}...\n"
19                result += f"   Likes: {post.get('likes', 0)}, Comments: {post.get('comments', 0)}\n"
20            return result
21        return f"Error: {response.text}"

Using with MCP (Claude Desktop)

For an even simpler setup, use our MCP server with Claude Desktop:

json
1{
2  "mcpServers": {
3    "socialapis": {
4      "command": "npx",
5      "args": ["-y", "@socialapis/mcp", "YOUR_API_KEY"]
6    }
7  }
8}

Then just ask Claude natural language questions about social media!

Conclusion

You've built a powerful AI agent that can:

  • Understand natural language queries
  • Fetch real social media data
  • Provide actionable insights

Next Steps

  • Add more platforms (Instagram, TikTok)
  • Implement caching for faster responses
  • Add memory for context-aware conversations
  • Deploy as a chatbot or API

Resources

  • SocialAPIs Documentation
  • LangChain Documentation
  • Full Code on GitHub

Questions? Join our community or check our documentation.

Try the SocialAPIs platform

Build on Facebook + Instagram data today (TikTok, X, LinkedIn, and YouTube on the roadmap). 200 free calls / month, no card.

Create a free account

More from the blog

Announcing: SocialAPIs is Now Available in MCP Registry!

We shipped first-class Model Context Protocol support. Claude Desktop, ChatGPT Custom Integrations, Cursor, an…

The Complete Guide to Building AI Agents

A practical guide to building production-grade AI agents — tool calling, memory, orchestration, deploying with…

SocialAPIs

The unified API for social media data. Built for developers and AI agents.

Now in MCP Registry

Product

  • API Reference
  • Pricing
  • Documentation
  • Blog
  • Compare vs others
  • MCP Server

Free Tools

  • Network Inspector
  • Visual Selector
  • JSON Selector
  • cURL Converter
  • Leads Generator
  • Hashtag Generator
  • JSON Formatter
  • URL Encoder

Libraries

  • Network Library
  • Cheerio Library

Resources

  • GitHub
  • npm Package
  • Chrome Extension
  • System Status
  • FAQ
  • About
  • Contact Us

Legal

  • Privacy Policy
  • Terms of Service

© 2026 SocialAPIs. All rights reserved.