Sub topic 2
Pick the Smallest Model That Meets the Bar
Assume you know basic Python, can call an LLM API, and understand prompts, JSON, and settings such as temperature. Optimize cost only after measuring quality and latency.
Choose by evaluation, not reputation
Create a small evaluation set of real tasks with expected properties, such as factual accuracy, valid JSON, or correct tool selection. Run each candidate model on the same set. Select the cheapest model that passes your quality threshold.
| Model choice | Use when |
|---|---|
| Smaller, cheaper model | Routine tasks pass the evaluation set |
| Larger, slower model | The smaller model fails important cases |
Trim the prompt
Remove repeated instructions, unused conversation history, and irrelevant retrieved documents. Keep stable instructions separate from changing user data. Retrieval budgets should limit both the number and size of returned passages.
Limit and shape the output
Set a maximum output-token limit that matches the task. Ask for the required format and length. A concise schema often costs less than a request for an unrestricted explanation.
def prepare_request(question, passages, max_passages=3, max_chars=1200):
context = "\n\n".join(passages[:max_passages])
context = context[:max_chars]
prompt = (
"Answer in JSON with keys: answer and confidence.\n"
f"Context:\n{context}\n\nQuestion: {question}"
)
return {"prompt": prompt, "max_output_tokens": 180}
request = prepare_request("What is caching?", ["Caching stores reusable results."])
print(request)Stream for perceived latency
Total generation time measures completion speed. Time to first token measures how quickly the user sees a response. Streaming sends chunks as they are generated, improving perceived latency even when total time is unchanged. It does not reduce token usage or provider cost.
Reuse stable prompt prefixes
Provider prompt caching can reduce cost and sometimes latency when the beginning of many requests is identical. Put stable system instructions and fixed examples first. Put the user question and changing context afterward. Check the provider's minimum prefix length, cache lifetime, and billing rules before relying on savings.
Exercise
Why can streaming improve user experience without reducing cost?
Show answer
Streaming lowers time to first visible output, but the model still generates the same tokens and is billed according to the provider's pricing rules.