AI & ML

Why Your AI Agent Can't Read the Web (and How to Build a Fetch Layer That Can)

· 5 min read
Community Article
Community articles are authored by SitePoint Premium contributors. Content is screened before publication, and SitePoint reserves the right to moderate or remove articles that violate our guidelines. Views expressed are those of the authors and do not necessarily reflect those of SitePoint.

Why Your AI Agent Can't Read the Web (and How to Build a Fetch Layer That Can)

AD
Abdullah Dogar
Published in
·Updated:

The AI briefing for Developers

Stay up to date with AI tools, model releases, and developer workflows that matter.

Weekly. Free. One click to leave.

Share this article

Why Your AI Agent Can't Read the Web (and How to Build a Fetch Layer That Can)
SitePoint Premium
Stay Relevant and Grow Your Career in Tech
  • Premium Results
  • Publish articles on SitePoint
  • Daily curated jobs
  • Learning Paths
  • Discounts to dev tools
Start Free Trial

7 Day Free Trial. Cancel Anytime.

You've built an agent. It plans well, calls tools in a sensible order and writes a decent summary. Then you point it at a real URL and it comes back with a summary of a Cloudflare challenge page, a cookie banner, or nothing at all.

This is the least glamorous part of building with LLMs and it's where a lot of agent projects quietly fall over. The model is rarely the problem. The fetch is. In this article we'll look at why live web retrieval has become so unreliable for AI tools, what the numbers say about the shift, and how to build a small, well-behaved fetch layer in Python that fails loudly instead of feeding your model garbage.

Key Takeaways

  • Automated traffic passed human traffic on the web in 2024, and site owners have responded by blocking bots more aggressively.
  • Most AI crawling is still for model training, which is why many sites now block AI user agents on sight, including the ones fetching pages for a real user.
  • A good fetch layer checks robots.txt, identifies itself honestly, sorts failures into types, retries with backoff and caches what it already has.
  • The most common agent bug is treating a block page as content. Detect it and fail loudly.

The Web Has Changed Under Your Agent's Feet

A few years ago, a plain requests.get() worked on most of the public web. That's no longer true, and the reason is simple: there are now more bots than people.

According to the 2025 Imperva Bad Bot Report, automated traffic made up 51% of all web traffic in 2024. That's the first time in a decade it has passed human activity. Bad bots alone (scrapers, credential stuffers, scalpers) went from 32% to 37% of traffic in a single year.

hyUmQUAzs9IAAAAASUVORK5CYII=

Source: Imperva Bad Bot Report 2024 and 2025

From a site owner's point of view, your polite research agent and a credential-stuffing botnet look much the same at the network edge. Both are non-browser clients making fast requests from data-center IP ranges. So the defaults have tightened. In July 2025 Cloudflare began blocking known AI crawlers by default for new customers, and bot management products now look at TLS fingerprints, header order, IP reputation and JavaScript execution, not just the User-Agent string.

Why AI Bots in Particular Get Blocked

It helps to understand the publisher's side of the deal, because it explains why your agent is being treated with suspicion.

Cloudflare splits AI crawling into three purposes: training (collecting data to train models), search (building an index for AI search answers) and user action (fetching a page because a person just asked a question). Training dominates.

Source: Cloudflare

Source: Cloudflare

Training crawls take content and send nothing back. Cloudflare measures this with a crawl-to-referral ratio: how many pages a platform crawls for every visitor it sends to the site. In its crawl-to-click gap analysis, the ratios for some AI platforms ran into the tens of thousands, compared with single digits for traditional search.

Source: Cloudflare

Source: Cloudflare

If you ran a publication and saw those numbers, you'd block too. The catch is that blocking is usually done by user agent or IP range, so it hits user-action fetches as well. Those are the ones that happen when a person asks your agent to read a specific article, and Cloudflare's 2025 Year in Review found they grew more than 15x during the year. Your agent is caught in a fight it didn't start.

