By the fastCRW team · Benchmark and credit figures verified 2026-05-18 · Verify independently before relying on any number.
Giving PydanticAI agents web tools
Giving a PydanticAI agent web tools means registering a search function and a scrape function as @agent.tool callables, each with a Pydantic model as its return type, so the framework validates what comes back from the web before the model ever reasons over it. PydanticAI validates tool inputs and outputs against your models automatically; the tool body just has to return data that already matches the shape. This post builds two tools — search_web and scrape_url — wires them onto one agent with shared dependencies, and adds a validation retry so a blocked or empty scrape gets a second attempt instead of silently poisoning the agent's context.
This is a different problem from JSON-schema field extraction, which is covered in Pydantic AI + fastCRW: type-safe web extraction. Here the agent decides which pages to look at and what to do with them — search, then read, then reason — and the tools just need to hand back clean, typed, trustworthy data at each step.
Why typed tool output matters for a web agent
An agent that calls a tool returning a raw string has no guarantee about what is inside that string — a real page, an error message, or an empty response after a block. If the tool's return type is a Pydantic model instead, PydanticAI validates the shape before the model sees it, and you can attach field constraints (a non-empty content: str, a valid url: HttpUrl) that catch malformed data at the boundary rather than three reasoning steps later.
The other half of the problem is retryable failure. A web fetch can come back empty because of a transient block, not because the page has no content. PydanticAI's ModelRetry exception lets a tool say "this result was bad, try again" and the framework re-invokes the tool call — which is the right response to a flaky scrape, and the wrong response to hard-code as a silent empty string.
Setting up shared dependencies
Both tools need an HTTP client and the fastCRW API key. PydanticAI's dependency injection (deps_type + RunContext) is the natural home for that — define it once, and every tool on the agent gets it through ctx.deps instead of re-reading an environment variable per call.
from dataclasses import dataclass
import httpx
from pydantic import BaseModel, Field, HttpUrl
from pydantic_ai import Agent, RunContext, ModelRetry
@dataclass
class WebDeps:
client: httpx.AsyncClient
api_key: str
CRW_BASE = "https://api.fastcrw.com/v1"
Create the agent with that dependency type and a model result type you define next:
agent = Agent(
"anthropic:claude-sonnet-4-5",
deps_type=WebDeps,
system_prompt=(
"You research topics using the search_web and scrape_url tools. "
"Search first to find candidate pages, then scrape the most "
"relevant ones before answering. Cite the URLs you used."
),
)
Tool 1: search_web, a typed search wrapper
The search tool calls POST /v1/search and returns a list of typed results — not the raw JSON envelope. Modeling the output shape here means the agent's reasoning always sees the same fields, regardless of how fastCRW's response happens to be structured internally.
class SearchResult(BaseModel):
title: str
url: HttpUrl
snippet: str = ""
@agent.tool
async def search_web(
ctx: RunContext[WebDeps], query: str, limit: int = 5
) -> list[SearchResult]:
"""Search the web and return ranked results with title, url, snippet."""
resp = await ctx.deps.client.post(
f"{CRW_BASE}/search",
headers={"Authorization": f"Bearer {ctx.deps.api_key}"},
json={"query": query, "limit": limit},
timeout=30.0,
)
resp.raise_for_status()
data = resp.json()
results = data.get("data", data.get("results", []))
if not results:
raise ModelRetry(f"No search results for '{query}'; try a broader query.")
return [
SearchResult(
title=r.get("title", ""),
url=r["url"],
snippet=r.get("description", r.get("snippet", "")),
)
for r in results
]
The ModelRetry on an empty result set is deliberate: a zero-result search is often a query the agent phrased too narrowly, and letting the model rephrase and retry is more useful than returning an empty list it has to reason around.
Tool 2: scrape_url, with a content-quality retry
The scrape tool calls POST /v1/scrape with onlyMainContent: true so the agent gets the article body, not nav and footer chrome. The return model enforces that content is present; the tool body enforces that it is not suspiciously short, which is the cheapest signal that a fetch hit an anti-bot wall or a JS-only shell.
class ScrapedPage(BaseModel):
url: HttpUrl
title: str = ""
content: str = Field(min_length=1)
@agent.tool
async def scrape_url(ctx: RunContext[WebDeps], url: str) -> ScrapedPage:
"""Fetch a URL and return its main content as clean markdown."""
resp = await ctx.deps.client.post(
f"{CRW_BASE}/scrape",
headers={"Authorization": f"Bearer {ctx.deps.api_key}"},
json={"url": url, "onlyMainContent": True, "formats": ["markdown"]},
timeout=30.0,
)
resp.raise_for_status()
payload = resp.json().get("data", {})
markdown = payload.get("markdown", "")
if len(markdown.strip()) < 40:
raise ModelRetry(
f"Scrape of {url} returned almost no content "
"(likely blocked or JS-rendered); try a different URL or renderJs."
)
return ScrapedPage(url=url, title=payload.get("title", ""), content=markdown)
The min_length=1 on the Pydantic field is the hard validation boundary — PydanticAI rejects a genuinely empty content before the model sees it. The 40-character check inside the tool is a softer, retryable signal: a fetch that technically returned text but not enough of it to be useful gets one more attempt rather than an outright validation failure.
Typing the agent's final answer
Give the agent a result_type too, so the answer it produces after calling both tools is itself validated — a structured research note rather than free text with citations buried in prose.
class ResearchNote(BaseModel):
answer: str
sources: list[HttpUrl]
research_agent = Agent(
"anthropic:claude-sonnet-4-5",
deps_type=WebDeps,
result_type=ResearchNote,
system_prompt=agent.system_prompt if hasattr(agent, "system_prompt") else "",
tools=[search_web, scrape_url],
)
async def main():
async with httpx.AsyncClient() as client:
deps = WebDeps(client=client, api_key="crw_live_...")
result = await research_agent.run(
"What renderer does fastCRW use as its default JS fallback?", deps=deps
)
print(result.data.answer)
print(result.data.sources)
Because sources is typed as list[HttpUrl], a malformed or hallucinated URL in the answer fails Pydantic validation and PydanticAI retries the generation — the same mechanism that protects tool output now protects the final answer.
What the round trip costs
Every tool call is a normal fastCRW request billed the normal way: 1 credit per search, 1 credit per scraped page, no premium for the renderer that ends up serving the request. A research loop that searches once and scrapes three of the results costs 4 credits, whether or not a retry fired — a ModelRetry re-invokes the tool, and the re-invocation is a fresh, separately billed call. Budget for retries the same way you budget for the base calls. The managed cloud free tier is 1,000 one-time lifetime credits, enough to build and debug this agent before deciding between cloud and self-host; compare current numbers at /pricing.
| Tool | Endpoint | Credit cost | Retry trigger |
|---|---|---|---|
search_web | POST /v1/search | 1 credit per call | zero results |
scrape_url | POST /v1/scrape | 1 credit per page | content under 40 chars |
Honest limits
Two things this pattern does not do. First, neither tool here uses fastCRW's /v1/extract JSON-schema path — both return markdown and let the agent's own reasoning pull facts out of it, which is the right shape for open-ended research but the wrong shape when you need guaranteed structured fields; for that, use the extraction-focused pattern in Pydantic AI + fastCRW: type-safe web extraction instead. Second, the ModelRetry content-length check is a heuristic, not a block detector — a legitimately short page (a redirect stub, a thin listing) will also trigger a retry and waste one credit. If you are scraping a known-short-page domain, lower the threshold or drop the check and rely on the field's min_length=1 alone.
fastCRW is stateless per request: it does not cache or remember a prior scrape of the same URL, so an agent that revisits a page in the same run pays for it twice. If that matters for your workload, cache ScrapedPage results in the agent's own run state rather than relying on the API to dedupe. For the surrounding self-host-vs-cloud tradeoff, see agentic RAG with fastCRW; for the raw REST surface these tools wrap, see best markdown extraction APIs.
Sources
- PydanticAI docs (tools, dependencies,
ModelRetry, result validation): ai.pydantic.dev - fastCRW engine and API reference: github.com/fastcrw/crw
- fastCRW pricing and credits: /pricing · benchmark detail: /benchmarks
Related: Pydantic AI + fastCRW: type-safe web extraction · Agentic RAG with fastCRW · Best markdown extraction APIs
