LLM API Web Search and Page Fetching: How to Evaluate the Costs

    This article explains how to evaluate and control the cost of adding web search and page fetching to large-model APIs. It breaks down the per-query cost components, clarifies how to interpret price changes, and presents engineering practices such as selective retrieval, caching, content cleaning, page limits, and graceful fallback. It also covers metrics, architecture, and compliance considerations, with sample Python code for caching and cost estimation.

    1. Why Web Access Raises Call Costs

    An LLM’s training data has a cutoff date, so answering time-sensitive questions requires external information. A common approach is to call a search API to get candidate links, fetch the page text, and then place that text into the context for the model to generate an answer. This chain involves three types of cost: search calls, page fetching, and the input tokens consumed when the model processes page content. Among these, input tokens often account for the largest share, because web pages contain navigation bars, ads, and script-generated noise text, and their raw length far exceeds the length of useful information.

    2. Breaking Down the Cost of a Single Q&A Request

    The cost of a single web-enabled Q&A request can be written as:

    Single-query cost ≈ search calls × search unit price + fetched pages × fetch unit price + input tokens × input unit price + output tokens × output unit price

    Each term is affected by business parameters. Search calls depend on whether retrieval is repeated; fetched pages depend on the result-filtering strategy; input tokens depend on how well body cleaning and truncation are performed. Only by quantifying these terms one by one can a team determine which term is most worth optimizing.

    In addition, whether failed search requests and timed-out fetch requests are billed should be based on the service provider’s official terms. During testing, failed calls should be tracked separately to avoid including hidden overhead in normal costs.

    3. Interpreting Price Changes Correctly

    When a web-access capability drops in price, or is even free for a period, first confirm the following:

    1. Free scope: whether there are limits on call count, concurrency, or daily quota;
    2. Service quality: whether low-cost or free resources have the same response latency and availability as paid resources;
    3. Validity period: whether the discount or resource-scheduling policy remains effective over the long term;
    4. Relationship with other costs: a single price reduction does not necessarily lower total cost. If it leads to fetching more pages, input-token costs may actually rise.

    The conclusion is that budgets should be calculated based on a total-cost model, with flexibility reserved for price changes. Temporary discounts should not be written directly into long-term budgets.

    4. Engineering Optimization Options

    (1) Trigger Web Access Only When Needed

    Not every question needs real-time information. A lightweight classifier can first determine whether a question involves time-sensitive content, such as news, prices, policies, or version numbers. Questions that do not need web access can be answered directly by the model, saving all retrieval costs. The classification logic can be implemented with rules plus a small model; the loss caused by misclassification is usually much lower than the cost of indiscriminate web access.

    (2) Cache Search and Fetch Results

    Queries on the same topic often recur within a short period. Cache search results and page text, and set expiration times by content type: news can use a shorter validity period, while encyclopedia-style content can use a longer one. Cache keys should be generated from normalized query terms, removing differences in case and extra whitespace so that requests differing only in casing or spacing can hit the cache.

    (3) Clean and Truncate Page Text

    After fetching, remove navigation, footers, scripts, and ad text, and keep only the main body paragraphs. Then rank them by relevance to the question, take the top paragraphs, and set a total token limit. This step usually has the greatest impact on cost, and it can also reduce cases where irrelevant information interferes with the model’s judgment.

    (4) Limit the Number of Fetched Pages

    Search results often contain more than ten items, but most answers only need two or three reliable sources. Set a maximum number of fetched pages, prioritize authoritative sites, and skip pages with duplicate content. When snippets are sufficient to answer the question, there is no need to fetch the full text.

    (5) Graceful Fallback on Failure

    When search or fetching times out, the system should fall back to the model’s own knowledge and state in the answer that the information may not be up to date. This controls waiting time and avoids uncontrolled costs caused by unlimited retries.

    Below is sample code with caching and a page limit. Here, clean_text is the body-cleaning function, and cache must provide get and set methods. Only the structure is shown; implement the details according to your project environment.

    1. import hashlib
    2. import time
    3. CACHE_TTL = {"news": 600, "general": 86400} # Unit: seconds
    4. def cache_key(query: str) -> str:
    5. normalized = " ".join(query.lower().split())
    6. return hashlib.sha256(normalized.encode("utf-8")).hexdigest()
    7. def fetch_with_cache(query, search_fn, fetch_fn, cache,
    8. max_pages=3, topic="general"):
    9. key = cache_key(query)
    10. hit = cache.get(key)
    11. if hit and time.time() - hit["ts"] < CACHE_TTL[topic]:
    12. return hit["docs"]
    13. results = search_fn(query)[: max_pages * 2]
    14. docs = []
    15. for item in results:
    16. if len(docs) >= max_pages:
    17. break
    18. text = fetch_fn(item["url"])
    19. if text:
    20. docs.append(clean_text(text)[:2000])
    21. cache.set(key, {"ts": time.time(), "docs": docs})
    22. return docs

    Cost estimation can follow a similar structure, making it easier to compare different strategies before launch:

    1. def estimate_cost(search_calls, fetched_pages, input_tokens,
    2. output_tokens, prices):
    3. return (search_calls * prices["search"]
    4. + fetched_pages * prices["fetch"]
    5. + input_tokens * prices["input"]
    6. + output_tokens * prices["output"])

    5. Measurement and Monitoring

    At minimum, track the following metrics:

    • Average cost per Q&A request, broken down by functional module;
    • Web-access trigger rate, meaning the share of requests that actually perform retrieval;
    • Average number of fetched pages and average number of input tokens;
    • Cache hit rate;
    • Failure and timeout rates for search and fetching.

    Combine these metrics with budget alerts so that when costs are abnormal, the cause can be identified quickly: whether it is traffic growth, a failed trigger policy, or a problem with the cleaning rules for a certain type of page.

    6. Architecture Design and Compliance Points

    First, encapsulate a unified retrieval interface. The business layer should depend only on internally defined data structures, such as title, link, snippet, and body text, rather than directly binding to the response fields of a specific service. In this way, when changing providers or adjusting billing methods, the scope of change is limited to the adapter layer.

    Second, when fetching web pages yourself, comply with the target site’s robots protocol and terms of service, respect copyright, control request frequency, and avoid placing an extra burden on the target site.

    Third, caching and logging components can use general capabilities on cloud platforms, such as object storage, key-value storage, and logging services. If the relevant services are deployed on Baidu AI Cloud, costs can be calculated according to the cost model above, and the actual billing data in the console should be used as the final reference. Query terms involving user data should be desensitized before being written to logs.

    7. Summary

    The core of cost optimization for web-access capabilities is to reduce unnecessary retrieval, compress the amount of text entering the context, and continuously monitor results with data. Price adjustments may bring short-term benefits, but long-term budgets should be built on a verifiable cost model, with the ability to recalculate at any time.