Sub topic 3
Budget Retrieved Context and Downstream Controls
Assume you can call an LLM API, count tokens, and run basic Python. The goal is to reduce cost and latency while preserving answer quality.
Budget retrieved context
Retrieval adds documents to the prompt. More retrieved text usually increases input cost and prefill latency. It can also distract the model.
Set a context budget before retrieval:
- Retrieve a moderate number of candidates, such as 20.
- Rerank them for relevance.
- Send only the best results that fit a token limit.
- Remove duplicate or overlapping passages.
- Keep metadata short.
- Measure answer quality as the budget changes.
A budget should apply to the complete prompt, not only the document text. Reserve space for instructions and the model's response.
Cache full responses
An exact-match response cache stores the result for a repeated request. Key the cache by every value that affects the answer, including the model, messages, tool versions, and relevant settings.
import hashlib
import json
cache = {}
def cached_call(model, messages, call_fn):
payload = json.dumps(
{"model": model, "messages": messages},
sort_keys=True,
)
key = hashlib.sha256(payload.encode()).hexdigest()
if key not in cache:
cache[key] = call_fn(model, messages)
return cache[key]Use expiration or versioned keys when source data changes. Do not cache responses containing user-specific or sensitive data in a shared cache.
Batch non-urgent work
Batch summarization, indexing, and evaluation jobs when users do not need immediate results. Batch APIs often reduce price, but they add waiting time. Keep interactive traffic separate from batch traffic.
Run requests in parallel safely
Parallel requests reduce wall-clock time for independent work. Bound concurrency with a semaphore. Retry temporary failures with exponential backoff and jitter. Retrying every error can duplicate side effects, so make operations idempotent.
Route requests and cascade between models
Use a quality evaluation set to compare models on real tasks. Route simple requests to a smaller model. Escalate only when confidence checks or validation reject the first answer.
Set budgets and monitor in production
Track input tokens, output tokens, cost, cache hit rate, time to first token, total latency, errors, retries, and quality scores. Set limits per request, user, and service. Alert on sudden cost, latency, or error-rate changes.
Use serving-side techniques
For self-hosted models, measure batching, continuous batching, quantization, GPU utilization, and key-value cache memory. Quantization can reduce memory and improve throughput, but test whether it harms evaluation quality. Continuous batching improves utilization when requests have different lengths.
Exercise
Why should a retrieval budget include prompt instructions and response space?
Show answer
Because the full context window and input cost include all prompt tokens, and leaving no response space can truncate the answer.