Build a Tweet Summarizer for Twitter (X): Cited AI Digests in Python

By TwitterAPI.io Team•14 min read
Five-step tweet summarizer pipeline: 1 Fetch with /twitter/user/last_tweets or advanced_search; 2 Dedupe, drop reposts and replies to other accounts, 51.0% removed; 3 Chunk with tiktoken o200k_base, about 8,762 tokens per 100 tweets; 4 Summarize with an LLM prompt citing [id] or an extractive top post per topic; 5 Verify each id, 6 of 6 re-fetched via /twitter/tweets.
Fetch, dedupe, chunk, summarize, verify. Measured on 584 timeline items from three organization accounts, collected in 2026.
TL;DR
  • Dedupe first: reposts were 39.7% and replies to other accounts 10.8% of 584 raw timeline items; removing them cut the model input by 18.8% to 64.9% per account.
  • Token budget: 100 deduped tweets, formatted as [id] date likes reposts | text, measured about 8,762 tokens with tiktoken o200k_base (mean 87.6 per tweet, p95 139).
  • Chunks: 100 tweets need 6 chunks at 2k tokens, 3 at 4k, 2 at 8k and 1 at 16k; map-reduce only when you exceed one chunk.
  • Citations you can check: ask for [tweet_id] at the end of each bullet, then drop any bullet whose id was not in the input. Our extractive baseline digest passed that check 6 of 6, and all 6 ids came back from /twitter/tweets.
  • Cost per digest: about $0.03 to fetch 200 timeline items, plus about $0.0010 of model tokens on gpt-6-luna list prices or $0.021 on gpt-6.2-sol.
  • Scope: this is for many tweets from an account or a keyword. To read one long thread, unroll it first with the thread tools linked below.

This guide builds a tweet summarizer you own: point it at an X (Twitter) account or a keyword, and it returns a short digest in which every bullet links to the tweet it came from. It differs from unrolling a Twitter thread, which stitches one author's reply chain into a single article; here the input is dozens or hundreds of separate posts, and the hard parts are filtering, token budgets and keeping the model honest about its sources.

Browser extensions and thread-summarizer web apps exist for reading one tweet or one thread at a time. They do not help when you want a daily digest of a competitor's account, a weekly summary of a product keyword, or summaries feeding a newsletter or a Slack channel. For that you need the raw tweets as JSON, a dedupe step, a prompt that forces citations, and code that checks those citations. All of it fits in about 150 lines of Python.

Every number on this page comes from a study we ran on three public organization accounts (@github, @NASA, @OpenAIDevs), collected in 2026: what share of a raw timeline is noise, how many tokens 100 tweets really cost, how many chunks that makes, and an extractive digest whose tweet ids we re-fetched. We did not call a paid LLM for this page, so no model output is shown as if it ran; the prompt and SDK call are given per the provider's documentation.

Share of a raw timeline removed before the LLM call

51.0% of 584 timeline items from @github, @NASA and @OpenAIDevs were reposts, replies to other accounts or repeats (collected in 2026). The 100 deduped tweets that remain are about 8,762 input tokens: one 16k chunk.

01 — Section

What a tweet summarizer does (and what it leaves out)

A useful summarizer answers one question: what did this account, or this keyword, talk about over the last N posts, and where can I read each point in full? That breaks into five steps, shown in the diagram at the top: fetch, dedupe, chunk, summarize, verify. The first three are plain data work and decide what the model sees. The fourth is one API call per chunk. The fifth is what makes the digest trustworthy enough to send to someone else.

Inputs it handles. An account timeline (/twitter/user/last_tweets, 20 tweets per page, newest first) or a keyword search (/twitter/tweet/advanced_search with queryType=Latest). Both return the same tweet objects with id, text, createdAt, likeCount, retweetCount, replyCount, quoteCount, viewCount, isReply, inReplyToUsername, retweeted_tweet and quoted_tweet, which is everything the pipeline needs.