The mix of crawlers also shifts quickly, which makes static allow and block lists fragile on both sides:

Source: Cloudflare

Source: Cloudflare

And restrictions keep piling up. The Consent in Crisis study audited 14,000 web domains and found that a large and fast-growing share of the sources behind the C4 training corpus now restrict AI crawlers, either through robots.txt or their terms of service.

Source: Longpre et al., Consent in Crisis (NeurIPS 2024)

Source: Longpre et al., Consent in Crisis (NeurIPS 2024)

So that's the environment your agent fetches in. Here's how to build for it.

The Four Ways a Fetch Fails

Before writing any retry logic, put names on your failures. "The request failed" is useless to both you and the model. In practice almost every failed fetch falls into one of four buckets:

  1. Not allowed. robots.txt disallows your agent, or the site's terms forbid automated access. The correct response is to stop and tell the user. Don't retry.
  2. Blocked. HTTP 403, a challenge page, or a 200 response whose body is actually a "verify you are human" interstitial. Retrying straight away won't help.
  3. Throttled. HTTP 429 or 503, often with a Retry-After header. Back off and try again later.
  4. Broken. DNS errors, timeouts, connection resets, 5xx errors. These are often temporary, so retry a small number of times.

Bucket 2 is the dangerous one, because a block page often comes back with a 200 OK. If you don't check, the model will happily summarise "Checking your browser before accessing..." as if it were the article.

Building the Fetch Layer

Here's a compact fetch layer in Python using httpx and the standard library's robots.txt parser. It's around 100 lines and covers the four buckets above.

Step 1: Identify yourself honestly and respect robots.txt

Use a descriptive user agent with a contact URL. It costs you nothing and site operators are far more likely to allow a client they can identify and reach. Then check robots.txt (standardised as RFC 9309) before every new host.

import time
import httpx
from functools import lru_cache
from urllib.parse import urlsplit
from urllib.robotparser import RobotFileParser

USER_AGENT = "AcmeResearchAgent/1.0 (+https://example.com/bot)"

@lru_cache(maxsize=512)
def robots_for(origin: str) -> RobotFileParser:
    rp = RobotFileParser()
    try:
        r = httpx.get(f"{origin}/robots.txt", headers={"User-Agent": USER_AGENT},
                      timeout=5, follow_redirects=True)
        if r.status_code in (401, 403):
            rp.disallow_all = True          # RFC 9309: treat as fully disallowed
        elif r.status_code >= 400:
            rp.allow_all = True             # no robots.txt means no restrictions
        else:
            rp.parse(r.text.splitlines())
    except httpx.HTTPError:
        rp.allow_all = True
    return rp

def allowed(url: str) -> bool:
    parts = urlsplit(url)
    origin = f"{parts.scheme}://{parts.netloc}"
    return robots_for(origin).can_fetch(USER_AGENT, url)

The lru_cache means you fetch robots.txt once per origin rather than once per page. In a long-running service you'll want a cache with a TTL instead, since robots.txt files do change.

Step 2: Classify every response

This is the core of the layer. Instead of returning raw HTML, return a result that says which bucket you landed in.

from dataclasses import dataclass

BLOCK_MARKERS = (
    "cf-chl-",                       # Cloudflare challenge
    "verify you are human",
    "checking your browser",
    "enable javascript and cookies",
    "access denied",
)

@dataclass
class FetchResult:
    status: str          # "ok" | "not_allowed" | "blocked" | "throttled" | "broken"
    url: str
    text: str = ""
    detail: str = ""
    retry_after: float | None = None

def looks_blocked(resp: httpx.Response) -> bool:
    if resp.status_code == 403:
        return True
    ctype = resp.headers.get("content-type", "")
    if "text/html" not in ctype:
        return False
    head = resp.text[:5000].lower()
    return any(marker in head for marker in BLOCK_MARKERS)

