Grounding an LLM with Live Social Media Data (Why It Beats RAG for Current Facts)

Published · 17 min read

Grounding an LLM with Live Social Media Data (Why It Beats RAG for Current Facts)

To ground an LLM with social media data, give the model a tool that fetches the public profile at query time, run the tool call when the model asks for it, and return the JSON as context before the model answers. For live facts such as follower counts, use a real-time read and not RAG over stale documents. The answer should also cite whether the count is exact and when it was read.

Key facts

This guide is part of our hub on social media data for AI agents. It covers the grounding pattern from start to finish: why models get social facts wrong, why RAG is the wrong fix, a runnable Anthropic tool-use loop, provenance handling, caching, cost, and a no-code MCP path.

Why do LLMs get follower counts wrong?

A language model's knowledge stops at its training cutoff. Follower counts, latest posts, bios, and verification badges change daily. When you ask a model for a current number, it usually does not say it doesn't know. It produces a plausible figure from patterns it saw months earlier.

The typical failure looks like this (illustrative, not a real transcript):

User: How many Instagram followers does Cristiano Ronaldo have? Ungrounded model: Cristiano Ronaldo has around 600 million Instagram followers, making him the most-followed person on the platform.

The tone is confident and the number is wrong. The live read on 2026-12-04 returned 679,519,176. The model has no way to know whether its figure is current, rounded, or invented, and it presents all three cases the same way.

Three kinds of social facts drift fastest and produce the most hallucinations:

Fact type How fast it moves Ungrounded failure mode
Follower and following counts Continuously, often minute to minute on large accounts Outdated or rounded number stated as fact
Latest posts Whenever the account posts Describes old posts as recent, or invents posts
Verification, privacy, bio, display name Occasionally, without notice Reports a badge or bio that has changed

The cause is that the model's weights don't contain today's value. Prompt engineering cannot supply information the model never saw. The only fix is to put the current value into the context window.

Why is RAG the wrong tool for live social facts?

Classic retrieval-augmented generation (RAG) embeds a document corpus ahead of time, stores the vectors, and retrieves the closest chunks at query time. That works well for stable knowledge such as product docs, policies, research papers, or a creator's past interviews. It fails for live facts because the value is frozen at the moment you embedded it.

The original data: two reads, same account, same day

We read the same public X profile twice on 2026-12-04 through the SocialLens profile endpoint. We also read one Instagram profile to anchor the grounding example below.

Account Platform Read Followers returned is_exact Change vs. earlier read
@elonmusk X Earlier read, 2026-12-04 239,280,966 not shown here n/a
@elonmusk X Later read, 2026-12-04 239,281,504 not shown here +538
@cristiano Instagram Single read, 2026-12-04 679,519,176 true n/a

Methodology: live calls to GET https://api.sociallens.dev/v1/profile against public profiles. The two X reads were a few hours apart. No figures are estimated or interpolated.

Data last verified: 2026-12-04

Suppose you had embedded the first X reading into a vector store at breakfast. By the afternoon your retriever would return a number 538 followers behind, and nothing in the RAG pipeline would flag it. Re-embedding on a schedule shrinks the gap without closing it, and you pay embedding costs to keep a lagging copy of a number the API can give you directly.

Is this RAG?

Partly. It is retrieval-augmented, but the retrieval step is a real-time API call made at question time, not a vector search over documents embedded earlier. Use RAG for stable knowledge. Use live retrieval (a tool call) for facts that change, such as follower counts, latest posts, and verification status.

Question Classic RAG (vector store) Live retrieval (tool call)
What is the data source? Documents you embedded earlier The source, read at query time
How fresh is it? As old as your last indexing run As fresh as the read (fetched_at)
Best for Docs, policies, transcripts, history Counts, latest posts, bios, badges
Exact numbers? Whatever text was scraped, often rounded is_exact tells you per read
Failure mode Silent staleness Visible errors (404, rate limit) you can handle

Many production agents use both: RAG for background knowledge and a live tool for current facts. The rule is simple. For live facts, ground with a real-time read, not RAG over stale documents. For more on choosing between tool styles, see MCP vs. API for AI agent social media data.

How do I ground a model with a live API call?