Out of scope. Rebuilding a single thread or reply tree. If your input is one long thread, unroll it with the Twitter thread reader tool or the conversation search shown in the unroll guide, then summarize the resulting text. Summarizing a home timeline is also out: that feed is personal to a logged-in user, while everything here reads public posts with no X account needed.

What the digest looks like. Five to eight bullets, one per topic, ordered by engagement, each ending with [tweet_id]. Your code turns the id into https://x.com/<account>/status/<id> and drops any bullet without a valid id. That rule is simple, and it is the difference between a summary and a plausible paragraph.

Stacked bar chart of timeline items by type. @github kept 149 of 200 items, reposts 24%. @NASA kept 84 of 184, reposts 38%, replies to other accounts 16%. @OpenAIDevs kept 53 of 200, reposts 56%, replies 16%. All three: 286 of 584 kept, 51.0% removed.
Dedupe removed 51.0% of 584 raw timeline items (includeReplies=true) across three organization accounts, collected in 2026.
02 — Section

Step 1: fetch the latest tweets of an account or a keyword

For an account, page /twitter/user/last_tweets with userName (or the steadier userId) and follow next_cursor while has_next_page is true. Per the endpoint docs, includeReplies defaults to false and each page returns up to 20 tweets, newest first; the pinned tweet comes back separately in data.pin_tweet, not in data.tweets. We set includeReplies=true in the study so the dedupe numbers below show what you would otherwise be filtering yourself; with the default you skip replies at the source.

For a keyword, use /twitter/tweet/advanced_search with queryType=Latest. Its tweets sit in a top-level tweets[] array rather than under data. A keyword digest attracts far more reposts and near-identical posts than an organization timeline, so the dedupe step matters even more there, and its raw pages belong in a temporary folder: those authors are individuals, so keep aggregates, not their handles.

What fetching costs. Tweet endpoints bill 15 credits per tweet returned, which is $0.15 per 1,000 tweets; a full 20-tweet page is $0.003 and a request that returns nothing still costs the $0.00015 minimum. A 200-item timeline (10 pages) is therefore $0.03. On the official X API's pay-per-usage card, a post read is $0.005, so the same 200 posts are $1.00, about 33x more per tweet; that card also caps pay-per-usage at 3 million post reads a month.

How far back 100 tweets reach. It depends on the account. In our sample the 200 newest items covered 21 days for @OpenAIDevs, 78 days for @github and 242 days for @NASA's timeline as returned, and after dedupe @github kept about 1.9 posts a day against 3.1 for @OpenAIDevs. Fetch by count for a fixed-size digest, or stop paging once createdAt passes your window start for a daily or weekly one.

python
import os, time, requests

BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}

def keyword_tweets(query, pages=5):
    """Latest tweets for a keyword or phrase; same tweet objects as last_tweets."""
    out, cursor = [], ""
    for _ in range(pages):
        r = requests.get(f"{BASE}/twitter/tweet/advanced_search", headers=HEADERS,
                         params={"query": query, "queryType": "Latest", "cursor": cursor}, timeout=30)
        r.raise_for_status()
        body = r.json()
        out += body.get("tweets", [])          # top-level tweets[] on this endpoint
        if not body.get("has_next_page"):
            break
        cursor = body.get("next_cursor") or ""
        time.sleep(1)                           # fixed pacing between pages
    return out
03 — Section

Step 2: dedupe before the model sees anything

Three filters do the work. Reposts carry another account's words, so they go (retweeted_tweet is set and the text starts with RT @). Replies to other accounts are usually one-line answers to support questions and add noise, so they go too; replies to the account itself are thread continuations and stay. Finally, the same text with a different link is a repeat, so we compare text with URLs stripped and whitespace collapsed.

AccountRaw itemsRepostsReplies to othersKept
@github20049 (24.5%)2 (1.0%)149
@NASA18470 (38.0%)30 (16.3%)84
@OpenAIDevs200113 (56.5%)31 (15.5%)53
All three584232 (39.7%)63 (10.8%)286

Repeated text was rare: 3 items, all on @OpenAIDevs. The spread between accounts is the point: @github's timeline was 74.5% original posts, while only 26.5% of @OpenAIDevs' survived, because that account reposts its team's posts heavily. If you skip dedupe on an account like that, the summary is mostly about other people's tweets, and you pay for those tokens.