def classify(url: str, resp: httpx.Response) -> FetchResult:
    if resp.status_code in (429, 503):
        ra = resp.headers.get("retry-after")
        wait = float(ra) if ra and ra.isdigit() else None
        return FetchResult("throttled", url, detail=str(resp.status_code), retry_after=wait)
    if looks_blocked(resp):
        return FetchResult("blocked", url, detail=f"HTTP {resp.status_code}")
    if resp.status_code >= 400:
        return FetchResult("broken", url, detail=f"HTTP {resp.status_code}")
    return FetchResult("ok", url, text=resp.text)

The marker list is deliberately simple. It won't catch every interstitial, but it catches the common ones, and a false "blocked" is much cheaper than a confident summary of a CAPTCHA page. Log every blocked result with its first few hundred characters so you can grow the list from real data.

Step 3: Retry only what's worth retrying

Retries should depend on the bucket. Throttled and broken responses get exponential backoff with jitter. Blocked and not-allowed responses get no retries at all.

import random

def fetch(url: str, max_attempts: int = 3) -> FetchResult:
    if not allowed(url):
        return FetchResult("not_allowed", url, detail="Disallowed by robots.txt")

    delay = 1.0
    last = FetchResult("broken", url, detail="no attempt made")
    with httpx.Client(headers={"User-Agent": USER_AGENT},
                      timeout=httpx.Timeout(10.0, connect=5.0),
                      follow_redirects=True) as client:
        for attempt in range(max_attempts):
            try:
                result = classify(url, client.get(url))
            except httpx.HTTPError as exc:
                result = FetchResult("broken", url, detail=type(exc).__name__)

            if result.status in ("ok", "blocked", "not_allowed"):
                return result

            last = result
            wait = result.retry_after or delay + random.uniform(0, delay)
            time.sleep(min(wait, 30))
            delay *= 2
    return last

Note the cap on wait. A site sending Retry-After: 3600 is telling you to go away for an hour. An interactive agent should report that to the user rather than block a request thread for that long.

Step 4: Cache with conditional requests

The cheapest fetch is the one you don't make. Agents often re-read the same documentation page several times in one session. Store the ETag and Last-Modified headers and send them back as If-None-Match and If-Modified-Since. A 304 Not Modified response costs the server almost nothing and lowers the odds of being rate limited.

_cache: dict[str, tuple[dict, str]] = {}

def conditional_headers(url: str) -> dict:
    if url not in _cache:
        return {}
    meta, _ = _cache[url]
    h = {}
    if "etag" in meta:
        h["If-None-Match"] = meta["etag"]
    if "last-modified" in meta:
        h["If-Modified-Since"] = meta["last-modified"]
    return h

def remember(url: str, resp: httpx.Response) -> None:
    meta = {k: resp.headers[k] for k in ("etag", "last-modified") if k in resp.headers}
    if meta:
        _cache[url] = (meta, resp.text)

Wire these into fetch() by passing headers=conditional_headers(url) to client.get(). On a 304, return the cached text. On a 200, call remember().

Step 5: Tell the model what happened

Finally, don't hide failures from the LLM. Give the tool output a structured shape so the model can reason about it:

def fetch_tool(url: str) -> dict:
    r = fetch(url)
    if r.status == "ok":
        return {"ok": True, "url": url, "content": extract_main_text(r.text)}
    return {
        "ok": False,
        "url": url,
        "reason": r.status,
        "detail": r.detail,
        "hint": {
            "not_allowed": "The site does not permit automated access. Tell the user.",
            "blocked": "The site blocked this request. Try an official API or another source.",
            "throttled": "The site is rate limiting. Try again later or use a cached source.",
            "broken": "The site could not be reached. It may be down.",
        }[r.status],
    }

(extract_main_text is whatever readability or boilerplate-removal step you already use. Libraries like trafilatura work well here.)

With this in place, the model's answer changes from a made-up summary to "I couldn't read that page because the site blocks automated access. Here's what I found from two other sources." That's a better product, and it builds trust with users.

