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.
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:
- User Input → Natural language query
- LangChain Agent → Interprets the query and decides which tools to use
- SocialAPIs Tools → Fetch data from social media platforms
- Response Generation → Format and present the results
Step 1: Install Dependencies
1pip install langchain openai requests python-dotenvStep 2: Set Up Environment
Create a
1.env1OPENAI_API_KEY=your_openai_key
2SOCIALAPIS_API_KEY=your_socialapis_keyStep 3: Create the SocialAPIs Tool
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
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
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
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:
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:
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
Questions? Join our community or check our documentation.