Self-replies stay. @github had 35 self-replies and @OpenAIDevs 37: second and third posts of the account's own threads. They carry the details (links, numbers, dates) that the first post teases, so dropping them makes the digest vaguer. If you only want the opening post of each thread, group by conversationId instead.

04 — Section

Step 3: count tokens and decide the chunk size

Each kept tweet becomes one line: [id] date likes=N reposts=N | text. The id lets the model cite, the date lets it say when, and the two counts let it rank topics without you asking for a separate scoring pass. That framing costs tokens: text alone averaged about 61 to 65 tokens per tweet in our sample, the formatted line about 86 to 91.

AccountTokens per 100 keptp95 per tweetRaw vs kept tokens
@github8,61314115,813 to 12,834
@NASA9,13310813,337 to 7,672
@OpenAIDevs8,58912612,967 to 4,552
All three8,76213942,117 to 25,058

Packing whole tweets greedily and reserving 250 tokens per chunk for the instructions, 100 deduped tweets needed 6 chunks at a 2,000-token budget, 3 at 4,000, 2 at 8,000 and 1 at 16,000. All 286 kept tweets together needed 15, 7, 4 and 2 chunks at the same budgets.

Why chunk at all when context windows are huge? Per OpenAI's model page, gpt-6-luna accepts up to 922,000 input tokens, and per both providers' pricing pages a long prompt changes the rate: over 272K input tokens OpenAI bills 2x input and 1.5x output for the whole request, and Claude Haiku 5.5 moves from $0.10 to $0.50 per 1M input tokens above 100,000 tokens. At about 9,000 tokens per 100 tweets you stay far below both lines, so for a digest of a few hundred tweets one call is enough. Chunk when you go into thousands of tweets, or when you want each chunk's bullets to stay tied to a time window.

About the tokenizer. We counted with tiktoken 0.14.0 and the o200k_base encoding, which tiktoken maps to gpt-4o and the gpt-5 family. It has no mapping for gpt-6-luna (it raises "Could not automatically map"), so treat the counts as an estimate for that model and read the real number from the usage the API returns. Anthropic's pricing page says Claude 4.7 and later models use a newer tokenizer that produces about 30% more tokens for the same text, so count Claude prompts with Anthropic's token counting endpoint; our Claude token counter guide walks through it.

Bar chart of input tokens before and after dedupe. @github 15,813 to 12,834 (-18.8%), @NASA 13,337 to 7,672 (-42.5%), @OpenAIDevs 12,967 to 4,552 (-64.9%). Headline: 100 deduped tweets are about 8,762 input tokens.
Formatted input tokens (tiktoken o200k_base) for each account's whole timeline vs the deduped set, collected in 2026.
05 — Section

Step 4: the prompt and the LLM call (per the provider docs)

The prompt has three jobs: say what the input lines are, ask for a fixed number of topic bullets ordered by engagement, and require the tweet id at the end of every bullet, copied from the input. Telling the model not to invent ids does not make it so; it makes rejected bullets rare enough that dropping them is acceptable.

The call below follows OpenAI's text generation guide as published at the time of writing: client.responses.create(model=..., instructions=..., input=...), with the result read from response.output_text. The guide also warns that the text is not guaranteed to sit at output[0].content[0].text, which is why the code uses the convenience property. We did not run this call for the page (no paid LLM API was used), so we show no model output here; the extractive digest in the next section is what we actually computed.

Choosing a model. OpenAI's model list describes gpt-6-luna as its model "for focused, high-volume tasks", at $0.10 per 1M input tokens and $0.50 per 1M output tokens (Standard tier, short context). gpt-6.2-sol lists at $2.00 and $10.00 and is the step up when bullets need more judgment, for example merging three announcements into one topic. Anthropic lists Claude Haiku 5.5 at $0.10 input and $0.50 output per 1M tokens for prompts up to 100,000 tokens. The Batch API at either provider halves the token price if the digest can wait.

