Sub topic 10
Managing Token Cost and Latency
Assume you understand prompts, model APIs, and basic production monitoring. This chapter focuses on applications that call a pretrained large language model rather than training and serving a model yourself.
Every LLM request has two main operational costs: token cost and latency. A token is a small piece of text used by the model. Providers usually charge separately for input tokens and output tokens. Latency is the time between sending a request and receiving its response.
Where the cost comes from
The input includes the system instructions, user message, conversation history, retrieved documents, and tool results. The output includes the model's generated answer. A simple estimate is:
request cost =
(input tokens × input price)
+ (output tokens × output price)Long context can dominate the bill even when the answer is short. Repeating the same instructions on every request also increases cost. Retrieval-augmented generation can make this worse when it inserts many irrelevant document chunks.
| Cost or latency source | Typical control |
|---|---|
| Long conversation history | Summarize or truncate old turns |
| Many retrieved chunks | Retrieve fewer, more relevant chunks |
| Large output | Set an output-token limit |
| Slow model | Use a smaller model for simple tasks |
| Repeated identical requests | Cache safe, reusable results |
Measure before optimizing
Record input tokens, output tokens, model identifier, request status, and latency for every call. Measure at least the median and high percentiles, such as p95. An average can hide a small group of very slow requests.
Separate time to first token from time to completion when the provider exposes both. Streaming improves perceived responsiveness because users see partial output sooner, but it does not necessarily reduce the total generation time or token cost.
Control the input and output
Use a token budget for each request. Keep only the context needed for the current decision. For retrieved documents, rank chunks by relevance and enforce a maximum context size. For conversations, summarize older turns while preserving facts that the application still needs.
Set a maximum output length. A shorter answer can reduce both cost and completion latency, but an overly small limit can cause incomplete results and retries. Choose the limit from evaluation data rather than guessing.
from dataclasses import dataclass
@dataclass
class Budget:
max_input_tokens: int
max_output_tokens: int
def prepare_request(system_text, user_text, retrieved_chunks, budget):
# This approximation is for budgeting only. Use the provider tokenizer in production.
def estimate_tokens(text):
return max(1, len(text) // 4)
context = []
input_tokens = estimate_tokens(system_text) + estimate_tokens(user_text)
for chunk in retrieved_chunks:
chunk_tokens = estimate_tokens(chunk)
if input_tokens + chunk_tokens > budget.max_input_tokens:
break
context.append(chunk)
input_tokens += chunk_tokens
return {
"system": system_text,
"user": user_text,
"context": context,
"max_output_tokens": budget.max_output_tokens,
"estimated_input_tokens": input_tokens,
}
request = prepare_request(
"Answer using the supplied evidence.",
"What is the refund policy?",
["Short policy section.", "Unrelated product description."],
Budget(max_input_tokens=30, max_output_tokens=80),
)
print(request)Reduce latency deliberately
Choose the smallest model that meets the quality target. Route simple classification or extraction tasks to a cheaper, faster model and reserve a larger model for difficult cases. Cache deterministic operations such as embeddings, retrieved results, or approved answers. Batch independent requests when the API supports batching.
Retries need limits. A retry can double cost and make an outage worse. Use exponential backoff, a maximum attempt count, and a request deadline. Track timeout and retry rates separately from ordinary errors.
Exercise
A request has a long chat history, ten retrieved chunks, and a generous output limit. Name two changes that can reduce cost and one measurement needed to confirm the changes did not harm the application.
Show answer
Summarize old chat turns and keep only the most relevant retrieved chunks. Also reduce the output limit if evaluation shows answers remain complete. Compare input and output token usage, latency, and quality scores before and after the change.