Skip to content
Claude Web Search Filtering: Cheaper Cited Agents in Python — ContentBuffer guide

Claude Web Search Filtering: Cheaper Cited Agents in Python

K
Kodetra Technologies··9 min read Intermediate

Summary

Build cheap, cited research agents on Claude Sonnet 5 using the web search tool and dynamic filtering.

Anthropic shipped Claude Sonnet 5 on June 30, 2026, and by July 1 it was the default model for every Free and Pro user. The headline was not a benchmark. It was the price: $2 per million input tokens and $10 per million output through August 31, 2026, for a model that plans, browses, and runs tools close to the level of Opus 4.8. Anthropic pitched it as a cheaper way to run agents, and that framing landed at exactly the moment teams were staring at Q2 agent bills they did not expect.

Here is the part that does not fix itself when the model gets cheaper. If you build a research agent that searches the web, the raw pages it pulls back are dumped into the context window as input tokens on every turn that follows. A single question can trigger ten searches, and each result page can be thousands of tokens. You pay for all of it, again and again, as the conversation grows. A cheaper model with an expensive context is still an expensive agent.

This guide fixes that. You will build a research agent on Claude Sonnet 5 using Anthropic's server-side web search tool, then switch on two features from the web_search_20260318 version that most people miss: dynamic filtering, where Claude writes code to trim search results before they ever reach its context, and response_inclusion, which stops the API from echoing raw search content back into your output tokens. Every answer comes with real citations, because for web search they are always on. By the end you will have a cited research agent that keeps its own token bill under control.

Prerequisites

  • Python 3.9+ and the official SDK: pip install anthropic (use 0.40 or newer).
  • An Anthropic API key exported as ANTHROPIC_API_KEY.
  • Web search enabled for your organization. It is on by default, but an admin can disable it in the Claude Console under Settings > Privacy. If it is off, a request that includes the tool fails with a 400.
  • A rough feel for the Messages API: you send messages, you get back a list of content blocks.

Web search is billed at $10 per 1,000 searches on top of normal token costs, so while you are learning, cap it with max_uses so a runaway loop cannot surprise you.

Step 1: The naive search agent, and why it gets expensive

Web search is a server tool. You do not run the search yourself and you do not append a tool result. You add the tool to the request, and the API runs the searches inside the same turn, then hands Claude the results and lets it answer with citations. Here is the smallest working version:

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment

resp = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    messages=[{
        "role": "user",
        "content": "What changed in the Claude Sonnet 5 release, and what does it cost?",
    }],
    tools=[{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}],
)

for block in resp.content:
    if block.type == "text":
        print(block.text)

print("searches:", resp.usage.server_tool_use.web_search_requests)

That works and it is cited. The problem is web_search_20250305, the basic version: every search result is loaded into the context window in full. On a five-search question that can be tens of thousands of input tokens, and because you must send the assistant's blocks back on later turns to keep the conversation valid, you keep paying for that bulk. The fix is not to search less. It is to filter.

Step 2: Turn on dynamic filtering

With web_search_20260209 and later, Claude runs the search from inside a sandboxed code execution step, writes a small amount of code to filter the results down to what actually matters, and only the filtered output reaches the context window. Anthropic calls this dynamic filtering. You do not add a code execution tool yourself and there is no extra charge for it beyond the tokens you would pay anyway. You just bump the tool version:

resp = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=2048,
    messages=[{
        "role": "user",
        "content": (
            "Compare the current per-token API prices of the newest frontier "
            "models and tell me which is cheapest for output-heavy agents."
        ),
    }],
    tools=[{
        "type": "web_search_20260318",   # newest version: filtering + response control
        "name": "web_search",
        "max_uses": 15,                  # research questions can use 10+ searches
    }],
)

print("searches:", resp.usage.server_tool_use.web_search_requests)
print("input tokens:", resp.usage.input_tokens)

