Practical Guide to Adding Web Search and File Reading to LLM APIs
This article explains how to extend a large language model API with web search and file reading capabilities using the tool-calling pattern. It covers how tool results accumulate in the context and drive up token usage, the four stages of search integration, document parsing and chunking with permission checks, multi-dimensional usage observability, a cost and latency optimization checklist, and security measures against prompt injection from untrusted external content. Readers will learn how to make per-call costs attributable and keep token spending under control.
1. What a Small Bill Reveals About the Real Cost of Capability Expansion
A developer reviewing daily usage found that a day of roughly a dozen API calls consumed about 17,000 tokens, costing less than a tenth of a cent. The bill is worth noting not because of the amount, but because it reflects a structural shift: LLM APIs are evolving from pure text generation into execution entities that can schedule external resources. When a model can initiate retrieval on its own and read documents a user has uploaded, a single question-and-answer exchange often corresponds to multiple rounds of internal reasoning and multiple tool round trips. Usage is therefore no longer the sum of one input and one output.
Understanding this is the prerequisite for capacity planning and cost governance. The following sections cover mechanisms, implementation, observability, optimization, and security.
2. Technical Foundation: Tool Calling and Context Assembly
The mainstream approach does not stuff a search engine or a file system into the model weights. Instead, it uses the tool-calling paradigm: during reasoning, the model emits a structured call intent, the runtime executes it for real, and the result is fed back to the model as new context. The loop continues until an answer is reached or a round limit is hit.
Illustrative pseudocode:
messages = [{"role": "system", "content": "You are a rigorous technical assistant. Cite sources when referencing external material."}]messages.append({"role": "user", "content": question})for step in range(max_steps):resp = client.chat.completions.create(model=model_name,messages=messages,tools=[web_search_tool, file_reader_tool],)messages.append(resp.choices[0].message)calls = resp.choices[0].message.tool_calls or []if not calls:breakfor call in calls:result = dispatch(call) # actually run the search or read the filemessages.append({"role": "tool", "tool_call_id": call.id, "content": result})
Three engineering points matter here. First, the context accumulates linearly: every tool result enters the input side of subsequent requests, so token consumption grows by accumulation and can even be amplified. Second, tool descriptions themselves consume input tokens; the more tools there are and the more verbose their descriptions, the higher the fixed overhead. Third, the round limit must be set explicitly, otherwise the model can loop on repeated calls without ever reaching a conclusion.
3. Web Search Integration: Retrieval Quality Determines Answer Quality
When adding retrieval, break “search” into four independently optimizable stages:
- Query rewriting: turn colloquial questions into retrieval-friendly keyword combinations, splitting them into multiple sub-queries for parallel recall when necessary.
- Result trimming: denoise the returned page content, strip ads, and extract the main passages, keeping only fragments relevant to the question instead of pushing large blocks of raw HTML into the context.
- Fragment ranking and deduplication: truncate by relevance to a set number of items, keeping the total length within budget.
- Citation and traceability: retain the title and link identifier for each fragment, and require the model to mark its basis in the answer, reducing the risk of answers that look plausible but have no source.
In practice, apply a hard length constraint to retrieval results: for example, cap each fragment at a few hundred words and cap total injection at a certain proportion of the context window, leaving the rest for conversation history and output space.
4. File Reading Integration: Parsing, Chunking, and Permission Boundaries
The hard part of document question answering is usually not the model but parsing and splitting:
- Format normalization: convert tables, presentations, plain text, and structured data into a unified intermediate representation with hierarchy information, preserving heading paths for locating content.
- Chunking strategy: split on semantic boundaries rather than fixed word counts, and keep a small overlap between chunks so answers do not break at the seams.
- Indexing and recall: in-memory retrieval works for small to medium scale; as scale grows, introduce a hybrid of vector retrieval and keyword retrieval to cover both semantic similarity and exact matching of proper nouns.
- Permission checks: read actions must be bound to the caller’s identity. Authenticate first, then parse, to eliminate unauthorized reads; temporary credentials should have short validity and minimal scope.
5. Usage Observability: Turning the Bill into Attributable Metrics
To read the bill as clearly as that developer did, build multi-dimensional observability. Beyond total tokens and request counts, track input tokens, output tokens, number of tool calls, average rounds, retrieval hit rate, and cache hit rate separately, and tag them by business identifier to achieve per-scenario attribution.
A simple local metering skeleton:
usage = {"input": 0, "output": 0, "steps": 0, "tool_calls": 0}# accumulate resp.usage.prompt_tokens / completion_tokens each round# emit structured logs with fields: trace_id, scene, latency, usage
Combined with general cloud capabilities such as logging services and monitoring alerts, you can set threshold notifications for abnormal volume spikes, excessively high rounds per request, and sudden cache invalidation.
6. Cost and Latency Optimization Checklist
- Trim prompts and tool descriptions: remove redundant explanations and keep the number of tools within what is necessary.
- Compress context: summarize earlier rounds, keeping only conclusions and key evidence.
- Cache results: build retrieval and answer caches for high-frequency queries, with an expiration policy in place.
- Tier models: assign lightweight tasks such as intent recognition and query rewriting to smaller models, and reserve larger models for complex reasoning.
- Stream output: return the first byte early to improve perceived latency, and make it easier to abort meaningless reasoning midway.
- Budget guardrails: set per-session round and token limits, and degrade to “answer using only the material already available” when exceeded.
7. Security and Compliance Baseline
Adding external capabilities expands the attack surface. Retrieved web pages and user documents are both untrusted input and may carry injected instructions. Countermeasures include explicitly marking external content as data rather than instructions, isolating tool return values, and applying secondary confirmation and whitelists to high-risk actions such as writing files or making external requests. Also encrypt data in transit and at rest, manage and rotate keys through a key management service, keep audit trails of calls, and mask personal information and sensitive fields before storing them.
8. Summary
Search and file reading move the API from “able to talk” to “able to get things done,” but the real engineering effort concentrates in four places: retrieval quality, context budget, observable metering, and security boundaries. Make the input, output, rounds, and tool overhead of every call attributable, and cost stays controllable, just as that bill of less than a tenth of a cent looks accidental but is actually the result of good metering habits. When deploying on Baidu AI Cloud, you can build a complete integration chain on general capabilities such as object storage, message queues, container platforms, logging services, and monitoring alerts.