Map-reduce for big inputs. When there is more than one chunk, summarize each chunk with the same instructions, then send the partial bullet lists to one more call that merges duplicates and keeps every [tweet_id]. Because each partial bullet already carries its ids, the merged digest stays checkable. If you already use LangChain, its loaders and chains can drive the same steps; see the LangChain and Twitter (X) API guide.

python
from openai import OpenAI   # pip install openai; reads OPENAI_API_KEY

INSTRUCTIONS = """You summarize posts from one X (Twitter) account for a busy reader.
Input: one post per line as [tweet_id] date likes reposts | text.
Write 5 to 8 bullets, one per distinct topic, highest-engagement topics first.
Every bullet must end with the [tweet_id] of the post (or posts) it is based on,
copied exactly from the input. Do not invent facts, numbers or ids.
If a post is only a link or an emoji, skip it."""

client = OpenAI()
resp = client.responses.create(
    model="gpt-6-luna",          # any model id from the provider's model list
    instructions=INSTRUCTIONS,
    input=chunk_text,             # one chunk: ~100 formatted tweets fit in 16k tokens
)
digest = resp.output_text          # the SDK's convenience property (per the guide)
06 — Section

Step 5: verify that every bullet maps to a real tweet

A digest is only worth sending if each claim can be traced. The check has two layers. First, offline: every bullet must contain at least one [id], and every id must be in the set of ids you sent; anything else is dropped. Second, optional and cheap: re-fetch the cited ids with /twitter/tweets (comma-separated tweet_ids, up to 50 per request per the docs) and confirm they still exist. Per the docs, deleted, private or suspended-account tweets are not returned, and you should match results by id.

We ran the offline check on the 100 deduped @github tweets with a planted fake id. The real bullet passed, the bullet with an invented id and the bullet with no id were both rejected. Then we re-fetched the 6 ids of our extractive digest through /twitter/tweets: 6 of 6 came back, with the same text and the same author.

What the check does not prove. It proves the cited tweet exists and was in the input. It does not prove the bullet describes that tweet correctly. For that, compare each bullet against its tweet text, by eye for a weekly digest, or with a second cheap model call that answers yes or no per bullet-tweet pair.

python
import re

ID_RE = re.compile(r"\[(\d{6,25})\]")

def check_bullets(digest, valid_ids):
    """Split bullets into (cited, rejected): every [id] must be one we sent."""
    cited, rejected = [], []
    for line in digest.splitlines():
        if not line.strip().startswith(("-", "*")):
            continue
        ids = ID_RE.findall(line)
        (cited if ids and all(i in valid_ids for i in ids) else rejected).append(line.strip())
    return cited, rejected

# Run against the study input (100 deduped @github posts), with one planted fake id:
# check_bullets("- Copilot benchmark result [2115480207469560109]\n"
#               "- Invented claim [1234567890123456789]\n- No id here", ids)
# -> cited:    ['- Copilot benchmark result [2115480207469560109]']
#    rejected: ['- Invented claim [1234567890123456789]', '- No id here']
07 — Section

A real extractive digest of @github's last 100 posts

To have something concrete to check, we built a no-LLM baseline: take the 100 newest deduped @github posts (a 58-day window), find the keywords that appear in at least three posts, assign posts to keyword clusters greedily, and pick the post with the highest likes + reposts + replies + quotes in each cluster. Six clusters covered 76 of the 100 posts. The digest below is what that code returned; the text column is the opening of @github's own post, shortened.

Cluster keywordPost (opening words)EngagementTweet id
copilot (44 posts)Frontier performance at a fraction of the cost. ...9762115480207469560109
code (8 posts)17.9 billion pushes. 34.3 billion commits. 1.3 billion pull requests merged. ...1,0442115846384850989124
repo (6 posts)Through internal testing, GitHub's new Git storage architecture supported 5,000 concurrent agents ...1,4572118830274431873379
githubuniverse (9 posts)How many donuts were eaten at #GitHubUniverse? ...4552119486448290120108
open (6 posts)Maintainers need fixes, not more AI bug reports. ...2272122765874415497621
keep (3 posts)Agent skills let you capture repeatable instructions so you and your agents can reuse them. ...6152122425932933959975