One thing to know about the plumbing: on web_search_20260209 and later, the tool's allowed_callers field defaults to ["code_execution_20260120"], which is what enables filtering. If your model does not support programmatic tool calling, or you deliberately want the old behavior, set allowed_callers: ["direct"]. Skip that setting on a model that needs it and the API returns a 400 telling you exactly what to add. Claude Sonnet 5 supports filtering, so the default is what you want.

Step 3: Stop paying to echo search content back

Dynamic filtering trims what enters Claude's context. response_inclusion trims what comes back to you. When a search is consumed by a completed code execution step in the same turn, the API normally returns those nested server_tool_use and search-result blocks in the response, and you pay output tokens for them. If your app only needs the final answer and its citations, drop them:

tools = [{
    "type": "web_search_20260318",
    "name": "web_search",
    "max_uses": 15,
    "response_inclusion": "excluded",   # default is "full"
}]

Set "response_inclusion": "excluded" and those raw nested pairs are dropped from the response, cutting output token cost for agent workflows that never display raw search content. Two caveats worth remembering: it requires web_search_20260318 or later, and results from direct calls, or from a code execution call that paused mid-turn, are always returned in full so you can send them back on the next turn. In other words, the API only excludes what it is safe to exclude.

Step 4: Pull out the citations

For web search, citations are always enabled, and if you show the answer to end users you are required to display them linking to the original source. Each cited span rides along on a text block as a web_search_result_location citation carrying a url, a title, and up to 150 characters of cited_text. Note that these citation fields do not count toward your token usage. Here is a renderer that stitches the answer together and lists unique sources:

def render_answer(resp):
    text_parts, sources = [], {}
    for block in resp.content:
        if block.type != "text":
            continue
        text_parts.append(block.text)
        for c in (block.citations or []):
            if c.type == "web_search_result_location":
                sources.setdefault(c.url, c.title)  # de-dupe by URL

    answer = "".join(text_parts)
    refs = "\n".join(f"- [{title}]({url})" for url, title in sources.items())
    return f"{answer}\n\nSources:\n{refs}"

print(render_answer(resp))

Because you de-dupe by URL, ten searches that keep citing the same three pages collapse into a clean three-item source list instead of a wall of repeats.

Step 5: Multi-turn without breaking the loop

A research turn can run long enough that the API pauses it and returns stop_reason: "pause_turn". It is not an error. You send the paused assistant message back unchanged and the search continues. The other rule that trips people: to continue any conversation that contains search results, you must send the assistant's content blocks back exactly as you received them, including each result's encrypted_content. Modify or drop it and the next request fails with a 400. The simplest correct loop just appends resp.content and never touches it:

def run_research(question, max_turns=6):
    messages = [{"role": "user", "content": question}]
    tools = [{
        "type": "web_search_20260318",
        "name": "web_search",
        "max_uses": 20,
        "response_inclusion": "excluded",
    }]

    for _ in range(max_turns):
        resp = client.messages.create(
            model="claude-sonnet-5",
            max_tokens=4096,
            messages=messages,
            tools=tools,
        )
        # Append assistant blocks EXACTLY as received (encrypted_content intact).
        messages.append({"role": "assistant", "content": resp.content})

        if resp.stop_reason == "pause_turn":
            continue          # long search paused; resend unchanged to resume
        return resp           # end_turn: Claude has finished answering

    raise RuntimeError("hit max_turns without finishing")

final = run_research(
    "Which frontier LLM is cheapest per output token as of this week, "
    "and by how much versus its closest rival?"
)
print(render_answer(final))

Notice what is not here: no manual tool execution, no hand-built tool_result blocks. Because web search is a server tool, the only control flow you own is the pause_turn resume. That is the whole point of server tools, and it is why this loop stays short.

A worked example, end to end

Run run_research on the cheapest-model question above and you get back a cited answer plus usage you can actually inspect. Illustrative output:

