Call a model through its API and steer it: parameters, prompting, context, structured output, reasoning, cost — ending with how to choose the right model.
This is the multi-page printable view of this section. Click here to print.
Work with a model
- 1: The AI API
- 2: Inference Parameters
- 3: Prompt Engineering
- 4: Context Engineering
- 5: Structured Outputs
- 6: Reasoning Models
- 7: Cost & Tokens
- 8: Choosing a Model
1 - The AI API
Everything you build talks to a model through an API: you send messages over HTTP and get a generated response back. Most providers share the same shape, so the concepts here transfer.
The request/response cycle
sequenceDiagram
participant App as Your app / SDK
participant API as Model API
App->>API: POST - messages + parameters
API-->>App: assistant message + usage + stop reason
App->>API: next turn - full history + new message
API-->>App: next assistant messageThe request
You send the model id, the conversation as a list of messages, and a few parameters:
{
"model": "<model-id>",
"max_tokens": 1024,
"messages": [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "Summarize this in one sentence: ..." }
]
}
The three roles
- system — standing instructions: who the model is, rules, output format.
- user — input from the person or your app.
- assistant — the model’s own replies. In a multi-turn chat you send the previous assistant turns back so it remembers.
The response
{
"role": "assistant",
"content": "The document argues that ...",
"usage": { "input_tokens": 812, "output_tokens": 24 },
"stop_reason": "end_turn"
}
- content — the generated text (or tool calls — see Tool & function calling).
- usage — tokens in/out, which is what you’re billed on.
- stop_reason — why it stopped (finished, hit
max_tokens, wants a tool, …).
Streaming
Instead of waiting for the whole answer, you can stream tokens as they’re generated — much better UX for long outputs, and it avoids request timeouts.
Stateless — you resend history
The API has no memory between calls. Each request must include the full conversation you want the model to see; managing that is context engineering.
SDKs
You rarely hand-write HTTP. Each provider ships an SDK (a library) that wraps these calls in your language. Exact field names vary by provider — the concepts (messages, roles, usage, streaming) do not.
Sources
2 - Inference Parameters
At request time a few parameters shape how the model generates. These are the everyday knobs for controlling output.
The core knobs
| Parameter | Controls | Typical use |
|---|---|---|
| Temperature | Randomness | Low (~0) = focused/deterministic-ish; high = creative/varied |
| Top-p (nucleus) | Sampling from the top probability mass | Alternative to temperature; lower = safer |
| Top-k | Sampling from the top k candidates | Similar effect; caps the candidate pool |
| Max tokens | Length cap on the output | Prevent runaway or truncated responses |
| Stop sequences | Strings that end generation | Cut off at a delimiter you control |
Temperature, in practice
- Low for extraction, classification, code, factual answers — you want consistency.
- Higher for brainstorming, copy, variety — you want range.
- Don’t tune temperature and top-p aggressively at once; pick one lever.
- Even at temperature 0, output isn’t guaranteed identical every time.
Example — prompt: “Write a tagline for a coffee shop.”
- Temperature 0 → the same safe answer each time: “Great coffee, every day.”
- Temperature 0.9 → varied and creative: “Sip the sunrise.” / “Your daily grind, reimagined.”
max_tokens is a hard cap
If the model hits it mid-sentence, the response is truncated — raise the limit or stream long outputs. Remember input + output share the context window.
A note on newer models
Some newer models are moving away from manual sampling knobs toward higher-level controls —
e.g. an effort / reasoning setting, or automatic (“adaptive”) reasoning — and may reject
temperature/top_p/top_k. Check your provider’s current API before assuming the classic
knobs are available.
Sources
3 - Prompt Engineering
What it is
Prompt engineering is designing the input to a foundation model to get the output you want. It’s the most direct lever over model behavior — no retraining required.
Anatomy of a good prompt
| Component | Purpose |
|---|---|
| Role | Who the model should act as |
| Task | What to do |
| Context | Background information needed |
| Constraints | Limits and conditions |
| Response format | Output structure |
| Response style | Tone and voice |
| Success criteria | What “good” looks like |
| Examples | Sample inputs/outputs when helpful |
Weak: “Summarize this document.”
Strong: “You are a document analyst. Summarize the content below in at most five key points. Each point is no more than two sentences. Use only information present in the document and do not add facts.”
Which technique when
| Situation | Reach for |
|---|---|
| The task is common and well-understood | Zero-shot — just ask; modern models usually get it |
| Output format or style keeps drifting | Few-shot — 2–5 examples teach the pattern faster than a paragraph of rules |
| Multi-step logic goes wrong | Chain-of-thought — ask it to reason step by step (or use a reasoning model) |
| The task is too big for one prompt | Prompt chaining — split into sequential prompts and validate between steps |
| The same prompt shape runs on many inputs | Prompt template — one structure, input variables |
| Every call repeats a long prefix | Prompt caching — a cost lever; see Cost & tokens |
The pattern behind the table: examples beat instructions for form; reasoning beats both for logic; and decomposition beats bigger prompts.
Strengths & limitations
- Strengths — the cheapest, fastest lever; no infrastructure; you iterate instantly.
- Limitations — can’t add knowledge the model lacks (use RAG); sensitive to wording; hits a ceiling on hard or consistency-critical tasks (then consider fine-tuning).
Sources
4 - Context Engineering
Builds on Prompt engineering. Prompting is wording the request; context engineering is deciding everything the model sees in its finite context window — and what to leave out.
What’s in the context
- System prompt — role, rules, output format.
- Instructions / examples — the task and any few-shot samples.
- Retrieved data — documents pulled in via RAG.
- Tool results — output from tools the model called.
- History / memory — prior turns, or facts carried across sessions.
flowchart LR
SP[System prompt] --> CW[Context window]
EX[Instructions and examples] --> CW
RD[Retrieved data via RAG] --> CW
TR[Tool results] --> CW
H[History and memory] --> CW
CW --> M[Model]The core problem: the window is finite
Everything above competes for the same token budget. More is not better — irrelevant context distracts the model and costs money. The goal is the right information, not the most.
Techniques
- Retrieval — fetch only the passages relevant to this request (RAG).
- Summarization / compaction — condense old turns when a conversation grows long. In a retry loop, compact each failed attempt down to what it taught, and keep the current artifact plus the criteria in full.
- Pruning — drop stale tool results and history the model no longer needs.
- Ordering & caching — put stable content first so it can be cached and reused cheaply.
Example — lean vs. bloated context
For the question “What’s our refund window?”:
- ❌ Bloated — the whole 40-page policy PDF + the entire chat history. Noisy, expensive, and often a worse answer.
- ✅ Lean — just the one retrieved paragraph about refunds + the question. Precise and cheap.
Why it matters to you
Most “the model got it wrong” problems are really context problems: it lacked the right information, or drowned in the wrong information. Fix the context before blaming the model.
Prompt and context engineering are the first two of five “-engineering” disciplines that appeared as AI systems grew; see From prompts to graphs for how they connect to harness, loop, and graph engineering.
Sources
5 - Structured Outputs
Builds on The AI API. To build with a model you usually need output your code can parse — not prose. Structured outputs constrain the model’s answer to a schema (usually JSON).
The idea
You give a schema; the model returns data that matches it; you validate and use it directly.
flowchart LR
P[Prompt + schema] --> M[Model]
M --> J[JSON matching the schema]
J --> V{Valid?}
V -->|yes| Use[Use directly in code]
V -->|no| MExample
Schema (what you ask for):
{ "type": "object",
"properties": {
"sentiment": { "type": "string", "enum": ["positive", "neutral", "negative"] },
"score": { "type": "number" }
},
"required": ["sentiment", "score"] }
Output (what you can rely on):
{ "sentiment": "positive", "score": 0.82 }
No string-parsing, no “sometimes it adds a sentence before the JSON.”
How it’s done
- JSON / schema mode — the API constrains decoding to valid JSON for your schema.
- Tool arguments — a tool call’s inputs are structured outputs too; same mechanism.
- Validate + retry — always validate; on a mismatch, re-ask.
Why it matters
Structured outputs are what make an LLM a reliable component in a pipeline — classification, extraction, routing, or any step whose result feeds other code.
Strengths & limitations
- Strengths — reliable, machine-readable output; no brittle text parsing; the schema is enforced.
- Limitations — schema features are limited (not arbitrary constraints); a brand-new schema can
add first-request latency; a refusal or a
max_tokenscut can still break the JSON.
Sources
6 - Reasoning Models
A reasoning model is trained to work through a problem step by step before giving its final answer — trading time and tokens for accuracy on hard, multi-step tasks.
flowchart LR
Q[Question] --> R[Reasoning model]
R --> Th[Internal step-by-step thinking]
Th --> A[Final answer]How it shows up
Providers expose this differently, but the shape is the same: a thinking / effort dial you turn up for harder problems (e.g. “extended” or “adaptive” thinking, an effort level, or a dedicated reasoning model). Higher effort → more internal reasoning → slower and pricier.
When to use one
- ✅ Complex reasoning, math, planning, multi-step debugging.
- ✅ Agentic tasks with many steps.
- ❌ Simple lookups, classification, or high-volume/latency-sensitive calls — a fast model is cheaper and good enough.
Example — where the extra tokens pay off
“Invoice totals are wrong, but only for orders with mixed-currency line items — find the bug.”
A fast model pattern-matches and blames the rounding helper — plausible, wrong. A reasoning model traces the flow: line items convert to base currency per line, the discount is applied at order level, but one code path applies it before conversion — a double conversion only mixed-currency orders can hit. Chained dependencies like this are exactly where the thinking earns its cost; for a lookup or a classification it’s money spent on nothing.
The trade-off
| Fast model | Reasoning model | |
|---|---|---|
| Speed | Fast | Slower |
| Cost | Lower | Higher (more tokens) |
| Best at | Simple, well-scoped tasks | Hard, multi-step problems |
Choosing between them is a model-choice decision; the effort dial is one of your inference parameters.
Sources
7 - Cost & Tokens
You pay per token — input and output, priced separately. Cost is easy to reason about once you see what feeds it.
What drives cost
flowchart LR
In[Input tokens: prompt + context + history] --> Cost[Total cost]
Out[Output tokens] --> Cost
Tier[Model tier price] --> Cost
Calls[Number of calls] --> Cost- Input tokens — your system prompt, retrieved context, and the whole conversation history you resend each turn.
- Output tokens — usually priced higher than input.
- Model tier — a flagship model can cost 10×+ a small one (see Choosing a model).
- Number of calls — agents multiply calls; a loop can be many requests per task.
Example — a rough cost calc
Support bot, per reply:
input = 2,000 tokens (system + context + question)
output = 300 tokens
Illustrative price: $3 / 1M input, $15 / 1M output
input = 2000/1e6 × $3 = $0.0060
output = 300/1e6 × $15 = $0.0045
→ ~$0.011 per reply ≈ $11 per 1,000 replies
Prices are illustrative — check your provider’s. The point: input tokens (context + history) usually dominate.
The levers
- Right-size the model — use a smaller tier where quality holds.
- Trim context — send only what’s relevant; don’t dump whole documents.
- Cap
max_tokens— bound the output. - Prompt caching — reuse a stable prompt prefix across calls to cut input cost.
- Batch offline work; stream for UX (doesn’t cut cost, improves perceived latency).
How prompt caching works (KV cache)
To generate text, the model computes attention key/value (KV) states for every token in the prompt — the expensive part. Normally these are recomputed on every call. Prompt caching stores the KV states for a stable prefix (a long system prompt, tool definitions, a big document) so a later call that starts with the same prefix reuses them instead of recomputing — cutting input cost and time-to-first-token.
Example: a support bot whose 8,000-token policy manual sits at the top of every prompt. Cache that prefix once; each subsequent question only pays to process the new question, not the manual again. It works only when the prefix is identical and at the start — put the stable part first, the variable part (the user’s question) last.
Estimating and tracking
- Count tokens with a tokenizer before you ship (don’t guess).
- Watch real token usage in Observability — the
API returns
usageon every response.
Rule of thumb: the cheapest token is the one you don’t send. Most cost problems are context problems.
Sources
8 - Choosing a Model
There’s rarely one “best” model — there’s the right model for this task. Pick along a few axes.
The dimensions that matter
| Dimension | Question |
|---|---|
| Capability | Is it smart enough for the task’s hardest step? |
| Speed / latency | Does the use case need fast responses (chat) or can it wait (batch)? |
| Cost | Price per input and output token — multiplied by your volume |
| Context window | How much text must it handle at once? |
| Modalities | Text only, or also images / audio? |
| Hosting | Proprietary API vs open-weight model you can self-host |
Capability tiers
Most providers offer a tier ladder — a large flagship model (most capable, slower, pricier), a mid tier (balanced), and a small model (fast, cheap, good for simple or high-volume tasks). Match the tier to the job rather than defaulting to the biggest.
Example — matching model to task
| Task | Pick | Why |
|---|---|---|
| Code autocomplete in the IDE | Small / fast model | High volume, latency-sensitive, simple |
| Summarize a support chat | Mid tier | Balanced quality vs. cost |
| Analyze a 50-page contract for risks | Flagship / reasoning | Hard, low volume, tolerates latency |
A practical approach
- Prototype on a capable model so model quality isn’t the bottleneck while you build.
- Then optimize — drop to a smaller/cheaper tier where quality still holds; keep the big one only where it’s needed.
- Measure the trade-off with an eval set, not by feel.
Open vs proprietary
- Proprietary (API) — easiest, most capable, no infrastructure; you send data to a vendor.
- Open-weight (self-host) — full control and data residency; you run and scale the infrastructure.