Built-in Search and File Reading in Chat APIs: How to Calculate Agent Costs

    Built-in search, link reading, and file parsing in chat APIs reduce client-side orchestration, but they do not remove the need for cost accounting. This article explains the two capability layers, how tool calls execute, how to model token, per-call, and retry costs, and how to implement timeouts, logging, and graceful degradation in production.

    1. Why Search and File Reading Are Moving into Model APIs

    Large models have a training knowledge cutoff and cannot directly read documents or web pages that users hold. In the past, developers who wanted a model to answer real-time questions usually had to build a pipeline themselves: call a search service to get a result list, fetch page content, clean noise, truncate to a suitable length, and finally insert the content into the prompt. The same applied to documents: PDFs, Word files, and presentations had to be parsed into text first, then chunked and retrieved.

    Every step in that pipeline is a separate engineering module, each with its own timeout, failure retry, format compatibility, and cost issues. As Agent-style applications grow, more model services are moving part of this capability to the server side. For developers, API call complexity does not disappear, but the code and state they must maintain themselves are reduced.

    This article discusses how these “built-in tools in chat interfaces” work, their cost structure, and engineering implementation methods. It covers only general concepts that are common in the industry. For specific parameters, unit prices, and limits, refer to the official documentation of the service you use.

    2. Two Capability Layers: Built-in Chat Tools and Standalone APIs

    From a usage perspective, these services usually fall into two layers.

    The first layer is tools inside the chat interface. Developers declare the tools to enable in the request, and the model decides whether to call them based on the question. Common tools include:

    • Web search: the model proposes search terms, and the server performs retrieval and returns result summaries or snippets.
    • Deep search: the model alternates between reasoning and retrieval during inference, using intermediate results to decide what to search next.
    • Link reading: given a URL, the server fetches the page and extracts the main content.
    • File input: upload a document, the server parses it, and the model answers based on the document content.
    • Content safety moderation: risk detection on input or output.

    The second layer is standalone APIs. Search, web scraping, optical character recognition, speech recognition, and speech synthesis can be called independently of chat. These APIs are suitable for embedding in your own workflows, such as batch page scraping, batch recognition of scanned documents, or speech capabilities in non-chat scenarios.

    The two layers do not conflict. Built-in chat tools are suitable for quickly building question-answering applications, while standalone APIs are suitable for systems that need fine-grained control over the workflow.

    Selection Points

    The table below compares the two forms across five dimensions.

    Dimension Built-in chat tools Standalone APIs
    Real-time behavior The model decides when to retrieve, suitable for open-ended Q&A Retrieval timing is decided by your code, and pre-fetching is possible
    Controllability Search terms, crawl scope, and loop count are decided by the server Custom keywords, filtering rules, and caching strategies are possible
    Batch processing Called turn by turn, inefficient for batch scenarios Suitable for batch tasks, with concurrency and rate limiting
    Cost visibility Costs are mixed into model tokens and need to be split for accounting Each call is billed separately, making attribution easier
    Compliance and data User content is processed server-side; confirm data retention rules Data can be sanitized in your own system before calling

    Before integration, check three items:

    1. Confirm the tool call limit and timeout parameters, and set an overall timeout on the business side.
    2. Record the latency, status, and billed count of each tool call, and reconcile them with the bill every month.
    3. Use a fixed set of questions for regression testing, comparing answer quality and per-request cost with tools enabled and disabled.

    3. How Tool Calls Execute

    Understanding the execution order of tool calls is necessary to determine where latency and costs occur. A request with tools usually goes through the following stages:

    1. The client sends the question, conversation history, and tool switches.
    2. The model decides whether external information is needed. If not, it generates an answer directly.
    3. If needed, the model generates a tool call request, and the server performs retrieval, scraping, or parsing.
    4. The server writes the tool result back into the context.
    5. The model continues reasoning based on the new context and may call tools again.
    6. The model outputs the final answer and returns call records or citation information.

    Steps 3 through 5 may loop multiple times. In deep search mode, the number of tool operations in one Q&A round may be significantly higher than in ordinary search, and latency and token consumption rise accordingly. The server generally sets a per-turn tool call limit; developers should check the documentation to confirm that limit.

    Latency Breakdown

    The time for one request can be split into the following segments. Only by recording each segment can you know where to optimize:

    • Model inference: time spent generating tool call requests or the final answer in each round.
    • Retrieval: time for the search service to return a result list.
    • Fetching: time to read a web page or download a file; this segment is longest when the website responds slowly.
    • Parsing: time to convert a document into text; more noticeable as file size increases.
    • Retry: accumulated time from repeated requests after failures.

    Deep search amplifies the inference and retrieval segments. Each new round of tool results enters the context, and subsequent inference must read a longer input, so latency and token costs grow together.

    4. How to Calculate Costs

    The cost of tool calls consists of three parts: model tokens, per-call tool billing, and waste from failed retries. There are also small storage, bandwidth, and logging costs. These are usually minor but should be recorded separately.

    Total cost can be written as:

    Total cost = model input token cost + model output token cost + per-call tool fees + retry waste + other costs

    Model input token cost requires special handling. Each inference round re-reads the full context, including conversation history and previously written-back tool results. Therefore, total input tokens are not a single accumulation of one turn’s length but the sum of context lengths across all turns.

    Variable Table

    Variable Meaning Source
    T_base Input tokens in the first round, including system prompt, history, and question Request logs or usage field
    T_r Tokens of new tool results written back in round r Length of tool return content
    R Number of model inference rounds Round count in call records
    T_out Total model output tokens usage field
    N_search, N_read, N_parse Number of search, link reading, and file parsing calls Tool call records
    P_in, P_out Input and output token unit prices Official pricing page; annotate the date used
    P_search, P_read, P_parse Per-call tool unit prices Official pricing page
    F Proportion of failed requests that were billed Comparison of failure logs and bills

    The formula for estimating input tokens is:

    Total input tokens = Σ (Tbase + T_1 + … + T(r-1)), where r goes from 1 to R

    Accounting Example

    The numbers below are only for demonstrating the calculation process and do not represent actual prices or usage of any service.

    Suppose a question triggers three inference rounds. The first round input is 2,000 tokens, the second round writes back 1,200 tokens of search results, and the third round writes back 1,800 tokens of web page content. The three input rounds are 2,000, 3,200, and 5,000, totaling 10,200 tokens. Total output across the three rounds is 1,100 tokens. During this process, two searches and one link reading call are made.

    Plugging into the formula:

    Cost = 10,200 × P_in + 1,100 × P_out + 2 × P_search + 1 × P_read + retry waste

    If one request times out and is retried, the billed portion of the failed request should also be included in retry waste. This example shows that even if tool unit prices are low, the accumulated input tokens from multiple rounds can become the main cost.

    Measurement Scope

    Cost figures must state their scope; otherwise, they cannot be compared. Record the following information for each accounting exercise:

    • Measurement date and pricing version used.
    • Model name and version.
    • Distribution of input lengths, such as average and maximum.
    • Number of tool calls, distinguishing ordinary search from deep search.
    • Ratio of successful to failed requests.

    Unit prices without a basis should not be written into documentation or cost models. After unit prices change, recalculate.

    5. Client Implementation Example

    The example below shows how a client can initiate a request with tools, handle timeouts and rate limiting, and record call details. Field names and API endpoint are illustrative; replace them according to the official documentation of the service you use.

    1. import os
    2. import time
    3. import requests
    4. API_URL = os.environ["CHAT_API_URL"] # Illustrative; refer to official documentation
    5. API_KEY = os.environ["CHAT_API_KEY"] # Read from environment variable; do not hard-code
    6. MAX_ATTEMPTS = 3
    7. def build_tools(enable_search: bool, enable_reader: bool) -> list:
    8. tools = []
    9. if enable_search:
    10. tools.append({"type": "web_search"}) # Illustrative field
    11. if enable_reader:
    12. tools.append({"type": "web_reader"}) # Illustrative field
    13. return tools
    14. def log_tool_calls(tool_calls: list) -> None:
    15. for call in tool_calls:
    16. # Do not log full request inputs, to avoid writing user documents or private content to logs
    17. print({
    18. "tool": call.get("name"),
    19. "duration_ms": call.get("duration_ms"),
    20. "status": call.get("status"),
    21. "billed_units": call.get("billed_units", 1),
    22. })
    23. def ask(question: str, history: list, enable_search=True, enable_reader=False, timeout_s=30) -> dict:
    24. payload = {
    25. "model": "your-model-name", # Replace with the actual model name
    26. "messages": history + [{"role": "user", "content": question}],
    27. "tools": build_tools(enable_search, enable_reader),
    28. }
    29. headers = {"Authorization": f"Bearer {API_KEY}"}
    30. for attempt in range(MAX_ATTEMPTS):
    31. try:
    32. resp = requests.post(API_URL, json=payload, headers=headers, timeout=timeout_s)
    33. except requests.Timeout:
    34. time.sleep(2 ** attempt) # Exponential backoff
    35. continue
    36. except requests.RequestException:
    37. break
    38. if resp.status_code in (429, 500, 502, 503):
    39. time.sleep(2 ** attempt)
    40. continue
    41. if resp.status_code != 200:
    42. break
    43. data = resp.json()
    44. tool_calls = data.get("tool_calls", [])
    45. log_tool_calls(tool_calls)
    46. return {
    47. "answer": data["choices"][0]["message"]["content"],
    48. "citations": data.get("citations", []),
    49. "tool_calls": tool_calls,
    50. "usage": data.get("usage", {}),
    51. }
    52. # Degrade after all retries fail, so the entire page does not error
    53. return {
    54. "answer": "Web search is temporarily unavailable. The following content may not include the latest information. Please try again later.",
    55. "citations": [],
    56. "tool_calls": [],
    57. "usage": {},
    58. }

    Key points in the example:

    • Timeouts and rate limiting use exponential backoff retries, with a retry limit to avoid runaway costs.
    • Tool call logs keep only the tool name, duration, status, and billed count for cost attribution.
    • After all retries fail, return a degraded message and clearly tell the user that the answer does not include the latest information.

    6. Risks, Timeouts, and Degradation

    The client should handle several common failures: tool failure, timeout, quota limits, and parsing failure.

    • Tool failure: when search or scraping returns an error, preserve the model’s existing answer and state which information could not be obtained.
    • Timeout: set an overall timeout on the business side. After it is exceeded, return existing results or a degraded message instead of waiting indefinitely.
    • Quota limits: when the call limit is reached or the quota is exhausted, stop further calls and ask the user to try again later.
    • Parsing failure: when a file cannot be parsed, tell the user the supported formats and size limits; do not pass empty content to the model.

    Retry strategy should be tied to cost. Use backoff retries for rate limiting and server errors. Do not retry deterministic failures such as parameter errors or permission errors, because that only duplicates billing.

    Citation Display and Content Compliance

    Citations returned by the model should display the source title and link so users can verify them. Do not display or republish the full page content scraped from a site as-is; large excerpts may raise copyright issues. Before scraping website content, review the site’s robots rules and terms of use.

    Data Retention and Privacy

    Documents uploaded by users and questions they enter may contain personal information or trade secrets. Before integration, confirm three things: how long the server retains this content, whether it is used for training, and whether it can be deleted on request. If these conditions are unacceptable, sanitize data in your own system first, or use standalone APIs so you control the data flow.

    7. Conclusion

    Built-in search and file reading in chat interfaces reduce client-side orchestration code, but they do not reduce the work of cost accounting. Costs mainly come from context repeatedly sent during multi-round inference, followed by per-call tool fees and failed retries. Accounting should use a fixed scope, record details of each call, and regularly reconcile with bills. For selection, consider real-time requirements, controllability, batch processing, cost visibility, and compliance and data handling.