When Web Search and Page Fetching Become Part of Token Billing: What Developers Should Check
A change from per-request charges to unified token billing can simplify cost reconciliation, but it does not necessarily reduce costs. Search results and fetched pages are added to the model context, which can significantly increase input token usage. This article explains what developers should verify in the billing policy and presents practical methods for measuring and controlling costs.
1. Confirm the Billing Rules Before Making Assumptions
Vendors use different pricing models for web search and page fetching. Some include these operations in token billing, while others continue to charge per tool call or bill separately for caching and storage.
Before preparing a budget, review the vendor’s official pricing page and announcement. Record the following details:
- The announcement date and effective date.
- The applicable models, API versions, and regions.
- Whether search and page fetching still incur separate charges, including tool-call and cache fees.
- The minimum billing unit—for example, whether input and output tokens are priced separately or combined into total token usage.
- Whether the announcement describes conditions for future changes.
If the official documentation does not clearly state that search fees have been removed, do not set search costs to zero in your budget.
2. Per-Request Billing vs. Unified Token Billing
| Comparison area | Per-request billing: search and fetching charged separately | Unified token billing: based on a vendor announcement |
|---|---|---|
| What is billed | Model tokens plus each search or page-fetch request | Model tokens, with retrieval-related usage included in token consumption |
| Budget estimation | Estimate both token usage and the number of tool calls | Primarily estimate token usage, while measuring how much retrieved content is injected |
| Multi-step retrieval | Each retrieval round creates a separate charge | Each retrieval round appears as additional input-token usage |
| Impact of input tokens | Retrieved content added to the context increases input tokens | Retrieved content added to the context is the main variable affecting token usage |
| Reconciliation | Logs must track tokens and tool calls separately | The usage totals in the response are the primary reference |
| Other charges | Check each item in the official pricing list | Confirm whether tool calls and cache storage are billed separately; do not assume they are free |
Unified billing mainly reduces the work required for accounting and recordkeeping. The bill is still driven by how much content the model reads and how many retrieval rounds the agent performs.
3. Unified Billing Does Not Automatically Mean Lower Costs
Input-token growth
A fetched web page may contain a large amount of text. If the full page is inserted into the context without processing, input-token usage can grow quickly.
Before injecting page content, truncate it and remove irrelevant elements such as navigation menus and advertisements. Keep only the passages related to the user’s question.
Multi-step retrieval loops
When an agent cannot reach a conclusion, it may repeatedly search for similar keywords. Each round increases token usage without necessarily improving answer quality.
Set a maximum number of retrieval rounds for each task. Also record the search terms used in each round and the number of tokens returned.
Duplicate queries
The same trending question may be submitted repeatedly by different users. If the application searches and fetches pages again for every request, costs will increase linearly.
Caching can significantly reduce repeated work, but cache freshness must be designed separately.
All three issues should be measured with real request samples. Developers can collect one week of production traffic and calculate the average, P95, and maximum values instead of relying on estimates.
4. Example: Tracking Tokens and Setting a Limit
The following is illustrative code. Replace the API URL, model name, and tool configuration with the values specified in the platform’s official documentation. The tools field is a placeholder, and its exact structure depends on the provider.
import osimport timeimport requests# Read secrets from environment variables instead of hard-coding themAPI_URL = os.environ["LLM_API_URL"] # Chat completions endpoint from the platform documentationAPI_KEY = os.environ["LLM_API_KEY"]MODEL = os.environ.get("LLM_MODEL", "your-model-name") # Placeholder; replace with the documented model nameTIMEOUT_SECONDS = 60MAX_RETRIES = 3TOKEN_ALERT_THRESHOLD = 8000 # Set this after measuring your own workloaddef ask_with_web_search(question: str) -> dict:headers = {"Content-Type": "application/json","Authorization": f"Bearer {API_KEY}",}payload = {"model": MODEL,"messages": [{"role": "system", "content": "Use web search when necessary and cite the sources used."},{"role": "user", "content": question},],# Placeholder configuration: follow the official tool schema"tools": [{"type": "web_search"}],"max_tokens": 1024,}for attempt in range(1, MAX_RETRIES + 1):try:resp = requests.post(API_URL,headers=headers,json=payload,timeout=TIMEOUT_SECONDS,)except requests.RequestException:if attempt == MAX_RETRIES:raisetime.sleep(2 ** attempt)continue# Retry 429 and 5xx responses. Other 4xx responses usually indicate# invalid parameters or authentication errors and should fail immediately.if resp.status_code == 429 or resp.status_code >= 500:if attempt == MAX_RETRIES:resp.raise_for_status()time.sleep(2 ** attempt)continueresp.raise_for_status()data = resp.json()answer = data["choices"][0]["message"]["content"]usage = data.get("usage", {})total = usage.get("total_tokens", 0)if total > TOKEN_ALERT_THRESHOLD:print(f"[Alert] This request used {total} tokens, "f"exceeding the threshold of {TOKEN_ALERT_THRESHOLD}")return {"answer": answer, "total_tokens": total, "usage": usage}raise RuntimeError("Retry limit exceeded")if __name__ == "__main__":result = ask_with_web_search("Summarize the major recent technical developments in artificial intelligence and provide sources.")print(result["answer"])print(f"Tokens used: {result['total_tokens']}")
Before running the example, confirm the following:
- The required environment variables are set.
- The
usagefield matches the provider’s response schema. - If tool-call charges are reported in another field, record that field separately.
5. Three Cost-Control Measures
Set usage limits
Set a per-request token limit, a daily limit for each user, and a daily budget for the entire service.
When a limit is exceeded, return a degraded result instead of continuing to make tool calls.
Use caching
For queries that do not require real-time information, cache summaries of search results. A cache key can be based on normalized question text, with an expiration time ranging from several minutes to several hours depending on the query type.
Track cache-hit rates separately in your logs.
Add alerts and reconcile usage
For every request, log:
total_tokens- The number of retrieval rounds
- Whether the cache was hit
- Whether content truncation was triggered
Aggregate these values daily and compare them with the platform bill. Trigger an alert when daily token usage exceeds the baseline by a defined percentage. Set the threshold using historical data from your own application rather than adopting a fixed value.
6. Scope and Risks
Unified billing has a limited scope. An announcement may apply only to specific models and interfaces. Billing can differ when you switch to another model or API.
The removal of separate search or page-fetching fees does not mean that all related costs are eliminated. Confirm tool-call charges, cache storage, data transfer, and other items individually.
Search results may be outdated or inaccurate. For medical, legal, financial, and other high-impact use cases, retain the sources and require human review.
When fetching web pages, comply with the target site’s robots rules and terms of use. Content licensing and data-compliance requirements should also be reviewed before launch.
The results for the same query may vary over time. If reproducibility matters, record the retrieval time, search terms, and list of returned sources.
7. Developer Checklist
- Use official sources to verify the announcement’s effective date, billing rules, applicable models, and regions.
- Run load tests with real samples and record average, P95, and maximum token usage.
- Set per-request and daily token limits, along with alert thresholds.
- Limit the agent’s maximum number of retrieval rounds and record the search terms used in each round.
- Add caching for frequently requested queries, set expiration times, and track the cache-hit rate.
- Before launch, compare usage recorded in application logs with the platform bill.