As of this week, Claude Sonnet 5 sits at $2 / $10 per million input/output
tokens under its introductory pricing, which undercuts most frontier peers on
output-heavy agent workloads. Its nearest rival on price-per-capability is
Gemini 3.5 Flash, positioned for fast production use, but Sonnet 5's agentic
scores land closer to flagship models at the same tier...

Sources:
- [Claude Sonnet 5 models overview](https://platform.claude.com/docs/en/about-claude/models/overview)
- [Sonnet 5: cheaper agents](https://knightli.com/en/2026/07/02/claude-sonnet-5-agentic-model-release/)

# usage snapshot for the run:
# server_tool_use.web_search_requests = 6
# input_tokens  = 8,142   (filtered, not raw pages)
# output_tokens = 1,203

Do the same run on web_search_20250305 with response_inclusion off and the input token count on a six-search question is typically several times higher, because the unfiltered pages and the echoed nested blocks are all in play. Same answer, same citations, very different bill. That gap is the entire reason this version exists.

Common pitfalls and gotchas

  • Sending both domain filters. Use allowed_domains or blocked_domains, never both in one tool. Include both and the API returns a 400. Entries are bare domains like example.com or example.com/blog, with no https:// scheme.
  • Stripping encrypted_content. On multi-turn conversations you must pass the assistant's search-result blocks back untouched. If encrypted_content is missing or modified, the request fails with a 400 validation error. Append resp.content as-is; do not rebuild it.
  • Treating pause_turn as done. It is a pause, not an end. Check stop_reason; on pause_turn, resend the paused assistant message unchanged to continue the search.
  • max_uses errors look like success. If Claude exceeds max_uses, the API still returns HTTP 200, but the search block carries web_search_tool_result_error with code max_uses_exceeded. Other codes to expect: too_many_requests, query_too_long, request_too_large (usually a huge domain list), and unavailable. Handle them in the response body, not as exceptions.
  • Using response_inclusion on the wrong version. It only exists on web_search_20260318 and later. On older versions the field is ignored or rejected. Dynamic filtering itself needs web_search_20260209 or later.
  • Assuming filtering works everywhere. Dynamic filtering runs on the Claude API, Claude Platform on AWS, and Microsoft Foundry (Hosted on Anthropic). On Google Cloud only basic web search is available, and web search is not available on Amazon Bedrock at all.
  • Forgetting the search line item. Searches cost $10 per 1,000 on top of tokens, and each search counts as one use regardless of result count. A failed search is not billed, but a loop with no max_uses can still run up a tab.

Quick reference

SettingWhat it doesNotes
web_search_20250305Basic web searchLoads all results into context in full
web_search_20260209Adds dynamic filteringallowed_callers defaults to code execution
web_search_20260318Adds response_inclusionNewest; use this for agents
max_usesCaps searches per request3 for lookups, 15-20 for research agents
response_inclusion"excluded" drops echoed search blocksCuts output tokens; 20260318+ only
allowed_callersdirect vs code_executionSet ["direct"] to force basic behavior
allowed_domains / blocked_domainsRestrict sourcesOne or the other, never both
stop_reason == pause_turnLong search pausedResend assistant message unchanged

Next steps

You now have a cited research agent on Claude Sonnet 5 that filters its own search results and does not pay to echo them back. From here, three directions pay off quickly. Add allowed_domains to pin the agent to sources you trust for a given task, such as official docs or a set of newsrooms. Pair web search with the web fetch tool so Claude can pull a specific URL in full when a snippet is not enough. And layer prompt caching on the tool definitions and system prompt so repeat runs get cheaper still, which stacks neatly on the token savings you just built.

The larger lesson outlives this one release. When models get cheap, the context window becomes the cost center. The teams that win the agent-cost game are the ones who treat every token that enters the context as something to justify, not something to dump. Dynamic filtering is Anthropic handing you that discipline as a one-line setting.

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,605 newsletter subscribers.

Also get