Sub topic 3
Managing Token Cost and Latency
This chapter assumes you can call an LLM API from Python, that you know what a prompt and a response are, and that you already log requests in production.
Managing token cost and latency
Providers bill by token. A token is a small chunk of text, roughly three-quarters of an English word. Input tokens and output tokens usually have different prices, and output is often more expensive. Latency also grows with output length, so shorter answers are usually cheaper and faster.
PRICE_PER_1K = {"input": 0.003, "output": 0.015}
def estimate_cost(input_tokens: int, output_tokens: int) -> float:
input_cost = (input_tokens / 1000) * PRICE_PER_1K["input"]
output_cost = (output_tokens / 1000) * PRICE_PER_1K["output"]
return input_cost + output_cost
print(round(estimate_cost(1200, 300), 6))Guardrails, data handling, and prompt injection
Prompt injection is text in user input or retrieved documents that tries to override your instructions. Treat all model input as untrusted. Limit which tools the model can call, remove sensitive data before it reaches the model, and never place secrets in prompts. Validate model output before your code acts on it.
Operating tool-using and agentic workflows
When a model calls tools, each call can change external state. Cap the number of steps in a run, require human confirmation for writes and deletes, and log every tool call with its arguments and result.
Where fine-tuning fits, and where it does not
Fine-tuning helps when prompting and retrieval cannot produce a consistent style or output format, and when a tested evaluation set shows the gain. Fine-tuning does not add reliable facts. Try prompt and retrieval changes first.
Putting it together: the LLMOps loop
Version your prompts and settings, evaluate them on a golden set, release them behind a gate, trace production calls, and watch cost, latency, and safety. Feed the failures back into the next prompt change.
Exercise
A prompt change raises output from 300 to 900 tokens per request, with the same input size. Using the price table above, how much more does each request cost, and what else changes?
Show answer
Output cost goes from 0.0045 to 0.0135 dollars, an increase of 0.009 dollars per request. Latency also rises, because the model generates more tokens. Check both in your traces before release.