What it shows. The input was 8,728 tokens and this digest 270 tokens, a 32.3x reduction, and every bullet is a real post you can open. It also shows the weak spots an LLM is there to fix. The cluster labels are raw keywords ("open" and "keep" say nothing), the 44-post Copilot cluster collapses many separate announcements into one line, and a headline such as "Frontier performance at a fraction of the cost" needs the rest of the post to make sense.

Use it as a fallback and a test set. Run the extractive digest next to the LLM digest. If the model's bullets cite none of the top-engagement posts, or cite ids outside the input, something is off with the prompt or the chunking. And when the LLM call fails or times out, the extractive version is still a usable digest.

08 — Section

What one digest costs, data plus model

Two bills add up: the tweets and the tokens. The table uses the prices we fetched from each provider's pricing page this session and our measured token counts; the model rows are list-price arithmetic, not a billed run.

Line itemVolumeUnit priceCost
Tweets, TwitterAPI.io200 timeline items$0.15 per 1,000 tweets$0.03
Tweets, official X API200 post reads$0.005 per post read$1.00
Model input, gpt-6-luna9,012 tokens$0.10 per 1M$0.0009
Model output, gpt-6-luna270 tokens$0.50 per 1M$0.00014
Model input + output, gpt-6.2-solsame$2.00 / $10.00 per 1M$0.0207

The input row is 100 deduped tweets (8,762 tokens) plus the 250-token instruction reserve; the output row assumes a digest the size of our extractive one (270 tokens). Real output length depends on the model and the prompt, so read it from the usage the API returns. Claude Haiku 5.5 has the same list rates as gpt-6-luna for prompts up to 100,000 tokens, but its own tokenizer, so the token count, and the cost, will differ.

The takeaway. With a small model, the tokens cost well under a tenth of a cent per digest and the tweets are the larger line, so the dedupe step and fetching only new tweets since the last run matter more than model choice. Store the newest id you summarized and stop paging when you reach it. For pricing on volume, see the TwitterAPI.io pricing page.

09 — Section

How we collected this

Question. What does a summarize-the-last-N-tweets job feed an LLM: how much of a raw timeline dedupe removes, how many tokens 100 kept tweets cost, how many chunks that makes at common budgets, and can an extractive digest be checked tweet by tweet?

Accounts and window. Three public organization accounts: @github, @NASA and @OpenAIDevs. /twitter/user/last_tweets with includeReplies=true, 10 pages each, newest first: 584 items in total (@NASA returned 184). Each window runs from the oldest to the newest item returned, collected in 2026.

Method. Dedupe rules exactly as in Step 2. Token counts with tiktoken 0.14.0, o200k_base, in a throwaway virtual environment. Chunking is greedy whole-tweet packing with a 250-token instruction reserve. The extractive digest is keyword clustering plus top engagement per cluster, with no model. The 6 digest ids were re-fetched through /twitter/tweets. The study used 31 requests (30 timeline pages and 1 lookup).

What the sample cannot show. Three accounts are not a census: an account that never reposts will lose far less to dedupe, and a keyword search will lose more. Token counts are for one tokenizer; other providers count differently. No LLM was called, so we report no model quality, latency or real output length.

Privacy. Aggregates only. Organization accounts only; reposted authors and reply targets are counted, never named or profiled. The digest quotes only @github's own posts. Analysis code and results live in data/studies/tweet-summarizer/ in our site repository.

python
"""tweet_summarizer.py - a cited AI digest of an X (Twitter) account's latest tweets.

Fetch with TwitterAPI.io, dedupe, chunk by tokens, summarize with an LLM,
then keep only the bullets whose [tweet id] was really in the input.

    pip install requests tiktoken openai
    export TWITTERAPI_IO_KEY=...   # docs.twitterapi.io
    export OPENAI_API_KEY=...
    python tweet_summarizer.py github 100
"""
import os
import re
import sys
import time

