Courses / AI Engineering: LLMs, RAG and Agentic System Design / Chapter 4
Module 2 · Generative AI foundations · Chapter 4 of 24
Working with model APIs
Builds on Generative AI and how LLMs work and Prompt engineering. Next up: Embeddings and vector databases.
Part 1 · The request and the response
What a chat request carries
Many hosted and local model servers accept the same chat request shape, so one client library and one set of habits cover OpenAI's service, Ollama, vLLM and others. This chapter follows that shape from the request to the bill.
The shape is the Chat Completions API: an HTTP POST with a JSON body, and a JSON reply. The openai Python library is a client for it, and it works against any server that speaks it if you change the base URL.
| Field | Direction | Meaning |
|---|---|---|
model | request | Name of the model to run |
messages | request | List of {role, content} objects: the whole conversation |
max_tokens | request | Upper limit on generated tokens |
choices[0].message | response | The assistant's reply |
finish_reason | response | Why generation stopped |
usage | response | Token counts for the call |
finish_reason is stop when the model reached a natural end or one of your stop sequences, and length when it hit max_tokens or the context limit. Other values exist, such as tool_calls when the model wants a function run. Always read it. A reply cut off by length looks like a complete answer until someone notices the missing end.
Roles, content and addresses
Each message has a role and content. The roles are system for standing instructions, user for the person's input, and assistant for earlier replies. A fourth role, tool, carries the result of a function call and appears once a model is given functions to call. The server renders all of them into one token sequence with the model's chat template, as the fundamentals chapter described.
content is usually a string. It can also be a list of parts, each with a type, which is how an image goes into a request: a part of type text and a part of type image_url whose URL is a base64 data URL. The image call in the fundamentals chapter used exactly that. Ollama's compatibility page lists base64 images and arrays of content parts as supported, and marks image URLs that point to a web address as unsupported.
Three settings point the client at a server: the base URL, an API key and a model name. The shared helper reads them from the environment variables LLM_BASE_URL, LLM_API_KEY and LLM_MODEL. A local server ignores the key, but the library insists on a non-empty value, so the helper sends ollama. A hosted service rejects a wrong key with a 401 error. Keep real keys in environment variables or a secrets store, never in source files or prompts.
Model names are not stable identifiers everywhere. A name can be an alias that moves to a newer model, or a dated snapshot that never changes. Record the exact name you tested against, and treat a change of name as a change of behaviour that needs a test run.
One call, two ways
The first script is the raw request with the httpx library: no SDK, so every field is visible. It prints the reply as JSON, minus two bookkeeping fields.
import json import httpx body = { "model": "gemma4:12b", "messages": [{"role": "user", "content": "Reply with exactly one word: ready"}], "max_tokens": 20, "reasoning_effort": "none", } r = httpx.post("http://127.0.0.1:11500/v1/chat/completions", json=body, timeout=60) print(r.status_code) data = r.json() data.pop("system_fingerprint", None) data["usage"].pop("prompt_tokens_details", None) print(json.dumps(data, ensure_ascii=False, indent=2))
200 { "id": "chatcmpl-308", "object": "chat.completion", "created": 1795354446, "model": "gemma4:12b", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "ready" }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 20, "completion_tokens": 2, "total_tokens": 22 } }
The reply is one choice with a message and a finish_reason of stop. usage shows 20 prompt tokens for a one-line request, because the chat template adds tokens around the message, and 2 completion tokens for a one-word answer. Token counts can be higher than the word count of what you see, so budget with the usage numbers and not with word counts.
The second script makes the same call through the openai library, using the shared helper. The SDK turns the JSON into typed objects and adds retries, timeouts and error classes, which later lessons use.
from llm import chat ask = [{"role": "user", "content": "Reply with exactly one word: ready"}] msg, r = chat(ask, max_tokens=20) print(type(r).__name__, r.id[:12], r.model) print(msg.role, repr(msg.content)) print(r.choices[0].finish_reason, r.usage.total_tokens)
ChatCompletion chatcmpl-54 gemma4:12b assistant 'ready' stop 22
The id differs on every call.
Other providers have their own shapes. OpenAI's newer Responses API takes an input and returns typed output items instead of choices. Google's Gemini documentation describes an Interactions API, where, for example, function-call arguments arrive as structured key-value data (a dictionary in Python) rather than as a JSON string. The ideas in this chapter carry over: an input, parameters, a stream of output, and usage. Only the field names change, and a thin wrapper around your provider keeps those names out of the rest of your code.
Part 2 · Parameters that matter
Controls on sampling and length
The request accepts parameters that change how the next token is chosen and when generation ends. These are the ones that matter day to day, all accepted by the OpenAI-compatible endpoint of Ollama according to its documentation.
| Parameter | Effect | Typical use |
|---|---|---|
temperature | Divides logits before softmax: lower is more repeatable, higher is more varied | 0 to 0.3 for extraction, higher for brainstorming |
top_p | Keep only the most probable tokens that add up to p | Change this or temperature, rarely both |
max_tokens | Hard cap on generated tokens | Always set it; it bounds cost and latency |
stop | Strings that end generation when produced | Cut a reply at a marker |
frequency_penalty, presence_penalty | Discourage repeated tokens or topics | Reduce loops in long text |
seed | Seeds the random draw | Repeatable runs in tests |
Temperature and top-p were explained in the fundamentals chapter. Change one of them at a time, not both, because both reshape the same distribution and you could not tell which one caused a difference.
max_tokens deserves care. It counts every generated token, including reasoning tokens on a thinking model, so a small cap can leave the visible answer empty. Set it to a value that covers the longest answer you accept and check finish_reason for length.
Choosing values
Defaults are a reasonable start, and most calls need only two settings changed: a lower temperature for extraction and classification, where you want the same answer each time, and a max_tokens that matches the answer you expect.
| Task | Setting to change | Why |
|---|---|---|
| Extract fields from text | temperature near 0 | You want the same value on every run |
| Draft several taglines | default or higher temperature | Variety is the point |
| One-line answer | small max_tokens, a stop sequence | Bounds cost and cuts chatter |
| Long reply that repeats itself | frequency_penalty above 0 | Discourages repeated tokens |
| Test that must repeat | seed, temperature 0 | Repeatable on a fixed server |
Not every parameter exists everywhere. Ollama's compatibility page lists temperature, top_p, max_tokens, stop, seed and the two penalties as supported. n, which asks for several alternative replies in one call, logit_bias and tool_choice are marked unsupported, so the self-consistency loop of the prompting chapter calls the model several times instead. When you move to another provider, read its parameter list before assuming a name carries over: output caps and sampling settings are named and restricted differently from one provider and model to the next.
Change one parameter at a time and compare on several inputs. A single run at a new setting is an anecdote.
What a seed promises
A seed makes the random draw repeatable. In the script, the same prompt runs three times at temperature 1 with no seed, three times with seed 42, once with seed 7, then three times at a low temperature with a restricted top_p, and finally once with a stop sequence.
from llm import chat ask = [{"role": "user", "content": "Invent a name for a tea stall. Name only."}] def name(**kw): return chat(ask, max_tokens=12, **kw)[0].content.strip() print("temperature 1.0, no seed:") for _ in range(3): print(" ", name(temperature=1.0)) print("temperature 1.0, seed 42:") for _ in range(3): print(" ", name(temperature=1.0, seed=42)) print("temperature 1.0, seed 7:") print(" ", name(temperature=1.0, seed=7)) print("temperature 0.2, top_p 0.5:") for _ in range(3): print(" ", name(temperature=0.2, top_p=0.5)) print("with stop=[\",\"]:") r = chat([{"role": "user", "content": "Count from 1 to 5 in words."}], stop=[","], max_tokens=30) print(" ", repr(r[0].content), r[1].choices[0].finish_reason)
temperature 1.0, no seed: Steep & Sip Brew & Bloom Steep & Soul temperature 1.0, seed 42: Brew & Bloom Brew & Bloom Brew & Bloom temperature 1.0, seed 7: Steeped Stories temperature 0.2, top_p 0.5: Steep & Sip Steep & Sip Steep & Sip with stop=[","]: 'one' stop
Output from one run; yours will differ.
Without a seed the three answers varied. With seed 42 all three were the same name, and seed 7 gave a different one. With a low temperature and top_p 0.5 the answers were identical without any seed, because the choice was nearly forced. The stop sequence , ended the reply right after one, and finish_reason was stop.
What the seed does not promise: identical output across servers, model versions, hardware or library updates. It worked here on one server in one session. Use it to make tests repeatable on a fixed setup, and compare behaviour with checks on the structure of the reply, not on exact text.
Why should max_tokens always be set?
- It bounds the cost and latency of a call and stops a runaway generation.
- It also counts reasoning tokens on a thinking model.
What did seed 42 change in the run?
Part 3 · Streaming
Why streams exist
A model writes a reply one token at a time. Without streaming the server waits until the last token and sends the reply in one piece, so a user stares at a blank screen for the full generation time. With streaming the server sends each piece as soon as it exists, and the interface can show text immediately.
Two numbers describe a streamed call. Time to first token is how long the user waits before anything appears: it covers network time, any queueing, and the processing of the prompt. Output speed, in tokens per second, is how fast the rest arrives. Streaming does not make the whole reply faster. It changes when the user starts reading.
Streaming uses server-sent events (SSE), a plain HTTP response with content type text/event-stream that stays open. The body is a series of events. Each is a line that starts with data: and holds one JSON chunk, followed by a blank line. The stream ends with the line data: [DONE].
Each chunk has a delta instead of a full message: the new text since the last chunk. The first chunk also carries the role. The chunk that ends generation carries the finish_reason with an empty delta. Your code concatenates the deltas to rebuild the reply.
Reading a stream
The first script reads the raw event stream with httpx and prints each event in short form. It also sets stream_options with include_usage, which asks for one extra chunk at the end that carries token counts.
import json import httpx body = {"model": "gemma4:12b", "stream": True, "max_tokens": 12, "reasoning_effort": "none", "stream_options": {"include_usage": True}, "messages": [{"role": "user", "content": "Count to three."}]} with httpx.stream("POST", "http://127.0.0.1:11500/v1/chat/completions", json=body, timeout=60) as r: print(r.status_code, r.headers["content-type"]) lines = [ln for ln in r.iter_lines() if ln] print(lines[0][:60], "...") for ln in lines: if ln == "data: [DONE]": print(ln) continue chunk = json.loads(ln[len("data: "):]) choice = chunk["choices"][0] if chunk["choices"] else {} print(repr(choice.get("delta", {}).get("content")), choice.get("finish_reason")) if chunk.get("usage"): u = chunk["usage"] print("usage:", u["prompt_tokens"], u["completion_tokens"], "cached:", u["prompt_tokens_details"]["cached_tokens"])
200 text/event-stream data: {"id":"chatcmpl-869","object":"chat.completion.chunk", ... '1' None ',' None ' ' None '2' None ',' None ' ' None '3' None '.' None None stop None None usage: 17 9 cached: 12 data: [DONE]
Output from one run; yours will differ.
The reply arrived as eight content chunks: 1, ,, a space, 2, ,, a space, 3 and .. The next chunk has an empty delta and finish_reason: stop. The one after it has no choices at all and holds usage. Code that reads chunk.choices[0] unguarded fails on that last chunk. The prompt_tokens_details field reports cached_tokens of 12 of the 17 prompt tokens here: the server reused prompt tokens it had processed on a recent call with the same beginning. A later run, after other requests had used the server, printed 0 cached tokens and wrote the numbers as words, so treat the cache as a saving you may get, not one you can count on.
The second script does the same through the SDK and measures time to first token and total time.
import time from llm import client, MODEL PROMPT = "Write three short sentences about the Ganga." start = time.perf_counter() stream = client.chat.completions.create( model=MODEL, max_tokens=150, reasoning_effort="none", stream=True, stream_options={"include_usage": True}, messages=[{"role": "user", "content": PROMPT}], ) first, chunks = None, 0 for chunk in stream: chunks += 1 if chunk.choices: choice = chunk.choices[0] if chunks == 1: delta = choice.delta.model_dump(exclude_none=True) print("first delta:", delta) if choice.delta.content and first is None: first = time.perf_counter() - start if choice.finish_reason: print("finish_reason:", choice.finish_reason, "text:", repr(choice.delta.content)) if chunk.usage: print("last chunk: choices", chunk.choices, "usage", chunk.usage.prompt_tokens, chunk.usage.completion_tokens) total = time.perf_counter() - start print("chunks:", chunks) print(f"time to first token {first:.2f} s, total {total:.2f} s")
Using a stream in an application
A user interface appends each delta as it arrives. Your code often needs the whole text as well, so it keeps a list of the pieces and joins them at the end. Three details need care.
- Guard the empty cases. Some chunks have no text, and the usage chunk has no choices.
- Stop when the user does. Closing the stream ends the request, and the server can stop generating, which saves tokens.
- Expect a broken stream. A connection can drop after some chunks arrived. The library does not retry a stream that has started. Keep the partial text, show it as incomplete, and let the user retry.
The script collects pieces and stops after twelve of them, as a user might who clicks Stop.
from llm import client, MODEL stream = client.chat.completions.create( model=MODEL, max_tokens=200, reasoning_effort="none", stream=True, messages=[{"role": "user", "content": "List five Indian rivers."}], ) parts = [] for chunk in stream: delta = chunk.choices[0].delta.content if chunk.choices else None if delta: parts.append(delta) if len(parts) == 12: # stop early, as a user might stream.close() break print(repr("".join(parts))) print("chunks kept:", len(parts))
'Here are five major rivers in India:\n\n1. **' chunks kept: 12
Output from one run; yours will differ.
The text kept is the start of the list, cut mid-reply. Each piece is a token or a few, so counting chunks gives only a rough idea of the length. Use the usage chunk when you need the exact numbers, and note that a stream you close early may not deliver it.
What is time to first token, and what does it include?
- How long the user waits before the first text appears. It includes network time, queueing and prompt processing.
Why does code that reads chunk.choices[0] break on some streams?
- With
include_usagethe last chunk has an emptychoiceslist and carries onlyusage.
Part 4 · Errors, timeouts and retries
What the SDK raises and what it retries
A call can fail in three ways: the server answers with an error status, the network breaks, or the answer takes too long. The openai library turns each into an exception class, read here from the installed version 3.46.0.
| Cause | Exception | Retried by default |
|---|---|---|
| 400 bad request | BadRequestError | No |
| 401 bad key | AuthenticationError | No |
| 403 not allowed | PermissionDeniedError | No |
| 404 unknown model or path | NotFoundError | No |
| 409 conflict | ConflictError | Yes |
| 422 unprocessable | UnprocessableEntityError | No |
| 429 rate limit | RateLimitError | Yes |
| 500 and above | InternalServerError | Yes |
| 408 request timeout | APIStatusError | Yes |
| Connection failure | APIConnectionError | Yes |
Timeouts and what to log
A timeout is a limit on waiting. Without a sensible one, a stalled connection holds a user, a thread and a worker for up to ten minutes. Set timeout= on the client or on a single call, to a value based on what you expect: a short extraction can have 10 or 20 seconds, a long generation more. For a stream, think about two waits: the time to the first chunk and the gap between chunks.
Every retry adds waiting. With the default two retries and a timeout of 30 seconds, one call can occupy a user for about 90 seconds plus the backoff waits. Decide the longest total wait the user will accept, then choose the timeout and the retry count to fit under it.
Hosted services usually limit both requests per minute and tokens per minute, and some add daily caps. A 429 response says that you hit one of them. Retrying with backoff helps for short bursts. For a sustained overload, reduce concurrency or add a queue on your side, because retries add load.
Log, for every call: the model name, the prompt version, the status or exception class, the number of attempts, the latency, and the usage counts. The SDK sends the retry number in the x-stainless-retry-count header, which the stub server in the next page records. Without these fields, you cannot tell a slow model from a flaky network or a rate limit.
Watching the retries
To see the behaviour without hitting a real rate limit, a small stub server listens on port 56000 and answers with a list of statuses you give it, one per request, while recording the retry count header the SDK sends and the time of each request. A status of 0 means answer after 1.5 seconds.
import json, threading, time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer PORT = 56000 OK = {"id": "stub-1", "object": "chat.completion", "created": 0, "model": "stub", "usage": {"prompt_tokens": 3, "total_tokens": 4, "completion_tokens": 1}, "choices": [{"index": 0, "finish_reason": "stop", "message": { "role": "assistant", "content": "pong"}}]}
class Stub(BaseHTTPRequestHandler): statuses = [] # one status per request, in order; 0 = answer late log = [] def do_POST(self): self.rfile.read(int(self.headers["content-length"])) status = self.statuses.pop(0) retry = self.headers.get("x-stainless-retry-count") self.log.append((status, retry, time.perf_counter())) if status == 0: time.sleep(1.5) status = 200 err = {"error": {"message": "stub error"}} body = json.dumps(OK if status == 200 else err).encode() try: self.send_response(status) self.send_header("content-length", str(len(body))) self.end_headers() self.wfile.write(body) except OSError: pass # the client gave up before the answer def log_message(self, *args): pass def start(): server = ThreadingHTTPServer(("127.0.0.1", PORT), Stub) threading.Thread(target=server.serve_forever, daemon=True).start() return server
The test client sends the same call under six scripts of statuses and prints how many attempts were made and the gaps between them.
import time from openai import OpenAI, APITimeoutError from openai import RateLimitError, BadRequestError from m4_stub import PORT, Stub, start server = start() client = OpenAI(base_url=f"http://127.0.0.1:{PORT}/v1", api_key="x") ASK = [{"role": "user", "content": "ping"}] def attempt(statuses, **opts): Stub.statuses, Stub.log = list(statuses), [] try: out = client.with_options(**opts).chat.completions.create( model="stub", messages=ASK) result = out.choices[0].message.content except (RateLimitError, BadRequestError, APITimeoutError) as e: result = type(e).__name__ times = [entry[2] for entry in Stub.log] gaps = [round(b - a, 2) for a, b in zip(times, times[1:])] print(statuses, opts or "defaults", "->", result) print(" attempts:", len(Stub.log), "retry counts:", [x[1] for x in Stub.log], "gaps (s):", gaps) attempt([429, 429, 200]) attempt([429, 429, 200], max_retries=1) attempt([400, 200]) attempt([500, 200]) attempt([0, 200], timeout=0.5, max_retries=0) attempt([0, 200], timeout=0.5) server.shutdown()
Part 5 · Structured output
From text to data
Your code needs fields, not prose. There are three ways to get them, in rising order of strength.
- Ask in the prompt. Describe the JSON you want. The model usually complies, and sometimes adds text around it or breaks the syntax.
- JSON mode. The server constrains output to valid JSON. OpenAI's structured outputs guide says that both modes produce valid JSON but only structured outputs ensure the output matches your schema.
- Schema-constrained output. You pass a JSON schema and the server restricts generation to outputs that match it. Ollama accepts a schema through
response_formaton the compatible endpoint or aformatfield on its own API, and recommends also describing the schema in the prompt.
With the openai library you rarely write the schema by hand. You define a Pydantic model, and client.chat.completions.parse turns it into a schema, sends the request, and validates the reply back into an instance of your class.
Even a schema-constrained reply can fail in ways the schema cannot see. The model can pick the wrong value for a field. A refusal may not follow the schema, which the OpenAI guide notes with a separate refusal field. And generation can be cut off by max_tokens halfway through the JSON. Your code must handle each.
Choosing an approach
Use the weakest method that is reliable enough, and validate whatever you use.
| Method | Good for | Watch for |
|---|---|---|
| Describe JSON in the prompt | Quick experiments, providers with no constraint | Extra text, broken syntax |
| JSON mode | Valid JSON is enough | Wrong or missing fields |
| Schema-constrained output | Production extraction | Truncation, refusals, wrong values that fit the schema |
Schemas guarantee shape, not truth. A reply can have the right fields and the wrong content: a urgent flag set to false for a message that says "today". Add checks that know your rules, such as a date that must not be in the past or an order number that must exist in your database. Keep the schema small, with fields the model can fill from the input, and move derived values into your own code.
Keep field names and descriptions meaningful, because they are part of the prompt. A field called urgent with a one-line description of when it is true gives the model more to go on than a field called flag.
Parse, validate and handle truncation
The script defines a Ticket model with three fields and parses one made-up message into it. It then calls again with max_tokens of 8, too small for the JSON, to show what truncation raises.
from typing import Literal from pydantic import BaseModel from openai import LengthFinishReasonError from llm import client, MODEL class Ticket(BaseModel): category: Literal["billing", "delivery", "login", "other"] urgent: bool summary: str text = ("My card was charged twice for order 4471 and I need it " "fixed today.") messages = [{"role": "user", "content": "Extract category, urgent and a summary of at most 10 " "words from this message:\n" + text}] def parse(**kw): return client.chat.completions.parse( model=MODEL, messages=messages, response_format=Ticket, reasoning_effort="none", **kw) r = parse(max_tokens=200) for field, value in r.choices[0].message.parsed: print(field, "=", repr(value)) print(r.choices[0].finish_reason) try: parse(max_tokens=8) except LengthFinishReasonError as e: print("truncated:", type(e).__name__)
category = 'billing' urgent = True summary = 'Double charge on order 4471 needs immediate correction.' stop truncated: LengthFinishReasonError
Output from one run; yours will differ.
The first call returns a Ticket, and finish_reason is stop. category is a Literal of four values, so the schema sent to the server lists them, the server constrains the reply to those four, and Pydantic would reject a fifth in any case. The summary is free text and varies between runs. The second call raised LengthFinishReasonError: the library refuses to parse a reply that stopped on length, because half a JSON document is not data.
Validate and retry
A safe pattern for production is validate and retry. Catch the length error and the validation error, retry with a bigger max_tokens or with the error message appended to the conversation, and cap the number of tries at two or three. After that, return a clear failure to the caller. Retrying a malformed reply is different from the network retries of the last lesson: it spends new tokens each time, so cap it and log it.
The script extracts two integer fields into a Refund model. It starts with a cap of 8 tokens on purpose, doubles the cap after each LengthFinishReasonError, counts a Pydantic ValidationError as a failed try, and gives up after three tries.
from pydantic import BaseModel, ValidationError from openai import LengthFinishReasonError from llm import client, MODEL class Refund(BaseModel): order_id: int amount_rupees: int ask = [{"role": "user", "content": "Extract the order id and the " "amount: please refund 1,250 rupees for order 5520."}] def extract(max_tokens, tries=3): for attempt in range(1, tries + 1): try: r = client.chat.completions.parse( model=MODEL, messages=ask, response_format=Refund, reasoning_effort="none", max_tokens=max_tokens) return r.choices[0].message.parsed, attempt except LengthFinishReasonError: print(f"attempt {attempt}: cut off at {max_tokens} tokens") max_tokens *= 2 except ValidationError as e: n = e.error_count() print(f"attempt {attempt}: {n} invalid fields") return None, tries result, attempts = extract(max_tokens=8) print(result, "after", attempts, "attempts")
attempt 1: cut off at 8 tokens attempt 2: cut off at 16 tokens order_id=5520 amount_rupees=1250 after 3 attempts
Output from one run; yours will differ.
Two tries were cut off, at 8 and 16 tokens, and the third, with 32, returned a valid Refund. The amount arrived as the integer 1250 although the message wrote 1,250, because the schema asks for an integer. In real code the first cap would be set from the longest valid reply you have seen, so that the retry path is rare, and every retry would be logged with its reason.
What does JSON mode guarantee, and what does it not?
- It guarantees syntactically valid JSON. It does not guarantee the JSON matches your schema; schema-constrained output does.
Part 6 · Usage and cost
The tokens you pay for
Hosted models are billed per token, with separate prices for input and output, quoted per million tokens. Output tokens usually cost more than input tokens. They are also the slow part: the prompt is processed in one pass over all its tokens, while each output token needs its own step through the model.
- Input tokens (
prompt_tokens): everything you send, including system message, history, examples and retrieved text. - Output tokens (
completion_tokens): everything the model generates, including reasoning tokens on a thinking model, even though you do not display them. - Cached tokens: some servers reuse the processing of a repeated prompt beginning and report it in
prompt_tokens_details.cached_tokens. Providers price cached input differently, and their terms change, so read the current price page.
On this server the usage object lists only completion_tokens, prompt_tokens, total_tokens and prompt_tokens_details, as the run below prints, so it does not split out reasoning tokens. Providers that do, report them in a details field next to completion_tokens.
Cost per request is a short sum: input tokens times the input price, plus output tokens times the output price, each per million. Because a prompt grows with history and retrieved text, and because retries and samples multiply calls, the average cost per request is worth measuring from real usage instead of guessing.
Budgets and limits
A bill is the sum of calls, so the controls are on calls.
- Cap each call.
max_tokensbounds the output, and checking the size of the prompt before sending bounds the input. - Cap each user and each day. Count tokens from
usageand refuse or queue work beyond a limit. One runaway loop or one very large input should not consume a month of budget. - Watch multipliers. Retries, sampling several answers, and agent loops multiply the number of calls per user action. Measure calls per action, not only tokens per call.
- Alert early. A provider-side budget alert catches what your own code missed.
Prices differ by model and change over time, and services add pricing for cached input and for batch use. Read the current price page of the provider you use before you size anything, and keep the prices in one place in your code with the date you read them.
A monthly estimate from measured usage
The script makes five calls, averages the real token counts, and applies example prices of $0.15 per million input tokens and $0.60 per million output tokens. These are made-up numbers for the sum and not any provider's price list. Replace them with the current prices of the model you use.
from llm import chat PRICE_IN, PRICE_OUT = 0.15, 0.60 # example $ per million tokens question = [{"role": "user", "content": "In two sentences, why is the sky blue?"}] runs = [chat(question, max_tokens=120)[1].usage for _ in range(5)] print("usage fields:") for name in sorted(runs[0].model_dump(exclude_none=True)): print(" ", name) print("completion tokens per run:", [u.completion_tokens for u in runs]) p = sum(u.prompt_tokens for u in runs) / 5 c = sum(u.completion_tokens for u in runs) / 5 cost = (p * PRICE_IN + c * PRICE_OUT) / 1_000_000 print(f"average prompt tokens {p:.0f}, completion tokens {c:.0f}") print(f"cost per request at the example prices: ${cost:.6f}") requests = 200_000 print(f"{requests:,} requests a month: ${cost * requests:,.2f}")
usage fields: completion_tokens prompt_tokens prompt_tokens_details total_tokens completion tokens per run: [49, 55, 54, 62, 58] average prompt tokens 23, completion tokens 56 cost per request at the example prices: $0.000037 200,000 requests a month: $7.36
Token counts vary between runs.
Plan for: about $7.36 (example prices, not a real provider's)
Read it as steps
Measured tokens, example prices, 2,00,000 requests.
An average of 23 input tokens and 55.6 output tokens per request, at the example prices, is $0.0000368 per request and $7.36 for 2,00,000 requests a month. Output tokens account for most of it, 33.36 of the 36.81 millionths of a dollar. Real workloads differ in two ways: prompts are far longer, with history, instructions and retrieved text, and the traffic is not flat. Estimate from a measured request mix, add a margin for retries, and set a budget alert.