> ## Documentation Index
> Fetch the complete documentation index at: https://www.outx.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# LangChain Integration, Build AI Agents with LinkedIn Data

> Use OutX as a tool in LangChain agents to fetch LinkedIn profiles, monitor posts, and automate engagement with AI-generated responses.

Use OutX as a [LangChain tool](https://python.langchain.com/docs/how_to/#tools) to give your AI agents real-time access to LinkedIn data, fetch profiles, retrieve posts, and engage with content.

## What You Can Build

* **Research agent**, fetch LinkedIn profiles and posts, summarize them, generate outreach
* **Sales signal agent**, monitor watchlists for buying intent, auto-generate personalized comments
* **Competitive intelligence agent**, track competitor mentions, summarize trends

## Prerequisites

* Python 3.9+
* `pip install langchain langchain-openai requests`
* OutX API key ([get yours](https://mentions.outx.ai/api-doc))
* OutX Chrome extension installed and active

## OutX Tools for LangChain

Create custom tools that wrap OutX API endpoints:

```python theme={null}
import os
import time
import requests
from langchain.tools import tool

OUTX_API_KEY = os.environ["OUTX_API_KEY"]
BASE_URL = "https://api.outx.ai"
HEADERS = {"x-api-key": OUTX_API_KEY, "Content-Type": "application/json"}


@tool
def fetch_linkedin_profile(profile_slug: str) -> dict:
    """Fetch a LinkedIn profile by slug. Returns name, headline, location, experience."""
    # Create task
    resp = requests.post(
        f"{BASE_URL}/linkedin-agent/fetch-profile",
        headers=HEADERS,
        json={"profile_slug": profile_slug},
    )
    task_id = resp.json()["api_agent_task_id"]

    # Poll for result
    for _ in range(30):
        result = requests.get(
            f"{BASE_URL}/linkedin-agent/get-task-status",
            headers={"x-api-key": OUTX_API_KEY},
            params={"api_agent_task_id": task_id},
        ).json()

        if result["data"]["status"] == "completed":
            return result["data"]["task_output"]
        if result["data"]["status"] == "failed":
            return {"error": "Task failed", "output": result["data"]["task_output"]}

        time.sleep(5)

    return {"error": "Task timed out"}


@tool
def get_watchlist_posts(watchlist_id: str, page: int = 1) -> dict:
    """Get recent LinkedIn posts from a watchlist. Returns post content, author, engagement metrics."""
    resp = requests.get(
        f"{BASE_URL}/api-posts",
        headers={"x-api-key": OUTX_API_KEY},
        params={
            "watchlist_id": watchlist_id,
            "sort_by": "recent_first",
            "page": page,
        },
    )
    return resp.json()


@tool
def comment_on_post(post_id: str, user_email: str, comment_text: str) -> dict:
    """Comment on a LinkedIn post from a watchlist. Requires post_id from get_watchlist_posts."""
    resp = requests.post(
        f"{BASE_URL}/api-comment",
        headers=HEADERS,
        json={
            "post_id": post_id,
            "user_email": user_email,
            "comment_text": comment_text,
            "actor_type": "user",
        },
    )
    return resp.json()
```

## Build the Agent

```python theme={null}
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate

# Define tools
tools = [fetch_linkedin_profile, get_watchlist_posts, comment_on_post]

# Create prompt
prompt = ChatPromptTemplate.from_messages([
    ("system", """You are a LinkedIn research assistant. You can:
1. Fetch LinkedIn profiles to learn about people
2. Get posts from watchlists to find relevant conversations
3. Comment on posts (only when explicitly asked)

When fetching profiles, extract the profile slug from LinkedIn URLs.
For linkedin.com/in/williamhgates, the slug is 'williamhgates'.

Always be respectful and professional in any comments you generate."""),
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}"),
])

# Create agent
llm = ChatOpenAI(model="gpt-4o")
agent = create_tool_calling_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# Run
result = executor.invoke({
    "input": "Fetch the LinkedIn profile for williamhgates and summarize their background"
})
print(result["output"])
```

## Example: Sales Signal Agent

An agent that monitors your watchlist for buying intent and drafts personalized comments:

```python theme={null}
result = executor.invoke({
    "input": """Check watchlist WATCHLIST_ID for posts with buying intent
    (people asking for tool recommendations, comparing solutions, or expressing pain points).
    For the top 3 most relevant posts, draft a helpful comment that adds value
    without being salesy. Show me the drafts but do NOT post them yet."""
})
```

## Rate Limit Considerations

<Warning>
  **OutX is a proxy, it does not rate-limit LinkedIn Data API calls for you.** When using `fetch_linkedin_profile` in loops or agents, add delays between calls:

  ```python theme={null}
  import time
  # Between consecutive profile fetches
  time.sleep(30)
  ```

  See [Rate Limits](/api-reference/rate-limits) for safe usage guidelines per endpoint.
</Warning>

## Tips

* **Start with read-only tools**, get `fetch_linkedin_profile` and `get_watchlist_posts` working before adding engagement tools
* **Add human-in-the-loop** for engagement, use `HumanApprovalCallbackHandler` before posting comments
* **Cache profile data**, store fetched profiles locally to avoid redundant API calls
* **Use watchlists for monitoring**, don't poll the LinkedIn Data API repeatedly; create watchlists for ongoing tracking

## Related

* [AI Agent Onboarding](/ai), Skill file and guardrails for AI agents
* [OutX Skill File](https://outx.ai/docs/outx-skill.md), Full API reference for agents
* [LinkedIn Data Quick Start](/linkedin-api/quickstart), End-to-end fetch example
* [Use Cases](/api-reference/use-cases), Common API workflows

## Partnerships

Interested in a collaboration or affiliate partnership? Reach out at [support@outx.ai](mailto:support@outx.ai).

***

## Learn More

* [LinkedIn API Guide](https://www.outx.ai/blog/linkedin-api-guide)
* [Best AI Tools for LinkedIn](https://www.outx.ai/blog/best-ai-tools-linkedin)