import requests
import tiktoken

BASE = "https://api.twitterapi.io"
MODEL = "gpt-6-luna"          # pick any model from the provider's model list
CHUNK_TOKENS = 16000          # 100 deduped tweets measured ~8,800 o200k_base tokens
PROMPT_RESERVE = 250          # room for the instructions in every chunk
ENC = tiktoken.get_encoding("o200k_base")  # an estimate; the bill uses the provider's own count
ID_RE = re.compile(r"\[(\d{6,25})\]")
URL_RE = re.compile(r"https?://\S+")

INSTRUCTIONS = """You summarize posts from one X (Twitter) account for a busy reader.
Input: one post per line as [tweet_id] date likes reposts | text.
Write 5 to 8 bullets, one per distinct topic, highest-engagement topics first.
Every bullet must end with the [tweet_id] of the post (or posts) it is based on,
copied exactly from the input. Do not invent facts, numbers or ids.
If a post is only a link or an emoji, skip it."""


def headers():
    return {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}


def keep(tweet, account, seen_text):
    """Drop reposts, replies to other accounts and repeated text; keep self-replies."""
    if tweet.get("retweeted_tweet") or tweet["text"].startswith("RT @"):
        return False
    if tweet.get("isReply") and (tweet.get("inReplyToUsername") or "").lower() != account.lower():
        return False
    key = re.sub(r"\s+", " ", URL_RE.sub("", tweet["text"])).strip().lower()
    if key in seen_text:
        return False
    seen_text.add(key)
    return True


def fetch_kept(account, want=100, max_pages=15):
    """Page /twitter/user/last_tweets (20 per page, newest first) until `want` tweets survive dedupe."""
    kept, seen_text, cursor = [], set(), ""
    for _ in range(max_pages):
        r = requests.get(f"{BASE}/twitter/user/last_tweets", headers=headers(),
                         params={"userName": account, "includeReplies": "true", "cursor": cursor},
                         timeout=30)
        r.raise_for_status()
        body = r.json()
        if body.get("status") != "success":
            raise RuntimeError(body.get("msg"))
        for t in (body.get("data") or {}).get("tweets", []):
            if keep(t, account, seen_text):
                kept.append(t)
                if len(kept) >= want:
                    return kept
        if not body.get("has_next_page"):
            break
        cursor = body.get("next_cursor") or ""
        time.sleep(1)  # fixed pacing between pages
    return kept


def fmt(tweet):
    day = " ".join(tweet["createdAt"].split()[1:3]) + " " + tweet["createdAt"].split()[-1]
    text = re.sub(r"\s+", " ", tweet["text"]).strip()
    return f"[{tweet['id']}] {day} likes={tweet.get('likeCount', 0)} reposts={tweet.get('retweetCount', 0)} | {text}"


def chunk(lines, budget=CHUNK_TOKENS - PROMPT_RESERVE):
    """Pack whole lines into chunks that stay under the token budget."""
    out, cur, used = [], [], 0
    for line in lines:
        n = len(ENC.encode(line)) + 1
        if cur and used + n > budget:
            out.append("\n".join(cur))
            cur, used = [], 0
        cur.append(line)
        used += n
    if cur:
        out.append("\n".join(cur))
    return out


def check_bullets(digest, valid_ids):
    """Split bullets into (cited, rejected): every [id] must be one we sent."""
    cited, rejected = [], []
    for line in digest.splitlines():
        if not line.strip().startswith(("-", "*")):
            continue
        ids = ID_RE.findall(line)
        (cited if ids and all(i in valid_ids for i in ids) else rejected).append(line.strip())
    return cited, rejected


def summarize(chunks):
    """Map-reduce: one call per chunk, then one call that merges the partial bullet lists."""
    from openai import OpenAI  # call shape per the OpenAI text generation guide
    client = OpenAI()
    partials = []
    for c in chunks:
        resp = client.responses.create(model=MODEL, instructions=INSTRUCTIONS, input=c)
        partials.append(resp.output_text)
    if len(partials) == 1:
        return partials[0]
    merge = INSTRUCTIONS + "\nThe input is several bullet lists. Merge duplicates and keep every [tweet_id]."
    return client.responses.create(model=MODEL, instructions=merge, input="\n".join(partials)).output_text


