Sub topic 14
Cost, latency, and token impact
This chapter assumes you can call a responses-style API, read JSON response bodies, and have used basic function calling. It covers what built-in tools add to your bill and your response time, and how to measure and limit both.
Why built-in tools change the cost model
With a plain model call, you pay for input tokens and output tokens, and latency is mostly generation time. A built-in tool adds three more costs:
- Per-call fees. Providers often charge a fee for each search call, each code container session, or each vector store query, and for vector store storage. These fees are separate from token charges.
- Extra tokens. Search results, retrieved chunks, and code output are inserted into the model's context. You pay for them as input tokens, and the model may then write a longer answer.
- Extra time. The provider runs the tool inside one request. Your call waits for every search, retrieval, or code run, and for the model passes between them.
Prices and limits change often. Check the provider's current pricing page instead of hard-coding numbers into your estimates.
Where the time goes
A single request that uses a tool is several steps in a row. You only see the final result, but each step takes time.
Each tool has its own typical delay:
| Tool | Main latency sources | Main token impact |
|---|---|---|
| Web search | One or more searches, page content processing | Search result text added to input |
| Code execution | Container start, code run time, repeated write-run-fix cycles | Code and output text in context |
| File search | Query embedding and vector lookup | Retrieved chunks added to input |
A request can loop. If the model searches, reads the results, and decides to search again, the delay and the cost both grow. Code execution loops the same way when the code fails and the model rewrites it.
Reading token usage
Start with measurement. Every response includes a usage object. Print it after each request while you tune.
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-4.1",
tools=[{"type": "web_search"}],
input="What are the most recent stable releases of Python?",
)
usage = response.usage
print("input tokens:", usage.input_tokens)
print("output tokens:", usage.output_tokens)
print("total tokens:", usage.total_tokens)
calls = [item for item in response.output if item.type == "web_search_call"]
print("search calls:", len(calls))Compare the same question with and without the tool. The difference in input tokens is the context the tool added. The count of web_search_call items tells you how many per-call fees apply. Fee billing is not shown in usage, so multiply the call count by the current price yourself.
For Anthropic, the response usage field reports token counts, and it includes a server tool use count for web search requests. Read the field names in the current SDK, since they differ from the OpenAI ones.
Limiting web search cost
Search is the easiest tool to run away. One question can trigger several searches, and each result set enlarges the context.
Anthropic's web search tool has a max_uses setting. Once the limit is reached, the model cannot search again within that request.
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=[
{
"type": "web_search_20250305",
"name": "web_search",
"max_uses": 2,
}
],
messages=[
{"role": "user", "content": "What are the latest developments in solid-state batteries?"}
],
)
print(message.usage)
for block in message.content:
if block.type == "text":
print(block.text)Other ways to cut cost, whichever provider you use:
- Tell the model in its instructions to search only when the question needs current information.
- Use domain filters, covered in an earlier chapter, to keep results short and relevant.
- Set a low
max_tokensor output limit so the answer cannot grow without bound. - Choose a smaller model when the task is only "search and summarize."
Limiting file search cost
File search has two cost areas: indexing and querying.
Indexing happens once per document. Uploading a file to a vector store triggers parsing, chunking, and embedding, and the store usually bills for storage by size and time. Delete stores you no longer use, and do not re-upload unchanged files.
Querying happens on every request. Retrieved chunks go into the prompt, so the number of chunks controls input tokens. The max_num_results setting is the main lever.
response = client.responses.create(
model="gpt-4.1",
tools=[
{
"type": "file_search",
"vector_store_ids": ["vs_your_store_id"],
"max_num_results": 2,
}
],
input="How many vacation days do new employees get?",
)
print(response.usage.input_tokens)
print(response.output_text)Replace vs_your_store_id with the ID returned when you created the store. Lower max_num_results reduces tokens and latency, but it can drop the chunk that holds the answer. Test with real questions. If answers get worse, raise the number by one and measure again.
Limiting code execution cost
Code execution bills for container time or sessions, plus the tokens for the code and its output. Ways to control it:
- Reuse a container across related requests when the provider allows it, instead of starting a new one each time. Check the container's lifetime, since idle containers expire.
- Instruct the model to print short results. A script that prints a 10,000-row table sends all of it back as tokens.
- Ask for computed answers, not data dumps. "Report the mean and the top 5 rows" costs much less than "show the data."
- Use code execution only for work that needs it. Simple arithmetic that a model gets right does not need a container.
Prompt caching and repeated context
Tool results land in the context, and the context grows across a conversation. If you send the full history on each turn, you pay for old search results every time. Options:
- Keep only the final answer text from earlier turns, and drop the raw tool output items, if your use case does not need them.
- Use the provider's prompt caching for large, stable prefixes such as long instructions. Caching helps only when the prefix is identical between requests.
- Summarize long conversations periodically.
Be careful with the first option. Some providers require tool-related items to be passed back in a particular form when you continue a conversation. Read the provider's guidance before removing items.
Setting a budget in your own code
Providers cap tool use per request, but you must cap total spend. A simple guard logs usage per request and refuses new work past a limit.
class Budget:
def __init__(self, max_tokens, max_search_calls):
self.max_tokens = max_tokens
self.max_search_calls = max_search_calls
self.tokens = 0
self.search_calls = 0
def record(self, response):
self.tokens += response.usage.total_tokens
self.search_calls += sum(
1 for item in response.output if item.type == "web_search_call"
)
def exhausted(self):
return (
self.tokens >= self.max_tokens
or self.search_calls >= self.max_search_calls
)
budget = Budget(max_tokens=50_000, max_search_calls=20)
for question in ["Latest Python release?", "Latest Node.js LTS?"]:
if budget.exhausted():
print("Budget used up; stopping.")
break
response = client.responses.create(
model="gpt-4.1",
tools=[{"type": "web_search"}],
input=question,
)
budget.record(response)
print(response.output_text)Common errors
- Assuming the tool is free beyond tokens. Per-call and storage fees often exceed the token cost for light requests.
- Measuring only the final text. The answer may be short while the input held thousands of tokens of search results.
- Testing latency once. Tool latency varies a lot. Measure many requests and look at the slow ones, not only the average.
- Setting limits too low. A cap of one search or one chunk can produce confident but wrong answers. Lower limits in steps and check quality each time.
- Keeping idle resources. Old vector stores and containers can keep billing or hold data. Clean them up.
Streaming for perceived latency
You cannot make a search faster, but you can make the wait feel shorter. Streaming returns events as they happen. You can show "Searching..." when a search call begins and start printing text as soon as the model writes it. Total time stays the same, and the user sees progress sooner.
Exercise
A request with web search returns a two-sentence answer, yet the input token count is 12,000. What most likely explains it, and which two settings could you change to reduce it?
Show answer
The search results were inserted into the model's context and counted as input tokens, so a short answer can still follow a large input. You can reduce it by limiting how many searches run (for example max_uses on Anthropic) and by narrowing results with domain filters. Instructing the model to search only when needed also helps.
Exercise
Your file search answers are fast but sometimes miss the right passage. You had set max_num_results to 1. What should you try, and what cost does it carry?
Show answer
Raise max_num_results to 2 or 3 and test on real questions. More chunks raise the chance that the right passage is included, but they add input tokens and some latency to every request.