You define a tool, let the model decide when to call it, run the call yourself, and return the result. Anthropic's tool use and the Model Context Protocol both follow this pattern. The loop has five steps:

  1. Declare the tool. Name it get_social_profile and give it an input schema with platform and username.
  2. Send the user question plus the tool definition to the model.
  3. The model returns a tool_use block when it needs a live fact. It includes the arguments it chose.
  4. Your handler calls SocialLens (GET /v1/profile) and sends the JSON back as a tool_result.
  5. Call the model again. It now answers from the returned data and cites it.

The SocialLens call on its own

Test the read before wiring up the model:

curl -s "https://api.sociallens.dev/v1/profile?platform=instagram&username=cristiano" \
  -H "Authorization: Bearer sk_live_YOUR_KEY"

The response from the 2026-12-04 read is below, trimmed. Values shown as ... are elided because they are long or not needed for this example. All values shown are from the live read.

{
  "exists": true,
  "username": "cristiano",
  "platform": "instagram",
  "nickname": "Cristiano Ronaldo",
  "verified": true,
  "private": false,
  "followers": 679519176,
  "is_exact": true,
  "following": 640,
  "likes": "...",
  "videos": 4164,
  "bio": "...",
  "avatar": "https://...",
  "id": "...",
  "created_at": "...",
  "external_link": "...",
  "category": "...",
  "fetched_at": "2026-12-04T...Z",
  "cached": "...",
  "source_cached": "...",
  "credits": { "...": "..." }
}

Every network returns the same field names. A YouTube read has the same followers, is_exact, and fetched_at keys, with is_exact: false because YouTube publishes only rounded subscriber counts (see the YouTube Data API docs). Your tool handler never needs per-platform parsing. That is the point of a unified social media data API.

The full Anthropic tool-use loop in Python

This script is complete and runnable. It needs pip install anthropic requests and two environment variables: ANTHROPIC_API_KEY and SOCIALLENS_API_KEY. The example uses claude-sonnet-5-5, but any current Claude model that supports tool use will work.

import json
import os

import anthropic
import requests

SOCIALLENS_KEY = os.environ["SOCIALLENS_API_KEY"]  # sk_live_YOUR_KEY
MODEL = "claude-sonnet-5-5"  # any capable tool-use model works

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment

TOOLS = [
    {
        "name": "get_social_profile",
        "description": (
            "Read the live public profile of a social media account. Returns "
            "followers, following, verified, bio, is_exact (true if the follower "
            "count is exact, false if the platform only exposes a rounded number) "
            "and fetched_at (ISO time of the read). Use for any question about "
            "current follower counts, verification, bio, or account status."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "platform": {
                    "type": "string",
                    "description": "Network, e.g. instagram, tiktok, youtube, x, "
                    "reddit, facebook, threads, linkedin, pinterest",
                },
                "username": {
                    "type": "string",
                    "description": "Handle without the @ sign",
                },
            },
            "required": ["platform", "username"],
        },
    }
]

SYSTEM = (
    "You answer questions about social media accounts. For any current fact "
    "(follower counts, verification, bio, account status) call "
    "get_social_profile instead of relying on memory. In the answer, state the "
    "number, say whether it is exact or rounded using is_exact, and cite the "
    "read date from fetched_at. Never present a rounded number as exact. If the "
    "tool returns an error or exists is false, say so plainly."
)


def get_social_profile(platform: str, username: str) -> dict:
    resp = requests.get(
        "https://api.sociallens.dev/v1/profile",
        params={"platform": platform, "username": username.lstrip("@")},
        headers={"Authorization": f"Bearer {SOCIALLENS_KEY}"},
        timeout=30,
    )
    resp.raise_for_status()
    return resp.json()


def ask(question: str) -> str:
    messages = [{"role": "user", "content": question}]

    while True:
        response = client.messages.create(
            model=MODEL,
            max_tokens=1024,
            system=SYSTEM,
            tools=TOOLS,
            messages=messages,
        )

        if response.stop_reason != "tool_use":
            return "".join(b.text for b in response.content if b.type == "text")

        # Keep the assistant turn (including tool_use blocks) in the history.
        messages.append({"role": "assistant", "content": response.content})

        tool_results = []
        for block in response.content:
            if block.type != "tool_use":
                continue
            try:
                data = get_social_profile(**block.input)
                tool_results.append({
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": json.dumps(data),
                })
            except Exception as exc:  # surface failures to the model honestly
                tool_results.append({
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": f"Error reading profile: {exc}",
                    "is_error": True,
                })

        messages.append({"role": "user", "content": tool_results})


