Sub topic 14
Managing cost and latency
This chapter assumes you can call an LLM API, read JSON, and write basic Python. It also assumes you have followed the earlier chapters on text extraction, schemas, prompts and validation. Here the question is how much a pipeline costs per document and how long it takes. You also learn which changes reduce either one without hurting accuracy.
Where the cost comes from
Most LLM APIs bill by tokens. A token is a chunk of text, roughly three to four characters of English. You pay for input tokens (your prompt plus the document) and output tokens (the model's reply). Output tokens usually cost several times more than input tokens, and they are generated one at a time, so they also dominate latency.
For document extraction, the main cost drivers are:
- Document length. A 40-page contract sent in full means tens of thousands of input tokens per call.
- Page images. A vision-capable model charges for each image, and an image often costs as much as one to several thousand text tokens.
- Retries. Each repair attempt re-sends the whole prompt plus the error message.
- Chunking. Splitting a long document into pieces repeats your instructions and schema in every call.
- Model size. Larger models cost more per token and respond more slowly.
Check your provider's current price list. Prices and limits change often, so treat any number in this chapter as an example.
Measure before you optimize
Do not guess which step is expensive. Log the token counts and the elapsed time for every call. Most APIs return token usage in the response object. The field names differ by provider, so adapt the wrapper below.
import time
# Example prices in dollars per million tokens. Replace with your provider's values.
PRICE_IN = 3.00
PRICE_OUT = 15.00
def timed_call(call_llm_with_usage, prompt):
"""call_llm_with_usage(prompt) -> (text, input_tokens, output_tokens)."""
start = time.perf_counter()
text, tokens_in, tokens_out = call_llm_with_usage(prompt)
seconds = time.perf_counter() - start
cost = (tokens_in * PRICE_IN + tokens_out * PRICE_OUT) / 1_000_000
return text, {"seconds": seconds, "in": tokens_in, "out": tokens_out, "cost": cost}Store these records per document and per step. After a few hundred documents, compute the median and the 95th percentile (p95) for both cost and latency. The p95 matters because a few long or messy documents often cause most of the spend and most of the slow responses.
Reduce the input
Input is the part you control most directly.
Send text instead of images when you can
For a native-text PDF, extracted text is far cheaper than page images and usually just as accurate. Use images only for scanned pages, or for pages where layout or tables are lost in text extraction. Make this choice per page, not per file. A mixed document may need images for two pages out of thirty.
Remove what the model does not need
Page headers, footers, repeated disclaimers and blank pages add tokens without adding data. Strip them before the call. If you know the fields you need appear only on the first and last pages of an invoice, send only those pages. Do this only after you check on labeled data that accuracy stays the same.
Select pages before extracting
A cheap filter can choose relevant pages. Keyword matching, a regular expression, or a small model that classifies each page as relevant or not can all work. This is the same idea as chunking, applied in reverse: instead of reading everything and merging, you skip what cannot contain the answer.
import re
def relevant_pages(pages, patterns):
"""Return (index, text) for pages that match any of the regex patterns."""
compiled = [re.compile(p, re.IGNORECASE) for p in patterns]
return [(i, t) for i, t in enumerate(pages) if any(c.search(t) for c in compiled)]
pages = ["Cover page", "Invoice No. 1042 Total due: 310.00 EUR", "Terms and conditions"]
print(relevant_pages(pages, [r"invoice no", r"total due"]))The risk is a recall problem: a page that holds a needed value but does not match your pattern is silently dropped. Measure field accuracy before and after adding the filter.
Reduce the output
Ask for only the fields you need, as compact JSON. Avoid asking the model to explain its answer or to copy long passages of the document into the result. If you want evidence for each value, ask for a short quote or a page number, not a paragraph. Set a maximum output token limit slightly above the largest valid answer. This caps the cost of a runaway response and shortens the wait.
Reuse repeated prompt content
Every call in a batch starts with the same instructions and schema. Some providers offer prompt caching, which charges less for a repeated prefix. To benefit, put the fixed material first (instructions, schema, examples) and the document text last. If the document comes first, the prefix differs on every call and the cache never hits. Caching rules, minimum prefix sizes and discounts vary by provider, so read the documentation.
Choose the model by difficulty
A large model is not needed for every document. A common pattern is a cascade:
- Run a small, cheap model first.
- Validate the output and check grounding.
- If validation fails or a field is ungrounded, run a larger model on that document only.
This works well when most documents are clean and a minority are hard. It works poorly if the small model often returns plausible but wrong values that pass validation, because those errors never reach the larger model. Measure this on your test set before you trust a cascade.
Cut latency
Cost and latency are related but not the same. A change that lowers one can raise the other.
Run independent work in parallel
Chunks of a long document, and separate documents in a batch, do not depend on each other. Send them concurrently with a bounded worker pool. Keep the pool size within your provider's rate limits, or you will receive rate-limit errors and spend the saved time on retries.
from concurrent.futures import ThreadPoolExecutor
def extract_many(documents, extract_one, max_workers=5):
"""Run extract_one(doc) for every document, keeping input order."""
with ThreadPoolExecutor(max_workers=max_workers) as pool:
return list(pool.map(extract_one, documents))Parallel calls do not lower the total cost. They lower the wall-clock time only. A document whose chunks run in parallel still waits for its slowest chunk.
Use batch APIs for work that can wait
Some providers offer an asynchronous batch interface that returns results within hours at a reduced price. If nobody is waiting on the result, such as a nightly import of archived invoices, this is often the cheapest option. It is a poor fit for an interactive upload form.
Watch retries
A retry loop that allows three attempts can triple the cost and latency of a bad document. Keep the attempt limit low. Pass the validation error back so the second attempt has a real chance, and stop early when the same error repeats. Track the retry rate: a rate above a few percent suggests the prompt or schema needs fixing, not more retries.
Trade-offs at a glance
| Technique | Lowers cost | Lowers latency | Main risk |
|---|---|---|---|
| Text instead of images | Yes | Yes | Lost layout or tables |
| Page selection | Yes | Yes | Dropped relevant pages |
| Short output, token cap | Yes | Yes | Truncated JSON |
| Prompt caching | Yes | Slightly | Needs a stable prefix |
| Model cascade | Yes | Mixed | Confident wrong answers from the small model |
| Parallel calls | No | Yes | Rate limits |
| Batch API | Yes | No (slower) | Results arrive late |
Common errors
- Optimizing without measurements. You may shrink a step that was only 5% of the total.
- Skipping the accuracy check. Every saving above can reduce accuracy. Re-run your labeled test set after each change and compare field accuracy.
- Counting only the happy path. Include retries, failed documents and human review time in your cost per document.
- Setting the output cap too low. A cut-off JSON object fails validation, triggers a retry, and costs more than it saved.
- Ignoring rate limits. Aggressive parallelism leads to errors and backoff delays.
Exercise
Your pipeline processes 10,000 scanned invoices each night, and results are needed by the next morning. Each invoice currently goes to a large vision model in a live call, and the bill is high. Name three changes you would test, and say how you would confirm that each one does not hurt accuracy.
Show answer
Three options: (1) Use a batch API, since results are not needed immediately and batch pricing is lower. (2) Run OCR first and send text to the model for invoices where OCR quality is good, keeping images only for pages where text or tables come out badly. (3) Use a cascade, with a small model first and a larger model only when validation or grounding checks fail. To confirm accuracy, keep a labeled test set of invoices, run the old and new setups on it, and compare per-field accuracy with the field_accuracy function. Accept a change only if accuracy stays within a tolerance you set in advance. Also compare retry rate and the share of documents sent to human review.
Exercise
Why should the instructions and schema come before the document text in the prompt when you use prompt caching?
Show answer
Caching works on a repeated prefix. Instructions and schema are identical across calls, so placing them first lets the provider reuse that prefix. If the document came first, every prompt would begin differently and the cache would not match.