def confirm_on_x(ids):
    """Optional: re-fetch cited ids with /twitter/tweets (up to 50 ids per call) and match by id."""
    r = requests.get(f"{BASE}/twitter/tweets", headers=headers(),
                     params={"tweet_ids": ",".join(ids[:50])}, timeout=30)
    r.raise_for_status()
    return {t.get("id") for t in r.json().get("tweets", []) if t.get("id")}


if __name__ == "__main__":
    account = sys.argv[1] if len(sys.argv) > 1 else "github"
    want = int(sys.argv[2]) if len(sys.argv) > 2 else 100
    tweets = fetch_kept(account, want)
    lines = [fmt(t) for t in tweets]
    chunks = chunk(lines)
    print(f"{len(tweets)} tweets kept, {sum(len(ENC.encode(l)) + 1 for l in lines):,} tokens, {len(chunks)} chunk(s)")
    digest = summarize(chunks)
    cited, rejected = check_bullets(digest, {t["id"] for t in tweets})
    found = confirm_on_x(sorted({i for b in cited for i in ID_RE.findall(b)}))
    for b in cited:
        link = ", ".join(f"https://x.com/{account}/status/{i}" for i in ID_RE.findall(b) if i in found)
        print(b, "->", link or "not returned by /twitter/tweets")
    if rejected:
        print(f"dropped {len(rejected)} bullet(s) with a missing or unknown id")

Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.

10 — Questions

Questions readers ask

Can ChatGPT or Claude summarize tweets for me?

Yes, if you give them the tweet text. Pasting a few posts into a chat works for one-off reading. For an account's or keyword's last 100 posts, fetch them as JSON with an API, dedupe, and send the text to the model's API with a prompt that requires a tweet id per bullet. That way the digest can be checked and repeated on a schedule.

How many tweets can I summarize in one LLM call?

In our study 100 deduped tweets, formatted with id, date and counts, were about 8,762 tokens with tiktoken o200k_base, so a few hundred tweets fit easily in one call on current models. Stay under pricing thresholds: OpenAI bills prompts over 272K input tokens at a higher rate, and Claude Haiku 5.5 changes rate above 100,000 tokens.

Should I remove retweets before summarizing?

Usually yes. Reposts were 39.7% of the raw items we collected and 56.5% on @OpenAIDevs alone. They are other accounts' words, so leaving them in makes the digest about someone else and adds tokens you pay for. Keep self-replies: they are the account's own thread continuations.

How do I stop the AI summary from making things up?

Ask for the source tweet id at the end of every bullet, then reject any bullet whose id is missing or was not in the input. Optionally re-fetch cited ids with /twitter/tweets. This catches invented sources; to catch a bullet that misreads its tweet, compare bullet and tweet text, by eye or with a second yes/no model call.

Can I summarize a keyword or hashtag instead of one account?

Yes. Use /twitter/tweet/advanced_search with queryType=Latest and your keyword, page with next_cursor, and run the same dedupe, chunking and citation check. Expect more reposts and near-duplicates than on an organization timeline, and keep keyword results as aggregates because the authors are individuals.

Can it summarize a single long thread?

That is a different job: first rebuild the thread from its conversation id, then summarize the text. Use the thread reader tool or the unroll guide linked on this page, and feed the result to the same prompt.

What does it cost to run a tweet summarizer every day?

Two lines: tweets at $0.15 per 1,000 returned (a full 20-tweet page is $0.003; an empty check is the $0.00015 minimum), and model tokens at the provider's list price. A 100-tweet digest on gpt-6-luna list prices is about a tenth of a cent in tokens. Fetch only posts newer than the last id you summarized to keep the tweet line small.

11 — Further reading

Continue

Sources & further reading
More from this series

Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.

Build it

Stop reading. Start building.

Starter credits cover real testing on real data. Google sign-in, no card, no application queue.

Get an API key

Already building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.