Sub topic 14
Managing cost and latency
This chapter assumes you can call an LLM API, have read the earlier chapters on text extraction and prompting, and know that providers bill by tokens. A token is a small piece of text, roughly three-quarters of a word in English. Cost and latency both grow with the number of tokens you send and receive, so most savings come from sending less.
Where the cost comes from
Each call costs input tokens × input price + output tokens × output price. In document extraction the input dominates: a 20-page contract can be tens of thousands of tokens, while the JSON answer is a few hundred. Page images are also billed as input tokens, and a full page image often costs more than that page's extracted text.
| Lever | Effect on cost | Effect on latency | Risk |
|---|---|---|---|
| Send text instead of images | Lower | Lower | Loses layout on complex pages |
| Trim boilerplate pages | Lower | Lower | May drop a needed field |
| Use a smaller model first | Lower | Lower | Lower accuracy on hard cases |
| Cache repeated prompt prefix | Lower | Lower | Needs a stable prefix |
| Parallel requests | Same | Lower total time | Rate limits |
| Fewer retries | Lower | Lower | Less repair coverage |
Send less input
Decide per page whether the page is worth sending. Cover sheets, terms and conditions, and blank pages rarely hold fields you need.
from pypdf import PdfReader
KEYWORDS = ("invoice", "total", "amount due", "bill to")
def relevant_pages(path, min_chars=50):
reader = PdfReader(path)
kept = []
for i, page in enumerate(reader.pages):
text = page.extract_text() or ""
if len(text.strip()) < min_chars:
continue
if any(k in text.lower() for k in KEYWORDS):
kept.append((i, text))
return keptKeep the page numbers. If a field comes back null, you can then re-run on the skipped pages instead of silently losing data.
Route by difficulty
Most documents in a batch are easy. Try a small, cheap model first. Escalate to a larger model only when validation fails or a field is not grounded in the source.
def extract_with_fallback(text, call_small, call_large):
for call_llm in (call_small, call_large):
try:
invoice = extract_invoice(text, call_llm, max_attempts=2)
except ValueError:
continue
if is_grounded(invoice.vendor, text) and is_grounded(invoice.invoice_number, text):
return invoice
return NoneA None result goes to human review. This reuses extract_invoice and is_grounded from earlier chapters. Measure the escalation rate. If 80% of documents escalate, the small model only adds cost.
Reduce latency
- Run documents in parallel. Calls are mostly network waiting, so a thread pool with 4 to 8 workers can cut batch time several times over. Stay below your provider's rate limit and back off on rate-limit errors.
- Keep the prompt prefix stable. Put the instructions and schema first and the document last. Providers that support prompt caching can reuse a repeated prefix at a lower price and with a faster start.
- Cap the output. Ask for only the fields you need and set a maximum output length. Long free-text explanations add seconds.
- Use a batch API for offline work. Many providers offer discounted asynchronous batches that finish within hours. This suits back-office jobs where nobody waits for the answer.
Common mistakes
- Optimizing before measuring. Log input tokens, output tokens, retries, and seconds per document, then fix the largest item.
- Counting only the price per call. A cheap model that triggers three retries and a human review can cost more than one call to a stronger model.
- Skipping accuracy checks after a change. Rerun your labeled test set whenever you switch models or trim pages.
Exercise
Your batch of 1,000 invoices uses a small model first and escalates failures to a large model. 30% escalate. The small model costs 1 unit per call and the large model costs 10 units per call. What is the average cost per document, and is it cheaper than using the large model for everything?
Show answer
Every document costs 1 unit for the small call, and 30% add 10 units: 1 + 0.3 × 10 = 4 units per document. Using the large model alone costs 10 units, so the fallback design is cheaper. It stops being cheaper when the escalation rate reaches 90%, since 1 + 0.9 × 10 = 10.