A team ships a support agent that answers questions about a payments API. In testing it is excellent. Six weeks later a customer asks how to handle a webhook signature header, and the agent describes a header name that the vendor renamed after the model's training data was collected. The reply is fluent, specific and wrong. The customer pastes it into production code, and the first signal anyone gets is a failed integration on a Friday evening.
The fix everyone reaches for is "give the agent web search". That sentence hides three separate jobs: finding candidate pages, fetching their content in a form a model can read, and deciding which claims in that content are trustworthy enough to repeat. Tools such as SearXNG, Crawl4AI and Tavily each cover one or two of those jobs and none covers all three. This article takes them apart so you can choose deliberately, wire them together safely and recognise the failure modes before your users do.
1. Three jobs hiding inside "web search"
When an agent needs fresh facts, the pipeline has three stages, and mixing them up is the most common source of confusion when people compare tools.
- Discovery. Turn a natural-language question into a ranked list of URLs. This is what a search engine does. The output is small: titles, URLs and short snippets.
- Retrieval. Fetch a chosen URL and convert it into text a model can consume. This involves HTTP, sometimes a headless browser to execute JavaScript, and cleaning: removing navigation, cookie banners, footers and ads, then converting what remains to markdown or plain text.
- Grounding. Decide which passages support the answer, attach the source to each claim, and refuse to answer when the evidence is thin. This stage lives in your agent logic and prompts, not in any of the tools.
SearXNG is a discovery tool. Crawl4AI is a retrieval tool. Tavily is a hosted service that bundles discovery with a first pass at retrieval, returning snippets already extracted from the pages it found. Grounding is yours regardless of which you choose. A team that buys or installs a tool and assumes the third job is handled has bought a faster way to produce confident errors, because now the wrong answer arrives with a citation attached.
2. Why search for agents differs from search for people
A human reads ten blue links, opens two, skims, and uses judgment about which site looks reputable. An agent has none of that peripheral vision. Four differences shape the tool requirements.
Output must be machine-readable
An agent consumes JSON, not a results page. Any tool that only offers HTML needs a scraper in front of it, and that scraper breaks whenever the markup changes. A JSON response with stable field names (title, URL, content, source engine) is worth more than a prettier ranking.
Context is the scarce resource
A model's context window holds the task, the instructions, the conversation and every tool result. A raw HTML page can run to hundreds of kilobytes, most of it markup and boilerplate. Feeding that in wastes tokens, raises cost and latency, and dilutes attention away from the three sentences that matter. Retrieval quality is therefore measured in how much useful text survives per token, not in how much was downloaded.
Ranking signals differ
Consumer search ranks for clicks, freshness of news and commercial intent. An agent often wants the primary source: the vendor changelog, the RFC, the standard, the source repository. Query phrasing, domain allow-lists and date filters matter more than they do for a person browsing casually.
The reader can be attacked
A person who lands on a page containing "ignore your previous instructions" is amused. A model that reads the same sentence inside a tool result may treat it as an instruction. Every page an agent fetches is untrusted input, and the architecture has to assume that from the first line of code. Section 7 returns to this.
3. SearXNG: a metasearch engine you operate
SearXNG is an open-source metasearch engine. It does not maintain its own web index. It forwards your query to many upstream engines, merges and de-duplicates the results, scores them, and returns one list. You host it yourself, typically as a container behind your own network boundary.
What you get
- Control over sources. Engines can be enabled, disabled and grouped into categories such as general, news, science or code. You can restrict an agent to the categories that suit its job.
- Privacy and no per-query bill. Queries leave your network from your server's address, and there is no API key to a vendor for the aggregation itself. The upstream engines still see the queries.
- A JSON interface. With the JSON output format enabled in the instance settings, a request such as
/search?q=...&format=jsonreturns structured results with fields including title, URL, content snippet, the engines that returned it and a score. If the format is not enabled, the instance refuses the request, which is a common first-day surprise.
What you take on
- Upstream fragility. Engines rate-limit, change markup, show CAPTCHAs and block data-centre addresses. A metasearch instance that worked last month can return empty results from one or more engines today. Monitor per-engine error rates and treat zero results as a signal, not as an answer.
- Snippets only. SearXNG gives you what the upstream engines show on their results pages. Snippets are short and sometimes truncated mid-sentence. They are good for choosing which page to open and poor evidence for a claim.
- Operations. Updates, settings, engine tuning and abuse protection are your responsibility. If the instance is reachable from outside, a bot limiter and access control are not optional.
The sweet spot is an agent that issues many exploratory queries, where a per-call price would add up and where you want to keep query text inside infrastructure you control.
4. Crawl4AI: turning pages into text a model can use
Crawl4AI is an open-source Python crawler built for feeding language models. It drives a real browser engine through Playwright, so pages that render content with JavaScript still produce text, and it converts the result into markdown. Its main value is the cleaning step between "bytes from a server" and "text in a prompt".
Mechanisms worth understanding
- Browser-backed fetching. A plain HTTP client sees the empty shell of a single-page application. A headless browser waits for the page to hydrate. The price is memory, CPU and seconds per page instead of milliseconds.
- Content filtering. Raw markdown of a page includes menus, related-article lists and legal footers. The library offers filtering strategies (for example, pruning blocks by text density or ranking blocks against a query) that produce a smaller "fit" version. Check the current documentation for the exact option names, as they have evolved between releases.
- Structured extraction. Beyond markdown, you can extract fields with CSS or XPath schemas, which is deterministic and cheap, or with an LLM-driven strategy, which is flexible and costs tokens on every page.
- Concurrency and sessions. An async API lets you crawl many URLs in parallel, reuse browser contexts and keep cookies across calls. The concurrency limit is where your memory goes.
Where it hurts
Crawling is the part with legal and ethical weight. Respect robots.txt and a site's terms, identify your crawler honestly, rate-limit per host, and cache aggressively so a loop does not hit the same page forty times. Sites that actively block automation (login walls, bot detection, paywalls) will defeat a generic crawler, and working around those measures is both a maintenance treadmill and, in many cases, a violation of the site's terms. Crawl4AI does not choose pages for you; something upstream, such as a search step, has to supply the URLs.
5. Tavily and the hosted agent-search APIs
Tavily is a commercial search API aimed at agents. You send a query with an API key and get back a JSON list of results, each with a title, URL, a relevance score and a content field holding text extracted from the page rather than the short snippet a consumer engine displays. Optional parameters control result count, search depth, domain include and exclude lists and whether to return a generated short answer. Treat parameter names and pricing tiers as things to confirm in the vendor's current documentation.
Why teams pick a hosted service
- One call instead of three. Discovery, fetch and extraction happen on the vendor's side. For a prototype or a low-volume agent this removes an entire subsystem.
- Extraction already tuned for models. The content field is meant to be dropped into a prompt.
- No fleet to run. The headless browsers, proxies and anti-bot upkeep are someone else's problem.
What you give up
- Opacity. You cannot inspect why a result ranked first or how the content was extracted. When an answer is wrong you can see the output but not the cause.
- Data egress. Query text goes to a third party. If queries embed customer names, internal project codenames or contract details, that is a policy question before it is a technical one.
- Cost shape. Usage-based pricing is cheap at low volume and can dominate the budget for an agent that searches in a loop. Measure calls per task before you commit.
- Dependency. Rate limits, outages and terms changes become your agent's availability profile. Design a fallback.
Hosted APIs of this kind are a category, not a single product. Other vendors offer similar JSON search endpoints, and the evaluation questions in this article apply to each of them.
6. Choosing: a qualitative comparison and a decision checklist
The table compares properties that follow from how each tool is built. It contains no performance numbers because those depend on your queries, your network and the sites involved; measure on your own workload.
| Property | SearXNG | Crawl4AI | Hosted agent-search API (e.g. Tavily) |
|---|---|---|---|
| Primary job | Discovery (ranked URLs and snippets) | Retrieval (page to clean markdown) | Discovery plus first-pass extraction |
| Where it runs | Your infrastructure | Your infrastructure | Vendor infrastructure |
| Query text leaves your network | Yes, to upstream engines | Only the URLs you fetch | Yes, to the vendor |
| Cost model | Hosting and upkeep | Hosting; memory-heavy under concurrency | Usage-based, per call |
| Handles JavaScript-rendered pages | No, snippets only | Yes, via a browser engine | Handled on the vendor side |
| Main failure mode | Upstream engines block or rate-limit | Bot walls, timeouts, noisy extraction | Opaque ranking, outages, spend |
| Operational burden | Medium: settings, engine health | Medium to high: browsers, proxies, politeness | Low |
| Best fit | High-volume exploratory queries, private deployments | Deep reading of known URLs, structured extraction | Prototypes, small teams, low to moderate volume |
Most production systems end up composing tools rather than picking one. A common arrangement uses a self-hosted metasearch step to find candidates, a crawler to read the two or three best pages in full, and a hosted API as a fallback when the first path returns nothing.
Decision checklist
- Can query text, including names and internal terms, leave your network? If not, rule out hosted APIs and scrub queries even for metasearch.
- Does the agent need the full page, or are a few extracted paragraphs enough? Full pages mean a crawler.
- How many searches does one task trigger, and how many tasks per day? Multiply, then price it.
- Do the target sources render with JavaScript or sit behind logins? Both push you toward a browser-backed fetch and raise the question of whether you are permitted to fetch them at all.
- Who is on call when the tool breaks at 2 a.m.? If the honest answer is nobody, favour the hosted option or a smaller scope.
- Is there a trusted source list? An allow-list of domains often improves answer quality more than any change of tool.
7. Failure modes that do the damage
Prompt injection through fetched pages
Any text retrieved from the web can contain instructions aimed at your agent, whether planted deliberately or by accident. The defences are structural. Wrap retrieved text in clearly delimited data sections and tell the model that content inside them is evidence, never instructions. Give the agent that reads the web the smallest possible set of tools, so that a hijacked reader cannot send email, write files or call internal APIs. Where an agent must both read the web and act, split it in two: a reader that returns a structured summary, and an actor that never sees raw page text.
Stale and cached content
Crawlers and hosted APIs cache. A page edited this morning may be served from yesterday's copy. For anything where recency matters, record the retrieval time and, where the page exposes one, its published or modified date, and make the agent state them in the answer. If no date can be found, say so rather than implying the information is current.
SEO spam and circular sourcing
Low-quality pages that paraphrase one original source can outrank the original. Ten results that all cite each other count as one source. Prefer primary sources (the vendor's documentation, the specification, the repository), and when you must rely on secondary ones, require two that are independent.
Silent empty results
An engine returns zero hits because it was blocked, and the agent concludes that nothing exists. Distinguish "no results" from "search failed" in your tool wrapper and surface the difference to the model.
Truncation and boilerplate bias
If you cut every page to the first N characters, you keep the navigation and lose the body. Truncate after cleaning, and prefer chunking by relevance to the question over cutting from the top.
8. A worked example: a grounded lookup with citations
The following sketch finds candidates with a self-hosted SearXNG instance, reads the best pages with Crawl4AI and returns evidence objects that carry their source and retrieval time. It deliberately stops before the model call, because the interesting design decision is what the model is allowed to see. The instance URL and the allow-list are placeholders to replace with your own.
import asyncio
from datetime import datetime, timezone
from urllib.parse import urlparse
import httpx
from crawl4ai import AsyncWebCrawler
SEARX_URL = "http://localhost:8080/search" # your own instance
ALLOWED = {"docs.example.com", "github.com"} # trusted domains
MAX_CHARS = 6000 # per page, after cleaning
async def discover(client: httpx.AsyncClient, query: str) -> list[dict]:
resp = await client.get(
SEARX_URL,
params={"q": query, "format": "json", "categories": "general"},
timeout=10,
)
resp.raise_for_status()
results = resp.json().get("results", [])
if not results:
raise RuntimeError("search returned no results; treat as failure, not as 'nothing exists'")
return [r for r in results if urlparse(r["url"]).hostname in ALLOWED][:3]
async def retrieve(crawler: AsyncWebCrawler, hit: dict) -> dict | None:
result = await crawler.arun(url=hit["url"])
if not result.success:
return None # keep going; one dead page must not sink the task
text = str(result.markdown)[:MAX_CHARS]
return {
"url": hit["url"],
"title": hit.get("title", ""),
"retrieved_at": datetime.now(timezone.utc).isoformat(),
"text": text,
}
async def grounded_evidence(query: str) -> list[dict]:
async with httpx.AsyncClient() as client:
hits = await discover(client, query)
async with AsyncWebCrawler() as crawler:
pages = await asyncio.gather(*(retrieve(crawler, h) for h in hits))
return [p for p in pages if p]
if __name__ == "__main__":
evidence = asyncio.run(grounded_evidence("webhook signature header"))
for e in evidence:
print(e["url"], e["retrieved_at"], len(e["text"]))
Several choices in that sketch carry the weight. The allow-list filters results after discovery, so a spam domain never reaches the crawler. An empty result list raises an error instead of returning an empty list, which forces the caller to distinguish failure from absence. Each evidence object keeps its URL and retrieval time so the final answer can cite them. A failed page returns None and the task continues with what remains.
The step after this code is the grounding step, and it belongs in the prompt and in code you can test. Pass the evidence as delimited data. Require that every factual sentence in the answer cite one of the supplied URLs. After generation, check mechanically that each cited URL appears in the evidence list, and reject or retry answers that cite anything else. If the evidence does not contain the answer, the correct output is "I could not find this in the sources I checked", with the list of sources checked.
9. When not to search, common mistakes and what to do on Monday
When not to use web search
- The answer lives in your own documents, tickets or code. Search those first; the open web adds noise and risk.
- The question is stable and well covered by the model, such as the meaning of an HTTP status code. Searching adds latency and a chance of being misled.
- The decision is high-stakes (legal, medical, financial). Retrieval can support a human reviewer; it should not replace one.
- The queries contain information you are not allowed to send to third parties.
Common mistakes
- Putting the user's whole message in the search box. Have the model write one or two focused queries instead, and log them.
- Letting the agent loop on search with no budget. Cap searches and fetched pages per task.
- Trusting snippets as evidence. Snippets choose pages; pages support claims.
- Giving the web-reading agent write access to anything.
- Not storing what was retrieved. Without the stored evidence you cannot debug a wrong answer after the page changes.
Frequently asked questions
Can I use only a crawler and skip search? Yes, when the set of relevant URLs is known in advance, such as a vendor's documentation site. A crawler plus an index of those pages is often more reliable than open-web search for that case.
Should the model decide which links to follow? It can propose them, but let code enforce the allow-list, the page budget and the depth limit.
Is a hosted API acceptable for a prototype? Usually, and it lets you learn what your agent actually needs. Record call counts from day one so a later move to self-hosting is based on data.
What to do on Monday
- Write down, for your agent, which questions require fresh external facts and which do not. Disable search for the second group.
- Pick a short list of primary-source domains and enforce it in code.
- Add a budget: a maximum number of searches and pages per task.
- Store every retrieved page with its URL and timestamp next to the answer it supported.
- Add one test where the evidence does not contain the answer, and assert the agent says so.
- Add one test with a page containing a hostile instruction, and assert the agent ignores it.