if __name__ == "__main__":
    print(ask("How many Instagram followers does Cristiano Ronaldo have right now?"))

Why it is written this way:

How do I keep the answer honest (is_exact and fetched_at)?

A grounded answer should carry three things: the value, its precision, and its timestamp. SocialLens provides all three in each response, so the model only has to report them.

Before (ungrounded, illustrative):

Cristiano Ronaldo has around 600 million Instagram followers.

After (grounded with the live read):

As of 2026-12-04, @cristiano has 679,519,176 Instagram followers. This is an exact count read live from the public profile. The account is verified and follows 640 accounts.

The grounded version can be audited. A reader, a reviewer, or another agent can see where the number came from and when it was valid.

What each provenance field means for the answer

Field Value example What the agent must do
is_exact true May state the full number, for example 679,519,176
is_exact false Must label it as approximate ("about", "roughly", "as displayed by the platform")
fetched_at ISO timestamp Use it as the as-of date in the answer
cached / source_cached boolean If served from cache, the as-of time is fetched_at, not "right now"
exists false Say the account was not found. Do not guess a similar handle.

The most common honesty bug in grounded agents is turning a rounded figure into false precision. YouTube publishes subscriber counts rounded to three significant figures, so the API cannot return an exact value there, and is_exact: false tells you so. If your agent rewrites "2.3M" as "2,300,000 subscribers," it has made up precision that the source never had. For how precision varies across networks, see how accurate social media follower counts are.

Add a check after generation if you can't rely on the prompt alone. If any tool result had is_exact: false, scan the final text for a long unrounded integer and regenerate or rewrite it if one appears.

What should I ground, and when?

Ground a question when the correct answer depends on the state of an account today. Skip grounding when the training data already answers it. Unneeded tool calls add latency and cost, and they don't improve answers to static questions.

Question Ground it? Why
"How many followers does @handle have?" Yes Changes continuously
"Is @handle verified?" / "Is it private?" Yes Status changes without notice
"What did @handle post this week?" Yes, with the profile posts read Latest posts are by definition newer than training data
"What does @handle's bio say?" Yes Bios are edited often
"Compare @a on TikTok and @b on Instagram" Yes, two calls Same schema, so the comparison is direct
"What is an engagement rate?" No Stable definition
"When was Instagram founded?" No Historical fact
"Write a caption in this creator's style" Optional RAG over past posts is fine here, since style changes slowly

Besides profiles, SocialLens reads public profile posts, a single post by URL, post comments, follower and following listings (TikTok), keyword search, video transcripts, and audience demographics. Each can be its own tool. Start with get_social_profile, then add tools only when users actually ask those questions. Models choose between tools more reliably when there are fewer, clearly described options. For a fuller multi-tool design, see building a social media profile analysis AI agent.

Data the agent can and cannot read

This read-only boundary matters for agents. A model that misreads an instruction cannot cause a write action through this tool, because the tool has no write actions.

How do caching and cost work?

Each grounding call uses credits, and each response includes a credits object, so your agent can track spending per request. Three controls keep costs in proportion to value.

1. Only ground when needed. The system prompt and tool description decide whether the model calls the tool. A narrow description ("use for current counts, status, bio") avoids calls on definitional questions. Log tool-call rates for a week and tighten the description if the model calls the tool for questions it could answer from memory.

2. Choose a freshness window per fact type. Use cached and source_cached to tell whether a read was fresh. Then decide what staleness each use case can tolerate:

Use case Reasonable freshness window (guidance, tune to your product)
Live chat answer to "how many followers right now" Fresh read, or a few minutes
Daily creator dashboard Hours
Weekly influencer shortlist A day
Historical trend chart Store each read with its fetched_at and never overwrite it

3. Cache in your own layer by (platform, username). Store the whole response, including fetched_at. If a cached entry is inside your window, return it to the model as the tool result. The model still sees the original fetched_at and cites the correct as-of time. This differs from RAG because the timestamp travels with the value, and a stale entry expires by rule rather than staying in an index indefinitely.

import time

_cache: dict[tuple[str, str], tuple[float, dict]] = {}
MAX_AGE_SECONDS = 300  # tune per use case