What About Pages You Still Can't Reach?

Once you've done everything above, some legitimate user-action fetches will still fail. That's usually because the site blocks data-center IP ranges outright, not because of anything your agent did. Teams handle this in a few ways, roughly in order of preference:

  • Use the official API or feed. RSS, sitemaps, public APIs and documentation exports are faster, more stable and clearly sanctioned.
  • Ask for access. Many publishers will allowlist a clearly identified bot with a real contact address, especially for low-volume, user-triggered fetches.
  • Use a search or retrieval API that already has licensing arrangements with publishers.
  • Route through a residential or consumer network. This is the most contested option, and how a network sources its IPs matters a great deal. Some proxy pools have historically been built from devices whose owners never knowingly agreed to share them. A newer group of providers is consent-based instead. For example, Bixberry runs an opt-in network where people install an app, choose to share spare bandwidth for AI assistant lookups, and earn rewards for it. If you go down this route, check how the provider gets consent, what traffic it allows, and whether it still respects robots.txt and site terms. A residential IP doesn't make it acceptable to fetch a page the site owner has explicitly disallowed.

The principle is the same in every case: the network path is a reliability decision, not a way around a site's wishes. Your robots.txt check and your honest user agent should stay in place whichever route the request takes.

Monitoring: The Numbers Worth Tracking

Once your fetch layer returns structured results, observability is easy. Emit one event per fetch with the host, status bucket and latency, and watch these:

  • Success rate by host. A sudden drop for one domain usually means its bot rules changed.
  • Blocked rate overall. If this goes up across many hosts, check whether your IP range or TLS fingerprint has been flagged.
  • Cache hit rate. A low rate in a chat-style agent often means the cache key is wrong (for example, query strings or trailing slashes).
  • "Content looked like a block page" rate. This tells you how often you would have fed the model garbage without the check.

If you're prototyping agents with AI coding assistants, ask them to generate these metrics hooks from the start. They're easy to bolt on now and painful to add later. For a sense of how well current tools handle this kind of infrastructure code, Vibe Coder Journal publishes hands-on reviews and benchmarks of AI coding tools.

A Quick Checklist

  • Descriptive User-Agent with a contact URL
  • robots.txt checked and cached per origin
  • Responses sorted into ok / not_allowed / blocked / throttled / broken
  • Block pages detected even when the status is 200
  • Exponential backoff with jitter for throttled and broken only, with a wait cap
  • Conditional requests with ETag and Last-Modified
  • Structured tool output so the model can explain failures
  • Per-host metrics on success, block and cache rates

Wrapping Up

The web your agent reads in 2026 isn't the open, fetch-anything web many of us learned on. More than half the traffic is automated, publishers have good reasons to be wary of AI crawlers, and the defaults now lean toward blocking. You can't change that. You can make your agent a good citizen, though: one that identifies itself, respects the rules, backs off when asked, and tells the truth when it can't read something.

Most of the reliability gains come from the unglamorous parts: classifying failures, caching and passing honest errors to the model. Get those right and your agent will feel much more dependable, even on the days when half the web won't let it in.

FAQs

It depends on the jurisdiction, the site's terms of service and what you do with the content. Respecting robots.txt and site terms is the baseline. For commercial products, get proper legal advice.

Should my agent obey robots.txt for user-triggered fetches?

Many site owners expect it to, and RFC 9309 makes no exception for user-triggered fetches. The safest default is to obey it and tell the user when a page is disallowed.

Why does my fetch return 200 but the content is useless?

Many bot-protection systems serve a challenge page with a 200 status. Check the body for challenge markers before passing it to the model, as in the looks_blocked() function above.

Do I need a headless browser?

Only for pages that render their main content with JavaScript. Try a plain HTTP fetch first. Headless browsers are slower, cost more to run and are easier to fingerprint.

Source: Abdullah Dogar · www.sitepoint.com