News data for RAG: give an LLM current news with citations

To ground an LLM in current news, fetch recent articles from World News API's Search News endpoint, split each article's text into chunks of about 200 words, keep the url, title and publish_date with every chunk, pick the chunks closest to the question and tell the model to cite them by number. One search that returns 50 articles costs 1.5 points, so the free plan's 50 points a day cover about 33 questions. You need no vector database to start: cosine similarity in plain Python handles the few hundred chunks one search produces.

  • Source: GET /search-news returns the full text, title, url, publish_date, language and source_country of each article.
  • Freshness: earliest-publish-date with sort=publish-time and sort-direction=DESC.
  • Chunks: word windows of the text, each carrying the article id, URL, title and publish date.
  • Cost: 1 point per search plus 0.01 per article; 50 articles cost 1.5 points.
  • Storage: the terms allow caching only with prior written permission and for at most 1 hour.
  • No code needed for agents: the MCP server gives Claude Desktop, Cursor and other MCP clients the same data.

What you'll build

A file rag_news.py that answers a question about current events in 5 steps: fetch recent articles, chunk them, rank the chunks against the question, build a prompt with numbered excerpts, and map the model's [n] citations back to URLs. Step 6 adds a daily refresh for when you keep an index. The code calls no particular LLM or vector database; you plug in the ones you use.

Prerequisites

  • Python 3.9 or newer and requests (pip install requests).
  • A free API key from the console, stored in WORLD_NEWS_API_KEY (free plan details).
  • Access to any chat model.

Before you store anything: the terms

The current World News API terms say you may not copy or store the information the API provides, "including any derived, hashed, or transformed data". With prior written permission you may cache user-requested data for up to 1 hour, and if you stop using the API you must delete what you obtained. Chunks and embeddings are transformed data, and the 1-hour cache that the terms allow with permission doesn't cover a persistent vector index: that needs a separate written agreement. That gives you 2 ways to build this:

  • Retrieve at question time (steps 1 to 5): fetch for each question, rank in memory, answer, discard. Nothing outlives the request.
  • Keep a daily index (step 6): only after you have written permission, and with an agreed limit on how long you keep the data.

The terms of use do not allow storing API data without a separate written agreement; ask at [email protected] before you build a persistent index. This guide uses the first design by default.

Step 1: Fetch recent articles

import os
from datetime import datetime, timedelta, timezone

import requests

API_KEY = os.environ.get("WORLD_NEWS_API_KEY", "YOUR_API_KEY")
SEARCH_URL = "https://api.worldnewsapi.com/search-news"


def fetch_recent(text, days=3, number=50, language="en"):
    """The newest articles matching text from the last few days."""
    since = (datetime.now(timezone.utc) - timedelta(days=days)).strftime("%Y-%m-%d %H:%M:%S")
    response = requests.get(
        SEARCH_URL,
        headers={"x-api-key": API_KEY},
        params={
            "text": text,
            "language": language,
            "earliest-publish-date": since,
            "sort": "publish-time",
            "sort-direction": "DESC",
            "number": number,
        },
        timeout=30,
    )
    response.raise_for_status()
    return response.json()["news"]

text takes 3 to 100 characters. Put a name in quotes for an exact phrase, or use entities (for example ORG:European Central Bank) to match an organization under any name. Let the LLM write this search string from the user's question if you like.

Example response (shortened), from the Search News docs:

{
  "offset": 0,
  "number": 10,
  "available": 83,
  "news": [
    {
      "id": 206030983,
      "title": "Nearly 30 aftershocks recorded around NJ quake epicenter since Friday",
      "text": "New Jersey continues to shake after Friday’s 4.8-magnitude earthquake ...",
      "url": "https://nypost.com/2024/04/06/us-news/nearly-30-aftershocks-recorded-around-nj-quake-epicenter/",
      "publish_date": "2024-04-06 22:44:18",
      "authors": ["Deirdre Bardolf"],
      "language": "en",
      "source_country": "us"
    }
  ]
}

Step 2: Chunk the text and keep the metadata