def get_social_profile_cached(platform: str, username: str) -> dict:
    key = (platform, username.lower().lstrip("@"))
    hit = _cache.get(key)
    if hit and time.time() - hit[0] < MAX_AGE_SECONDS:
        return hit[1]  # original fetched_at is preserved inside the payload
    data = get_social_profile(platform, username)
    _cache[key] = (time.time(), data)
    return data

Swap get_social_profile for get_social_profile_cached in the loop and nothing else changes.

On price, this guide doesn't quote figures that could go out of date. Check current rates on the SocialLens pricing and keys pages. The tradeoff to understand: data APIs bill per request, per unit, per credit, or by subscription. Per-request or per-credit billing fits grounding best, because you pay only when a question needs a live fact. A large flat subscription fits bulk analytics better than conversational grounding. If you are evaluating per-call follower data specifically, see the follower count API guide.

Does this work with Claude, Cursor, and ChatGPT?

Yes. You can skip the SDK loop above. The SocialLens MCP server exposes get_social_profile and the other read tools to any MCP client, and the client runs the tool-use loop for you. The server runs locally over stdio through npx. There is no remote SocialLens MCP URL to paste into a dashboard. If MCP is new to you, start with what an MCP server is.

The flow, with the trust boundary marked:

Your question
    |
    v
AI agent (Claude Code / Claude Desktop / Cursor)
    |
    v
MCP client  --stdio-->  sociallens-mcp (runs locally via npx)
                              |
                              |  HTTPS, Authorization: Bearer sk_live_...
                              v
                   +--------------------------------------------+
                   | READ-ONLY. PUBLIC DATA ONLY. NO LOGIN.     |
                   | Public profiles and posts on 17 networks   |
                   +--------------------------------------------+

Get a key at sociallens.dev/keys (new accounts: sociallens.dev/register). Agent docs are at sociallens.dev/agents.

Claude Code

Run one command. See the Claude Code MCP docs for scopes and options.

claude mcp add --env SOCIALLENS_API_KEY=sk_live_YOUR_KEY --transport stdio sociallens -- npx -y sociallens-mcp

Then ask: "How many Instagram followers does @cristiano have? Say whether it is exact and when it was read." Claude Code will call get_social_profile and answer from the result. More Claude-specific patterns are in Claude and social media data.

Claude Desktop and Cursor

Both use the same block. Put it in claude_desktop_config.json for Claude Desktop, or in .cursor/mcp.json for Cursor:

{
  "mcpServers": {
    "sociallens": {
      "command": "npx",
      "args": ["-y", "sociallens-mcp"],
      "env": { "SOCIALLENS_API_KEY": "sk_live_YOUR_KEY" }
    }
  }
}

Fully quit and reopen the app afterward. Closing the window is not enough.

ChatGPT

ChatGPT doesn't run local stdio MCP servers, so use one of two paths:

  1. Custom GPT: create a GPT, add an Action, and import the OpenAPI file at https://sociallens.dev/openapi.json. Set authentication to API key (Bearer) with your sk_live_YOUR_KEY. The step-by-step version is in ChatGPT social media data with a Custom GPT.
  2. Function calling in your own app: declare a function with the same platform and username parameters and have your handler make the same GET /v1/profile request shown above.

Add the same honesty rules from the system prompt to the GPT's instructions so it reports is_exact and fetched_at.

Agent frameworks

Any framework that accepts a Python function as a tool can wrap get_social_profile from the script above. Frameworks that support MCP can launch npx -y sociallens-mcp as a stdio server with SOCIALLENS_API_KEY in its environment. Either way, the grounding contract stays the same: live read in, value plus precision plus timestamp out. To compare MCP servers for this use case, see the best social media MCP server.

SocialLens also publishes a no-key lookup page for AI crawlers that shows a live, dated figure. An assistant reading SocialLens content can check a current number itself without credentials.

SocialLens reads only publicly visible data, never logs in, and never accesses private accounts, DMs, or sessions. In hiQ Labs v. LinkedIn, the Ninth Circuit held that scraping publicly accessible data likely does not violate the Computer Fraud and Abuse Act. That case turned on federal anti-hacking law and does not resolve every question.

