Skip to content
~/series/building-llm-applications/llm-fundamentals
EST: 22mSECTIONS: 11SKILLS: 6

Lesson 1 · Building LLM applications

22 min readIntermediate

LLM fundamentals

Tokens, context windows, model APIs, pricing and the mental model every AI engineer needs.

Why every LLM call is stateless and priced in both directions
1 / 4Build messages

Step 1 of 4

Build messages

Your app assembles the system prompt, the whole conversation so far and the new user message. The model holds no state, so anything it should know has to be in this list.

The model remembers nothing between calls, so the history you resend is the context you pay for.

What is an LLM?

A Large Language Model is a neural network trained to predict the next token given a sequence of tokens. Through next-token prediction at massive scale, models learn language, facts, reasoning patterns and instruction-following.

Modern LLM architectures divide into two primary categories:

1. Standard generation models (e.g., GPT-4o, Claude 3.5 Sonnet, Gemini Flash): compute a fixed number of operations per token, generating visible text immediately following prompt prefill.

2. Reasoning models and Test-time compute (OpenAI o1/o3, Claude 3.7 Thinking, Gemini Flash Thinking, DeepSeek-R1): spend variable compute at inference time. These models generate internal, hidden chain-of-thought tokens before returning the visible answer, exploring solution trees and verifying logical consistency.

Key engineering concepts: tokens (the atomic unit of text), context window (total tokens attended to), parameters (temperature, reasoning effort / thinking budget, max_tokens), and pricing (input, prompt cache read, output, and reasoning tokens).

Why fundamentals matter

Engineers who skip fundamentals burn budget on oversized prompts, hit context-window errors in production, and experience unexpected timeouts. Reasoning models introduce unique operational dynamics:

(1) Reasoning tokens are billed as output tokens, often at premium rates, even when hidden in client interfaces.

(2) The thinking phase delays time-to-first-token (TTFT) by seconds or minutes; standard 15-30s HTTP gateway timeouts will drop connections unless configured for long read timeouts.

(3) Unbudgeted reasoning can consume the entire max_tokens allowance, truncating the final answer.

Understanding tokens, caching, and test-time compute is the difference between an efficient feature and a broken, runaway bill.

Where the LLM sits

Your app → API request (messages + params + reasoning budget) → LLM provider inference:

1. Prefill: prompt tokens processed (retrieved from KV cache or recomputed).

2. Generation:

Standard model: generates visible output tokens sequentially.
Reasoning model: executes test-time search, generating internal thinking tokens, followed by the visible completion.

Total cost = (input tokens × input rate) + (cached tokens × cache read rate) + ((thinking tokens + visible output tokens) × output rate). State is stateless — every call re-sends the conversation context.

A complete LLM call

llm_call.py
import time

from openai import OpenAI
import tiktoken

client = OpenAI()

def count_tokens(text: str, model: str = "gpt-4o-mini") -> int:
    enc = tiktoken.encoding_for_model(model)
    return len(enc.encode(text))

def call_llm(messages: list[dict], model: str = "gpt-4o-mini", temperature: float = 0.7, max_tokens: int = 500) -> dict:
    """Call the LLM with token counting and cost estimation."""
    # Count input tokens
    input_text = " ".join(m["content"] for m in messages)
    input_tokens = count_tokens(input_text, model)

    start = time.perf_counter()
    response = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=temperature,
        max_tokens=max_tokens,
    )
    latency_ms = (time.perf_counter() - start) * 1000  # the API response has no latency field; time the call yourself

    output = response.choices[0].message.content
    output_tokens = response.usage.completion_tokens

    # USD per 1M tokens, as of 2026-10-26; check /pricing for current prices.
    # Real model names here because the prices belong to them. Model names change often; check your provider's model list (as of 28 October 2026).
    pricing = {
        "gpt-4o-mini": {"input": 0.15, "output": 0.60},
        "gpt-4o": {"input": 2.50, "output": 10.00},
    }
    cost = (input_tokens * pricing[model]["input"] + output_tokens * pricing[model]["output"]) / 1_000_000

    return {
        "output": output,
        "input_tokens": input_tokens,
        "output_tokens": output_tokens,
        "cost_usd": cost,
        "model": model,
        "latency_ms": round(latency_ms),
    }

result = call_llm([
    {"role": "system", "content": "You are a helpful assistant. Be concise."},
    {"role": "user", "content": "What is RAG in one sentence?"},
])
print(result["output"])
print(f"Cost: " + str(result['cost_usd']) + " (USD)")

Experiment: model and temperature

See how model choice and temperature affect output, cost and latency. Prices as of 26 October 2026 (USD per million tokens, from our model catalog); check /pricing for current prices. OpenAI has announced it will remove gpt-4o and gpt-4o-mini from its API on 14 January 2027, so treat these as worked examples, not model advice.

Pick a model and temperature. Observe the trade-offs.

What to observe

gpt-4o-mini is ~17x cheaper per token than gpt-4o ($0.15 vs $2.50 per million input tokens, as of 26 October 2026) and often faster. Most queries can use mini. Temperature 0 = deterministic (good for extraction and tests); higher = more variance (creative only). Cost scales with BOTH input and output tokens — long prompts are expensive.

Production considerations

Always count tokens and estimate cost per call. Pin model versions (not 'latest'). Default to the cheapest model that works, with fallback. Set max_tokens to prevent runaway generations. Stream for UX. Monitor cost per user and per feature — set budgets.

Challenge

Your feature makes 10k calls a day on gpt-4o. The average prompt is 2,000 tokens and the average output 800 tokens, so each call costs $0.013 and the feature costs $130/day. Cut cost by 80% without hurting quality. (Hint: model routing + prompt compression + caching.) Prices as of 26 October 2026 (USD per million tokens, from our model catalog); check /pricing for current prices. OpenAI has announced it will remove gpt-4o and gpt-4o-mini from its API on 14 January 2027, so treat these as worked examples, not model advice.

Production checklist

Production checklist

0 of 10 checked

Knowledge check

Your chatbot sends the full 20-message conversation history on every turn. Cost is climbing. What's the most effective first fix?

Complete

You now understand tokens, context windows, pricing, test-time compute and the LLM call. Next: prompt engineering — getting reliable, structured outputs.

Mark this chapter as complete

Track your progress and unlock the next chapter.

Email updates

Get the next chapter and new guides by email.

One email per substantial release. Unsubscribe in one click.

We will email you a confirmation link first, then send an occasional email when a substantial guide is published. Unsubscribe in one click. Stored with our email provider (Resend), never sold or shared. See the privacy policy.

Continue learning