def chunk_article(article, size=200, overlap=40):
    """Split the article text into overlapping word windows that carry the article's metadata."""
    words = (article.get("text") or "").split()
    chunks = []
    start = 0
    while start < len(words):
        chunks.append({
            "text": " ".join(words[start:start + size]),
            "article_id": article["id"],
            "url": article["url"],
            "title": article["title"],
            "publish_date": article["publish_date"],
        })
        if start + size >= len(words):
            break
        start += size - overlap
    return chunks

Each chunk from the example article above looks like this:

{
  "text": "New Jersey continues to shake after Friday’s 4.8-magnitude earthquake ...",
  "article_id": 206030983,
  "url": "https://nypost.com/2024/04/06/us-news/nearly-30-aftershocks-recorded-around-nj-quake-epicenter/",
  "title": "Nearly 30 aftershocks recorded around NJ quake epicenter since Friday",
  "publish_date": "2024-04-06 22:44:18"
}

200 words with a 40-word overlap keeps a sentence that crosses a boundary in at least one chunk. Measure in tokens instead of words if your model's context is tight.

Step 3: Rank the chunks in plain Python

This scores each chunk against the question with cosine similarity over word counts. It needs no library and no index, and it keeps at most 2 chunks per article so one long article cannot fill the context.

import math
import re
from collections import Counter

TOKEN = re.compile(r"\w+")
STOPWORDS = {
    "a", "an", "and", "are", "as", "at", "be", "by", "did", "does", "for", "from", "has", "have", "how",
    "in", "is", "it", "of", "on", "or", "that", "the", "this", "to", "was", "were", "what", "when",
    "which", "who", "why", "will", "with",
}


def vectorize(text):
    return Counter(token for token in TOKEN.findall(text.lower()) if token not in STOPWORDS)


def cosine(a, b):
    dot = sum(count * b[term] for term, count in a.items() if term in b)
    norm = math.sqrt(sum(v * v for v in a.values())) * math.sqrt(sum(v * v for v in b.values()))
    return dot / norm if norm else 0.0


def top_chunks(question, chunks, k=6, per_article=2):
    """The k chunks most similar to the question, at most per_article from one article."""
    q = vectorize(question)
    ranked = sorted(chunks, key=lambda c: cosine(q, vectorize(c["title"] + " " + c["text"])), reverse=True)
    picked, used = [], Counter()
    for chunk in ranked:
        if used[chunk["article_id"]] < per_article:
            picked.append(chunk)
            used[chunk["article_id"]] += 1
        if len(picked) == k:
            break
    return picked

To use embeddings instead, replace vectorize() with a call to your embedding model and change cosine() to work on 2 lists of numbers (the version above expects word counts). The rest of the pipeline stays the same, and so does the metadata on each chunk.

Step 4: Build a prompt that asks for citations

def build_prompt(question, chunks, today):
    sources = "\n\n".join(
        f"[{n}] {c['title']} (published {c['publish_date']}, {c['url']})\n{c['text']}"
        for n, c in enumerate(chunks, start=1)
    )
    return (
        f"Today is {today}. Answer the question using only the numbered news excerpts below.\n"
        "Cite each claim with the excerpt number in square brackets, for example [2].\n"
        "If the excerpts do not contain the answer, say that you do not know.\n\n"
        f"{sources}\n\nQuestion: {question}"
    )


def cited_sources(answer, chunks):
    """Map the [n] markers in the model's answer back to titles and URLs."""
    numbers = sorted({int(n) for n in re.findall(r"\[(\d+)\]", answer)})
    return [(n, chunks[n - 1]["title"], chunks[n - 1]["url"]) for n in numbers if 1 <= n <= len(chunks)]

Giving the model today's date and each excerpt's publish date lets it say "on Thursday" correctly and prefer the newest report when sources disagree.

Step 5: Answer a question

from datetime import date


def ask_llm(prompt):
    """Send the prompt to the chat model you use and return its text answer."""
    raise NotImplementedError("Call your LLM here")


question = "What did the European Central Bank decide this week?"
articles = fetch_recent('"European Central Bank"', days=7, number=50)
chunks = [chunk for article in articles for chunk in chunk_article(article)]
context = top_chunks(question, chunks)
if not context:
    print("No recent articles found. Tell the user instead of letting the model guess.")