Some risk remains. Platform terms of service can still restrict automated access. If you store or profile identifiable individuals, privacy laws such as GDPR and CCPA can apply to your processing. Minimize what you keep, keep fetched_at so you know how old a record is, and have a reason for each account you look up. This is not legal advice.

Troubleshooting the grounding setup

The model answers from memory instead of calling the tool. Make the tool description concrete ("use for current follower counts") and add a system prompt rule that current facts must come from the tool. With the SDK, check that tools=TOOLS is actually passed on every messages.create call in the loop.

400 error about tool_result without a matching tool_use. You appended the tool results without first appending the assistant turn. Append response.content as an assistant message, then the tool results as a user message, in that order.

SocialLens returns 401 or 403. The key is missing, mistyped, or not being sent. Check that the header is exactly Authorization: Bearer sk_live_... and that the environment variable is set in the process that makes the call. In MCP configs, the key belongs in env, not args. SocialLens has no OAuth flow in the stdio setup. A 401 means the key was rejected.

MCP server never appears (Claude Desktop or Cursor). Usually the JSON is malformed. A trailing comma or an unescaped quote silently disables every server in the file. Validate the file, then fully restart the app.

npx not found or the server exits immediately. GUI apps often don't inherit your shell PATH. Install Node.js, then set "command" to the absolute path of npx (run which npx on macOS or Linux, where npx on Windows). Use absolute paths for anything path-based, because the app's working directory is not your project folder.

Cursor uses the wrong key or server version. Cursor reads both a global ~/.cursor/mcp.json and a project .cursor/mcp.json. If both define sociallens, check Cursor's MCP settings panel to see which one is active, and remove the duplicate so only one definition remains.

A client only supports remote HTTP MCP servers. sociallens-mcp is stdio. Either run it behind a stdio-to-HTTP bridge you control, or use the plain REST call or the OpenAPI import instead.

The grounded answer shows an exact-looking YouTube number. The model ignored is_exact: false. Strengthen the system prompt rule and add the post-generation check described in the honesty section.

FAQ

How do I ground an LLM with live social media data?

Give the model a tool such as get_social_profile, run the real API call when the model requests it, return the JSON as a tool result, and let the model answer from it. Include is_exact and fetched_at so the answer states precision and the as-of date.

Why not just use RAG for follower counts?

RAG retrieves values embedded earlier, so counts are stale from the moment they are indexed. On 2026-12-04, X @elonmusk changed by 538 followers between two reads a few hours apart. Live facts need a live read at query time.

What does is_exact mean?

is_exact: true means the platform exposes a precise follower count. false means only a rounded figure is published, as with YouTube subscribers. A grounded answer should label rounded numbers as approximate and never present them as exact.

What is fetched_at used for?

fetched_at is the ISO timestamp of the read. Use it as the as-of date in the answer, for example "as of 2026-12-04." If the response came from cache, it still reflects when the value was actually read.

Can the agent read private accounts or DMs?

No. SocialLens is read-only and public-data-only. It never logs in, never uses sessions, and cannot read private profiles, DMs, or logged-in feeds. A private account returns private: true with only its public fields.

Which networks can I ground against?

Seventeen: TikTok, Instagram, YouTube, Facebook, X, Reddit, LinkedIn, Threads, Pinterest, Telegram, Bluesky, Truth Social, Cosmos, SoundCloud, Kwai, GitHub, and Spotify. They share one API key and one JSON schema.

Which Claude model should I use for the tool-use loop?

Any current Claude model with tool use works. The example uses claude-sonnet-5-5. Choose based on your latency and cost needs, since the grounding loop is identical across models.

Does this work in ChatGPT?

Yes, but not as a local MCP server. Build a Custom GPT and import https://sociallens.dev/openapi.json as an Action, or use function calling in your own app with the same GET /v1/profile request.

How do I control the cost of grounding?

Ground only questions that need current facts, cache responses by platform and username within a freshness window, and track the credits object in each response. Narrow tool descriptions reduce unnecessary calls.

Do I need to write code to ground Claude or Cursor?

No. Add the SocialLens MCP server with one claude mcp add command, or with the shared JSON block in Claude Desktop or Cursor. The client then calls get_social_profile whenever a question needs a live social fact.

Run these requests yourself

Every example on this page is a real call to the SocialLens API. A new account starts with 250 free reads, no card needed, and a read that fails is never charged.

Keep reading