else:
    answer = ask_llm(build_prompt(question, context, today=date.today().isoformat()))
    print(answer)
    print("\nSources:")
    for n, title, url in cited_sources(answer, context):
        print(f"[{n}] {title}: {url}")

Show the sources list under every answer. Readers can check the claim, and you can spot an excerpt the model misread.

Step 6: Refresh daily with earliest-publish-date

The terms of use do not allow storing API data without a separate written agreement; ask at [email protected] before you build a persistent index. With such an agreement, run this once a day, for example from cron. It fetches only what was published since the last run, 100 articles per request, and keys the index by article id so a repeated article replaces its old chunks instead of adding new ones.

import time


def refresh(index, text, last_run, language="en"):
    """Add articles published since last_run to index (article id: chunks); return the next last_run."""
    started = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
    offset = 0
    while offset <= 10000:
        response = requests.get(
            SEARCH_URL,
            headers={"x-api-key": API_KEY},
            params={
                "text": text,
                "language": language,
                "earliest-publish-date": last_run,
                "latest-publish-date": started,
                "sort": "publish-time",
                "sort-direction": "ASC",
                "offset": offset,
                "number": 100,
            },
            timeout=30,
        )
        response.raise_for_status()
        page = response.json()
        for article in page["news"]:
            chunks = chunk_article(article)
            if chunks:
                index[article["id"]] = chunks
        offset += len(page["news"])
        if not page["news"] or offset >= page["available"]:
            break
        time.sleep(1)  # free plan: 1 request per second
    return started


def drop_older_than(index, days):
    cutoff = (datetime.now(timezone.utc) - timedelta(days=days)).strftime("%Y-%m-%d %H:%M:%S")
    for article_id in [i for i, chunks in index.items() if chunks[0]["publish_date"] < cutoff]:
        del index[article_id]

Save the returned timestamp and pass it as last_run the next day. If the index needs older articles than a month, note that the free plan only searches the last month; Reporter and higher go back to January 1, 2022.

Error handling

StatusWhat it meansWhat to do
401 UnauthorizedListed for every endpoint in the OpenAPI file; the docs say nothing more.Check the key and the x-api-key header.
402 Payment RequiredOn the free plan, today's points are used up (quota docs).Answer "news search unavailable" instead of letting the model answer from memory. The quota resets at midnight UTC.
429 Too Many RequestsToo many requests per second or at once.Queue questions and send searches one at a time on the free plan; retry with growing delays (the Python guide has a client that does this).

What this guide costs

ActionRequestsPoints
One question (steps 1 to 5), 50 articles11.5
One question with 20 articles11.2
Daily refresh (step 6) with 150 new articles23.5

On the free plan's 50 points a day, that is about 33 questions with 50 articles each, or 41 with 20 each.

Next steps

Frequently asked questions

How do I give an LLM access to current news?

Fetch recent articles with a news API when the question comes in, pass the most relevant excerpts with title, publish date and URL in the prompt, and ask the model to cite them. With World News API, one search that returns 50 articles costs 1.5 points.

Do I need a vector database for news RAG?

No. For the few hundred chunks that one search returns, cosine similarity in plain Python is enough. A vector database helps once you keep a large index, and for that you should check the storage terms first.

How do I make the LLM cite its news sources?

Number each excerpt in the prompt, include its title, publish date and URL, tell the model to cite the numbers in square brackets, then map the numbers back to URLs in your code and show them under the answer.

Can I store World News API articles in a vector index?

Not without permission. The current terms do not allow storing API data, including derived or transformed data such as chunks and embeddings, without prior written permission, and they limit caching to 1 hour. Ask [email protected] before you build a persistent index.

Is there an MCP server for news?

Yes. The World News API MCP server lets Claude Desktop, Cursor and other MCP clients search news with your API key, without writing retrieval code.

Last updated November 22, 2026 by the World News API team. Spotted an error? Tell us at [email protected] or on Discord.

More from World News API

  • Compare news APIs
    World News API next to NewsAPI.org, NewsData.io, GNews, Mediastack and others.
  • Guides
    Step-by-step tutorials with working code.
  • Use cases
    AI agents, finance, media monitoring and research.
  • Documentation
    Every endpoint with parameters, examples and quotas.

Get a free API key