{"id":"6b08c24e38c84264c20274a0","slug":"llm-fundamentals","title":"LLM fundamentals: tokens, context windows and next-token prediction","summary":"How a large language model really works – from tokenization and the transformer, through context windows and sampling, to costs, hallucinations and a first API call in five languages.","servedLang":"en","availableLangs":["pl","en"],"topics":["llm-fundamentals","prompt-engineering","rag","llm-ops"],"techs":["python","typescript","dotnet","java","go"],"tags":["llm","tokens","context-window","transformer","sampling","hallucinations","claude"],"level":"beginner","kind":"article","access":"public","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":21,"stats":{"views":4,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:35:42.417Z","updatedAt":"2026-11-27T13:16:15.047Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"rose","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"LLM fundamentals for developers: tokens, BPE tokenizers, transformers and attention, context windows, temperature, hallucinations, costs and a first Claude API call in Python, TypeScript, C#, Java and Go.","wordCount":4042,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"A large language model (LLM) is not a knowledge base or a search engine. It is a function that, given a piece of text, returns a probability distribution over the "},{"type":"text","text":"next token","marks":[{"type":"bold"}]},{"type":"text","text":" – and it does this so well that translation, coding and reasoning emerge from that single skill. Once you understand the mechanics, you know why the model \"forgets\", where hallucinations come from and what exactly you are paying for on the invoice."}]},{"type":"stats","attrs":{"items":[{"value":"1M","label":"tokens of context window","hint":"Claude Opus 5.5, Sonnet 5.5 and Haiku 5.5 (as of November 2026)"},{"value":"5×","label":"how much more an output token costs than an input token","hint":"a typical price ratio"},{"value":"0","label":"memory between calls","hint":"the API is stateless – you send the history"}]}},{"type":"callout","attrs":{"variant":"info","title":"TL;DR"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"An LLM predicts the next "},{"type":"text","text":"token","marks":[{"type":"bold"}]},{"type":"text","text":" (a piece of a word) from everything it sees in the "},{"type":"text","text":"context window","marks":[{"type":"bold"}]},{"type":"text","text":"; the answer is produced token by token in a loop."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The model does not \"know\" what is true – it generates "},{"type":"text","text":"probable","marks":[{"type":"italic"}]},{"type":"text","text":" text. That is why you supply the facts yourself (prompt, "},{"type":"text","text":"RAG","marks":[{"type":"link","attrs":{"href":"/en/topics/rag"}}]},{"type":"text","text":", tools) and measure quality with "},{"type":"text","text":"evals","marks":[{"type":"link","attrs":{"href":"/en/topics/evals"}}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"You pay for input and output tokens on "},{"type":"text","text":"every","marks":[{"type":"bold"}]},{"type":"text","text":" call – a long conversation history and an elaborate system prompt are real money."}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"the-problem-an-assistant-that-invents-allergens"},"content":[{"type":"text","text":"The problem: an assistant that invents allergens"}]},{"type":"paragraph","content":[{"type":"text","text":"Halina's Pierogi launches a chat on its ordering site. A developer wires up a model, pastes the prompt \"You are the assistant of a pierogi restaurant, answer customer questions\" and has a working demo within an hour. A week later three tickets arrive:"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A customer asked whether the spinach pierogi contain nuts. The model confidently said \"no\" – even though the menu says nothing about it and the sauce contains walnuts."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"In a long conversation the assistant \"forgot\" the delivery address the customer gave at the start."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The API bill is three times the estimate, because every message carries the whole menu and the whole conversation so far."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Each of these problems follows directly from "},{"type":"text","text":"how","marks":[{"type":"bold"}]},{"type":"text","text":" an LLM works. Let's start with the mechanics."}]},{"type":"heading","attrs":{"level":2,"id":"intuition-autocomplete-that-has-read-the-internet"},"content":[{"type":"text","text":"Intuition: autocomplete that has read the internet"}]},{"type":"paragraph","content":[{"type":"text","text":"Your phone keyboard suggests the next word based on the previous two or three. An LLM does the same, except that it looks at the "},{"type":"text","text":"entire","marks":[{"type":"bold"}]},{"type":"text","text":" text so far (even hundreds of thousands of tokens), and its \"statistics\" are billions of parameters learned from a huge corpus of text and code. To predict how \"Ruskie pierogi are filled with…\" continues, the model has to capture grammar, cooking and the context of the conversation – and that very pressure is what makes knowledge about the world get encoded in the parameters."}]},{"type":"paragraph","content":[{"type":"text","text":"The answer is not produced all at once. The model generates one token, appends it to the input and computes the next one – until it emits an end token or hits the "},{"type":"text","text":"max_tokens","marks":[{"type":"code"}]},{"type":"text","text":" limit."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart TB\n  A[\"Text: “Ruskie pierogi are filled with”\"] --> B[\"Tokenizer\"]\n  B --> C[\"Token IDs<br/>[4021, 377, 9182, …]\"]\n  C --> E[\"Embeddings + N transformer blocks<br/>(self-attention + MLP)\"]\n  E --> G[\"Logits → softmax:<br/>probability distribution\"]\n  G --> H{\"Sampling\"}\n  H --> I[\"New token: “ potatoes”\"]\n  I -->|\"append to input and repeat\"| C","caption":"The generation loop: text → tokens → transformer → probability distribution → new token"}},{"type":"heading","attrs":{"level":2,"id":"tokens-the-currency-of-language-models"},"content":[{"type":"text","text":"Tokens: the currency of language models"}]},{"type":"paragraph","content":[{"type":"text","text":"The model sees neither letters nor words, only "},{"type":"text","text":"tokens","marks":[{"type":"bold"}]},{"type":"text","text":" – numbers from a fixed vocabulary (typically tens to hundreds of thousands of entries). The vocabulary is built with an algorithm such as "},{"type":"text","text":"BPE","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"Byte Pair Encoding","marks":[{"type":"italic"}]},{"type":"text","text":"): it starts from single bytes and repeatedly merges the most frequent pairs into new tokens. Common English words become a single token; rarer ones break into pieces."}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Text"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Example split (illustrative)"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Why"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the order","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the","marks":[{"type":"code"}]},{"type":"text","text":" · "},{"type":"text","text":" order","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"common words = single tokens, the space often belongs to the token"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"pierogarnia","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"pier","marks":[{"type":"code"}]},{"type":"text","text":" · "},{"type":"text","text":"og","marks":[{"type":"code"}]},{"type":"text","text":" · "},{"type":"text","text":"arnia","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a rare non-English word is assembled from pieces"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"zamówień","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"zam","marks":[{"type":"code"}]},{"type":"text","text":" · "},{"type":"text","text":"ów","marks":[{"type":"code"}]},{"type":"text","text":" · "},{"type":"text","text":"ień","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Polish diacritics and inflection multiply tokens"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"2026-11-26","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"202","marks":[{"type":"code"}]},{"type":"text","text":" · "},{"type":"text","text":"6","marks":[{"type":"code"}]},{"type":"text","text":" · "},{"type":"text","text":"-","marks":[{"type":"code"}]},{"type":"text","text":" · "},{"type":"text","text":"11","marks":[{"type":"code"}]},{"type":"text","text":" · "},{"type":"text","text":"-","marks":[{"type":"code"}]},{"type":"text","text":" · "},{"type":"text","text":"26","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"numbers split unintuitively – hence the trouble with arithmetic"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"The exact split depends on a given model's tokenizer – the table shows the phenomenon, not an exact result. Three consequences matter to developers:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Cost and limits are measured in tokens","marks":[{"type":"bold"}]},{"type":"text","text":", not characters. The same text in Polish usually costs noticeably more tokens than in English – measure instead of guessing."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Tokenizers differ between vendors","marks":[{"type":"bold"}]},{"type":"text","text":", and even between model generations of the same vendor. The "},{"type":"text","text":"tiktoken","marks":[{"type":"code"}]},{"type":"text","text":" library counts tokens for OpenAI models and gives wrong numbers for Claude; for Claude use the "},{"type":"text","text":"count_tokens","marks":[{"type":"code"}]},{"type":"text","text":" endpoint."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Model quirks","marks":[{"type":"bold"}]},{"type":"text","text":" (counting letters in a word, reversing strings, arithmetic on long numbers) often come from the fact that the model never saw individual characters."}]}]}]},{"type":"codeGroup","attrs":{"title":"Counting tokens and estimating cost"},"content":[{"type":"codeBlock","attrs":{"language":"python","filename":"estimate_cost.py"},"content":[{"type":"text","text":"import anthropic\n\nclient = anthropic.Anthropic()\n\n# List prices in USD per 1M tokens (check the pricing page before relying on them).\nPRICES = {\n    \"claude-opus-5-5\": (4.00, 20.00),\n    \"claude-sonnet-5-5\": (2.00, 10.00),\n    \"claude-haiku-5-5\": (0.10, 0.50),\n}\n\ndef estimate(model: str, system: str, question: str, expected_output: int) -> float:\n    # count_tokens uses the real tokenizer of the given model - never tiktoken.\n    counted = client.messages.count_tokens(\n        model=model,\n        system=system,\n        messages=[{\"role\": \"user\", \"content\": question}],\n    )\n    price_in, price_out = PRICES[model]\n    return (counted.input_tokens * price_in + expected_output * price_out) / 1_000_000\n\nmenu = open(\"menu.md\", encoding=\"utf-8\").read()  # ~ the whole menu as context\nfor model in PRICES:\n    cost = estimate(model, menu, \"Which pierogi are vegan?\", expected_output=300)\n    print(f\"{model:20} ${cost:.5f} per question\")"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"estimate-cost.ts"},"content":[{"type":"text","text":"import Anthropic from \"@anthropic-ai/sdk\";\nimport { readFileSync } from \"node:fs\";\n\nconst client = new Anthropic();\n\n// List prices in USD per 1M tokens (check the pricing page before relying on them).\nconst PRICES = {\n  \"claude-opus-5-5\": [4.0, 20.0],\n  \"claude-sonnet-5-5\": [2.0, 10.0],\n  \"claude-haiku-5-5\": [0.1, 0.5],\n} as const;\ntype ModelId = keyof typeof PRICES;\n\nasync function estimate(model: ModelId, system: string, question: string, expectedOutput: number) {\n  // countTokens uses the real tokenizer of the given model - never a GPT tokenizer.\n  const counted = await client.messages.countTokens({\n    model,\n    system,\n    messages: [{ role: \"user\", content: question }],\n  });\n  const [priceIn, priceOut] = PRICES[model];\n  return (counted.input_tokens * priceIn + expectedOutput * priceOut) / 1_000_000;\n}\n\nconst menu = readFileSync(\"menu.md\", \"utf8\");\nfor (const model of Object.keys(PRICES) as ModelId[]) {\n  const cost = await estimate(model, menu, \"Which pierogi are vegan?\", 300);\n  console.log(`${model.padEnd(20)} $${cost.toFixed(5)} per question`);\n}"}]},{"type":"codeBlock","attrs":{"language":"csharp","filename":"EstimateCost.cs"},"content":[{"type":"text","text":"using Anthropic;\nusing Anthropic.Models.Messages;\n\nAnthropicClient client = new();\n\n// List prices in USD per 1M tokens (check the pricing page before relying on them).\nvar prices = new Dictionary<string, (decimal In, decimal Out)>\n{\n    [\"claude-opus-5-5\"] = (4.00m, 20.00m),\n    [\"claude-sonnet-5-5\"] = (2.00m, 10.00m),\n    [\"claude-haiku-5-5\"] = (0.10m, 0.50m),\n};\n\nstring menu = await File.ReadAllTextAsync(\"menu.md\");\n\nforeach (var (model, price) in prices)\n{\n    // CountTokens uses the real tokenizer of the given model.\n    MessageTokensCount counted = await client.Messages.CountTokens(new MessageCountTokensParams\n    {\n        Model = model,\n        System = menu,\n        Messages = [new UserMessageParam { Content = \"Which pierogi are vegan?\" }],\n    });\n\n    const int expectedOutput = 300;\n    decimal cost = (counted.InputTokens * price.In + expectedOutput * price.Out) / 1_000_000m;\n    Console.WriteLine($\"{model,-20} ${cost:F5} per question\");\n}"}]}]},{"type":"heading","attrs":{"level":2,"id":"the-context-window-everything-the-model-sees-at-once"},"content":[{"type":"text","text":"The context window: everything the model sees at once"}]},{"type":"paragraph","content":[{"type":"text","text":"The "},{"type":"text","text":"context window","marks":[{"type":"bold"}]},{"type":"text","text":" is the maximum number of tokens a model processes in a single call – input "},{"type":"text","text":"and","marks":[{"type":"bold"}]},{"type":"text","text":" output together. It holds the system prompt, tool definitions, attached documents, the whole conversation history, the current question and the generated answer."}]},{"type":"paragraph","content":[{"type":"text","text":"The most important fact beginners forget: "},{"type":"text","text":"the API is stateless","marks":[{"type":"bold"}]},{"type":"text","text":". The model does not remember the previous call. A chat's \"memory\" is an illusion created by the application, which sends the entire history every time."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"sequenceDiagram\n  participant U as Customer\n  participant A as Application\n  participant M as Model (API)\n  U->>A: “Deliver to 5 Long Street”\n  A->>M: system + [message 1]\n  M-->>A: answer 1 + usage\n  U->>A: “How long will it take?”\n  A->>M: system + [message 1, answer 1, message 2]\n  M-->>A: answer 2 + usage\n  Note over A,M: Every turn pays again for the whole history","caption":"A stateless API: on every turn the application resends the whole conversation"}},{"type":"paragraph","content":[{"type":"text","text":"This explains two of the pierogi tickets. The assistant \"forgot\" the address because the application trimmed the history to the last five messages. And the bill grew because on every turn the whole menu and the whole conversation were counted again as input tokens:"}]},{"type":"chart","attrs":{"type":"area","title":"Input tokens sent by one conversation – turn by turn","caption":"Illustrative data: system prompt with the menu 1,800 tokens, tools 1,200, history grows by about 1,100 tokens per turn.","unit":"tokens","stacked":true,"data":{"labels":["turn 1","turn 2","turn 3","turn 4","turn 5","turn 6","turn 7","turn 8"],"series":[{"name":"System prompt (menu)","values":[1800,1800,1800,1800,1800,1800,1800,1800]},{"name":"Tool definitions","values":[1200,1200,1200,1200,1200,1200,1200,1200]},{"name":"Conversation history","values":[150,1250,2350,3450,4550,5650,6750,7850]}]}}},{"type":"paragraph","content":[{"type":"text","text":"A large window (a million tokens) does not mean it is worth filling. Every token costs money and adds latency, and models make worse use of information \"buried\" in the middle of a very long context (a phenomenon known as "},{"type":"text","text":"lost in the middle","marks":[{"type":"italic"}]},{"type":"text","text":"). Good practice is to send what is needed: the relevant document fragments instead of the whole knowledge base – which is exactly the idea behind "},{"type":"text","text":"RAG","marks":[{"type":"link","attrs":{"href":"/en/topics/rag"}}]},{"type":"text","text":" – and to summarize or compact the older part of the conversation."}]},{"type":"callout","attrs":{"variant":"tip","title":"Prompt caching"},"content":[{"type":"paragraph","content":[{"type":"text","text":"The repeated beginning of a prompt (instructions, menu, tool definitions) can be marked for caching. Subsequent calls with an identical prefix pay a fraction of the price for those tokens. The catch: the prefix must be byte-for-byte identical – a timestamp in the system prompt breaks the cache on every request. Details in the "},{"type":"text","text":"LLMOps","marks":[{"type":"link","attrs":{"href":"/en/topics/llm-ops"}}]},{"type":"text","text":" topic."}]}]},{"type":"heading","attrs":{"level":2,"id":"what-happens-inside-the-transformer-in-five-sentences"},"content":[{"type":"text","text":"What happens inside: the transformer in five sentences"}]},{"type":"paragraph","content":[{"type":"text","text":"Almost all modern LLMs are "},{"type":"text","text":"decoder-only","marks":[{"type":"italic"}]},{"type":"text","text":" "},{"type":"text","text":"transformers","marks":[{"type":"bold"}]},{"type":"text","text":", descended from the 2017 paper "},{"type":"text","text":"Attention Is All You Need","marks":[{"type":"italic"}]},{"type":"text","text":"."}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Each token is turned into an "},{"type":"text","text":"embedding","marks":[{"type":"bold"}]},{"type":"text","text":" – a vector of a few thousand numbers – enriched with information about its position in the text."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The vectors pass through dozens of "},{"type":"text","text":"transformer blocks","marks":[{"type":"bold"}]},{"type":"text","text":". In each, the "},{"type":"text","text":"self-attention","marks":[{"type":"bold"}]},{"type":"text","text":" mechanism lets a token \"look at\" all earlier tokens and pull relevant information from them (for example, who \"he\" refers to), and an MLP layer processes the result."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A causal mask makes each token see only the past – the model learns to predict the future without peeking at it."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The last vector is projected onto "},{"type":"text","text":"logits","marks":[{"type":"bold"}]},{"type":"text","text":" – one number per vocabulary token – and the softmax function turns them into probabilities."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The next token is chosen from that distribution."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"This also explains the price list. The model processes input tokens "},{"type":"text","text":"in parallel","marks":[{"type":"bold"}]},{"type":"text","text":" (the "},{"type":"text","text":"prefill","marks":[{"type":"italic"}]},{"type":"text","text":" phase), but has to generate output tokens "},{"type":"text","text":"one after another","marks":[{"type":"bold"}]},{"type":"text","text":", each requiring a separate pass through the network (the "},{"type":"text","text":"decode","marks":[{"type":"italic"}]},{"type":"text","text":" phase, sped up by the "},{"type":"text","text":"KV cache","marks":[{"type":"italic"}]},{"type":"text","text":"). That is why an output token costs several times more, and why answer length has the biggest impact on waiting time."}]},{"type":"resourceRef","attrs":{"resourceId":"6b0854ad1a40d7e6c24c8ee7"}},{"type":"heading","attrs":{"level":2,"id":"sampling-why-the-same-request-gives-different-answers"},"content":[{"type":"text","text":"Sampling: why the same request gives different answers"}]},{"type":"paragraph","content":[{"type":"text","text":"The model returns a distribution, not a single answer. The strategy for picking a token from it is called "},{"type":"text","text":"sampling","marks":[{"type":"bold"}]},{"type":"text","text":". The classic knobs are:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"temperature","marks":[{"type":"bold"}]},{"type":"text","text":" – divides the logits before the softmax: a low value sharpens the distribution (the favourite almost always wins), a high one flattens it (more variety and more risk),"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"top-p","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"nucleus sampling","marks":[{"type":"italic"}]},{"type":"text","text":") – samples only from the most probable tokens whose cumulative probability reaches "},{"type":"text","text":"p","marks":[{"type":"italic"}]},{"type":"text","text":","}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"top-k","marks":[{"type":"bold"}]},{"type":"text","text":" – samples from the "},{"type":"text","text":"k","marks":[{"type":"italic"}]},{"type":"text","text":" best candidates."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"The chart shows a real softmax computed for made-up logits of candidates completing the sentence \"Ruskie pierogi are filled with…\":"}]},{"type":"chart","attrs":{"type":"bar","title":"Temperature changes the shape of the next-token distribution","caption":"Illustration: the logits [4.0, 3.2, 2.6, 1.5, 0.8, 0.3] are made up; the probabilities are softmax(logit / T).","unit":"%","data":{"labels":["potatoes","cheese","quark","onion","meat","cabbage"],"series":[{"name":"T = 0.5","values":[78.6,15.9,4.8,0.5,0.1,0]},{"name":"T = 1.0","values":[54.2,24.4,13.4,4.5,2.2,1.3]},{"name":"T = 1.5","values":[42.2,24.7,16.6,8,5,3.6]}]}}},{"type":"callout","attrs":{"variant":"warning","title":"Sampling in the current Claude API"},"content":[{"type":"paragraph","content":[{"type":"text","text":"The newest Claude models (from the 4.7 generation on) accept only the default sampling values, and from API version "},{"type":"text","text":"2026-10-21","marks":[{"type":"code"}]},{"type":"text","text":" the "},{"type":"text","text":"temperature","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"top_p","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"top_k","marks":[{"type":"code"}]},{"type":"text","text":" parameters cause a 400 error altogether. You set how deeply the model \"thinks\" with the "},{"type":"text","text":"effort","marks":[{"type":"code"}]},{"type":"text","text":" parameter ("},{"type":"text","text":"low","marks":[{"type":"code"}]},{"type":"text","text":" … "},{"type":"text","text":"max","marks":[{"type":"code"}]},{"type":"text","text":"), and you enforce a repeatable format with structured outputs, not temperature. You will still meet temperature in local models and OpenAI-compatible APIs – see "},{"type":"text","text":"Local LLMs","marks":[{"type":"link","attrs":{"href":"/en/topics/local-llms"}}]},{"type":"text","text":"."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Even at zero temperature, do not count on bit-for-bit reproducible answers – floating-point arithmetic on GPUs and batching on the provider's side introduce small differences. Tests for LLM applications are therefore written as evaluations with criteria, not string comparisons."}]},{"type":"heading","attrs":{"level":2,"id":"your-first-api-call"},"content":[{"type":"text","text":"Your first API call"}]},{"type":"pullQuote","attrs":{"text":"The hottest new programming language is English.","author":"Andrej Karpathy","role":"OpenAI co-founder","source":"post on X (2023)"}},{"type":"paragraph","content":[{"type":"text","text":"Enough theory – time to send a request. All official Anthropic SDKs look similar: the client reads the key from "},{"type":"text","text":"ANTHROPIC_API_KEY","marks":[{"type":"code"}]},{"type":"text","text":", the call takes a model, an output token limit, a system prompt and a list of messages, and the response contains content blocks, a stop reason ("},{"type":"text","text":"stop_reason","marks":[{"type":"code"}]},{"type":"text","text":") and token usage ("},{"type":"text","text":"usage","marks":[{"type":"code"}]},{"type":"text","text":")."}]},{"type":"codeGroup","attrs":{"title":"First Messages API call"},"content":[{"type":"codeBlock","attrs":{"language":"python","filename":"first_call.py"},"content":[{"type":"text","text":"import anthropic\n\nclient = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment\n\nSYSTEM = (\n    \"You are the support assistant of Halina's Pierogi. \"\n    \"Answer briefly. If you are not sure, say so instead of guessing.\"\n)\n\nresponse = client.messages.create(\n    model=\"claude-opus-5-5\",\n    max_tokens=1024,\n    system=SYSTEM,\n    messages=[{\"role\": \"user\", \"content\": \"Do you deliver on Sundays?\"}],\n)\n\n# The model may stop for different reasons - always check before trusting the text.\nif response.stop_reason == \"max_tokens\":\n    print(\"Answer was cut off - raise max_tokens or ask for a shorter reply.\")\nelif response.stop_reason == \"refusal\":\n    print(\"Request declined.\")\n\nfor block in response.content:\n    if block.type == \"text\":\n        print(block.text)\n\n# Every response reports what you pay for.\nusage = response.usage\nprint(f\"input={usage.input_tokens} output={usage.output_tokens}\")"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"first-call.ts"},"content":[{"type":"text","text":"import Anthropic from \"@anthropic-ai/sdk\";\n\nconst client = new Anthropic(); // reads ANTHROPIC_API_KEY from the environment\n\nconst SYSTEM =\n  \"You are the support assistant of Halina's Pierogi. \" +\n  \"Answer briefly. If you are not sure, say so instead of guessing.\";\n\nconst response = await client.messages.create({\n  model: \"claude-opus-5-5\",\n  max_tokens: 1024,\n  system: SYSTEM,\n  messages: [{ role: \"user\", content: \"Do you deliver on Sundays?\" }],\n});\n\n// The model may stop for different reasons - always check before trusting the text.\nif (response.stop_reason === \"max_tokens\") {\n  console.warn(\"Answer was cut off - raise max_tokens or ask for a shorter reply.\");\n} else if (response.stop_reason === \"refusal\") {\n  console.warn(\"Request declined.\");\n}\n\nfor (const block of response.content) {\n  if (block.type === \"text\") console.log(block.text);\n}\n\n// Every response reports what you pay for.\nconst { input_tokens, output_tokens } = response.usage;\nconsole.log(`input=${input_tokens} output=${output_tokens}`);"}]},{"type":"codeBlock","attrs":{"language":"csharp","filename":"FirstCall.cs"},"content":[{"type":"text","text":"using Anthropic;\nusing Anthropic.Models.Messages;\n\nAnthropicClient client = new(); // reads ANTHROPIC_API_KEY from the environment\n\nconst string SystemPrompt =\n    \"You are the support assistant of Halina's Pierogi. \" +\n    \"Answer briefly. If you are not sure, say so instead of guessing.\";\n\nvar response = await client.Messages.Create(new MessageCreateParams\n{\n    Model = \"claude-opus-5-5\",\n    MaxTokens = 1024,\n    System = SystemPrompt,\n    Messages = [new UserMessageParam { Content = \"Do you deliver on Sundays?\" }],\n});\n\n// The model may stop for different reasons - always check before trusting the text.\nif (response.StopReason == \"max_tokens\")\n    Console.WriteLine(\"Answer was cut off - raise MaxTokens or ask for a shorter reply.\");\n\nforeach (var text in response.Content.Select(b => b.Value).OfType<TextBlock>())\n    Console.WriteLine(text.Text);\n\n// Every response reports what you pay for.\nConsole.WriteLine($\"input={response.Usage.InputTokens} output={response.Usage.OutputTokens}\");"}]},{"type":"codeBlock","attrs":{"language":"java","filename":"FirstCall.java"},"content":[{"type":"text","text":"import com.anthropic.client.AnthropicClient;\nimport com.anthropic.client.okhttp.AnthropicOkHttpClient;\nimport com.anthropic.models.messages.Message;\nimport com.anthropic.models.messages.MessageCreateParams;\n\npublic class FirstCall {\n    public static void main(String[] args) {\n        // Reads ANTHROPIC_API_KEY from the environment.\n        AnthropicClient client = AnthropicOkHttpClient.fromEnv();\n\n        MessageCreateParams params = MessageCreateParams.builder()\n                .model(\"claude-opus-5-5\")\n                .maxTokens(1024L)\n                .system(\"You are the support assistant of Halina's Pierogi. \"\n                        + \"Answer briefly. If you are not sure, say so instead of guessing.\")\n                .addUserMessage(\"Do you deliver on Sundays?\")\n                .build();\n\n        Message response = client.messages().create(params);\n\n        response.content().stream()\n                .flatMap(block -> block.text().stream())\n                .forEach(text -> System.out.println(text.text()));\n\n        // Every response reports what you pay for.\n        System.out.printf(\"input=%d output=%d%n\",\n                response.usage().inputTokens(), response.usage().outputTokens());\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"go","filename":"first_call.go"},"content":[{"type":"text","text":"package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/anthropics/anthropic-sdk-go/v2\"\n)\n\nfunc main() {\n\tclient := anthropic.NewClient() // reads ANTHROPIC_API_KEY from the environment\n\n\tresp, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{\n\t\tModel:     \"claude-opus-5-5\",\n\t\tMaxTokens: 1024,\n\t\tSystem: []anthropic.TextBlockParam{{\n\t\t\tText: \"You are the support assistant of Halina's Pierogi. \" +\n\t\t\t\t\"Answer briefly. If you are not sure, say so instead of guessing.\",\n\t\t}},\n\t\tMessages: []anthropic.MessageParam{\n\t\t\tanthropic.NewUserMessage(anthropic.NewTextBlock(\"Do you deliver on Sundays?\")),\n\t\t},\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, block := range resp.Content {\n\t\tif text, ok := block.AsAny().(anthropic.TextBlock); ok {\n\t\t\tfmt.Println(text.Text)\n\t\t}\n\t}\n\t// Every response reports what you pay for.\n\tfmt.Printf(\"input=%d output=%d\\n\", resp.Usage.InputTokens, resp.Usage.OutputTokens)\n}"}]}]},{"type":"paragraph","content":[{"type":"text","text":"Note three details:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"max_tokens","marks":[{"type":"code"}]},{"type":"text","text":" is a hard output limit","marks":[{"type":"bold"}]},{"type":"text","text":", not a wish. When the model reaches it, the answer is cut off mid-sentence and "},{"type":"text","text":"stop_reason","marks":[{"type":"code"}]},{"type":"text","text":" is "},{"type":"text","text":"max_tokens","marks":[{"type":"code"}]},{"type":"text","text":" – always check it."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"content","marks":[{"type":"code"}]},{"type":"text","text":" is a list of blocks","marks":[{"type":"bold"}]},{"type":"text","text":", not a single string. Besides text it can contain thinking blocks or tool calls – filter by type."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"usage","marks":[{"type":"code"}]},{"type":"text","text":" tells you what you will pay.","marks":[{"type":"bold"}]},{"type":"text","text":" Log it from day one; without it you cannot optimize costs."}]}]}]},{"type":"heading","attrs":{"level":3,"id":"streaming-the-answer-before-it-is-complete"},"content":[{"type":"text","text":"Streaming: the answer before it is complete"}]},{"type":"paragraph","content":[{"type":"text","text":"Generating a long answer takes seconds. Instead of making the user wait, display tokens as they are produced ("},{"type":"text","text":"streaming","marks":[{"type":"italic"}]},{"type":"text","text":", technically Server-Sent Events). The key UX metric then becomes time to first token (TTFT), not the time of the whole answer."}]},{"type":"codeGroup","attrs":{"title":"Streaming the response"},"content":[{"type":"codeBlock","attrs":{"language":"python","filename":"stream_answer.py"},"content":[{"type":"text","text":"import anthropic\n\nclient = anthropic.Anthropic()\n\nwith client.messages.stream(\n    model=\"claude-opus-5-5\",\n    max_tokens=64000,\n    output_config={\"effort\": \"low\"},  # simple FAQ answer: little reasoning needed\n    messages=[{\"role\": \"user\", \"content\": \"Explain in 3 sentences how you cook pierogi.\"}],\n) as stream:\n    for text in stream.text_stream:  # tokens arrive as they are generated\n        print(text, end=\"\", flush=True)\n    final = stream.get_final_message()\n\nprint(f\"\\n[{final.stop_reason}] output tokens: {final.usage.output_tokens}\")"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"stream-answer.ts"},"content":[{"type":"text","text":"import Anthropic from \"@anthropic-ai/sdk\";\n\nconst client = new Anthropic();\n\nconst stream = client.messages.stream({\n  model: \"claude-opus-5-5\",\n  max_tokens: 64000,\n  output_config: { effort: \"low\" }, // simple FAQ answer: little reasoning needed\n  messages: [{ role: \"user\", content: \"Explain in 3 sentences how you cook pierogi.\" }],\n});\n\n// Tokens arrive as they are generated - render them immediately.\nstream.on(\"text\", (delta) => process.stdout.write(delta));\n\nconst final = await stream.finalMessage();\nconsole.log(`\\n[${final.stop_reason}] output tokens: ${final.usage.output_tokens}`);"}]},{"type":"codeBlock","attrs":{"language":"go","filename":"stream_answer.go"},"content":[{"type":"text","text":"package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/anthropics/anthropic-sdk-go/v2\"\n)\n\nfunc main() {\n\tclient := anthropic.NewClient()\n\n\tstream := client.Messages.NewStreaming(context.Background(), anthropic.MessageNewParams{\n\t\tModel:     \"claude-opus-5-5\",\n\t\tMaxTokens: 64000,\n\t\tMessages: []anthropic.MessageParam{\n\t\t\tanthropic.NewUserMessage(anthropic.NewTextBlock(\"Explain in 3 sentences how you cook pierogi.\")),\n\t\t},\n\t})\n\n\t// Tokens arrive as server-sent events - print each text delta immediately.\n\tfor stream.Next() {\n\t\tevent := stream.Current()\n\t\tif delta, ok := event.AsAny().(anthropic.ContentBlockDeltaEvent); ok {\n\t\t\tif text, ok := delta.Delta.AsAny().(anthropic.TextDelta); ok {\n\t\t\t\tfmt.Print(text.Text)\n\t\t\t}\n\t\t}\n\t}\n\tif err := stream.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}"}]},{"type":"codeBlock","attrs":{"language":"csharp","filename":"StreamAnswer.cs"},"content":[{"type":"text","text":"using Anthropic;\nusing Anthropic.Models.Messages;\n\nAnthropicClient client = new();\n\nvar parameters = new MessageCreateParams\n{\n    Model = \"claude-opus-5-5\",\n    MaxTokens = 64000,\n    Messages = [new UserMessageParam { Content = \"Explain in 3 sentences how you cook pierogi.\" }],\n};\n\n// Tokens arrive as server-sent events - print each text delta immediately.\nawait foreach (RawMessageStreamEvent ev in client.Messages.CreateStreaming(parameters))\n{\n    if (ev.TryPickContentBlockDelta(out var delta) && delta.Delta.TryPickText(out var text))\n        Console.Write(text.Text);\n}"}]}]},{"type":"section","attrs":{"background":"dots","width":"wide","padding":"m"},"content":[{"type":"heading","attrs":{"level":2,"id":"where-the-model-knows-anything-from-training-stages"},"content":[{"type":"text","text":"Where the model \"knows\" anything from: training stages"}]},{"type":"columns","attrs":{"layout":"1-1","valign":"top"},"content":[{"type":"column","content":[{"type":"paragraph","content":[{"type":"text","text":"1. Pretraining.","marks":[{"type":"bold"}]},{"type":"text","text":" The model learns to predict the next token on trillions of tokens of text and code. The result is a \"base model\" that completes text brilliantly but does not answer questions like an assistant."}]},{"type":"paragraph","content":[{"type":"text","text":"2. Instruction tuning (SFT).","marks":[{"type":"bold"}]},{"type":"text","text":" On carefully prepared dialogue examples, the model learns the \"question → helpful answer\" format."}]},{"type":"paragraph","content":[{"type":"text","text":"3. Reinforcement learning.","marks":[{"type":"bold"}]},{"type":"text","text":" RLHF (human ratings), RLAIF and Constitutional AI (ratings by another model following written principles) teach preferred behaviour: helpfulness, honesty, declining harmful requests. Training on verifiable tasks (maths, code) develops step-by-step reasoning."}]},{"type":"paragraph","content":[{"type":"text","text":"4. Knowledge cutoff.","marks":[{"type":"bold"}]},{"type":"text","text":" Anything that happened after the training data was collected is unknown to the model – you have to supply current facts in the context."}]}]},{"type":"column","content":[{"type":"timeline","attrs":{"items":[{"date":"2017","title":"Attention Is All You Need","text":"Vaswani et al. (Google) introduce the transformer architecture."},{"date":"2018","title":"GPT and BERT","text":"OpenAI shows generative pretraining, Google the bidirectional BERT."},{"date":"2019","title":"GPT-2","text":"1.5B parameters and a debate about whether to release the weights."},{"date":"2020","title":"GPT-3","text":"175B parameters; learning \"from a few examples in the prompt\" (few-shot)."},{"date":"2022","title":"InstructGPT and ChatGPT","text":"RLHF turns a base model into an assistant; ChatGPT launches at the end of the year."},{"date":"2023","title":"GPT-4, Claude, Llama","text":"a race between commercial and open-weight models."},{"date":"2024","title":"Reasoning models and MCP","text":"models that \"think before answering\"; Anthropic publishes the Model Context Protocol."},{"date":"2025","title":"Agents","text":"models in a loop with tools become part of developers' daily work."}]}}]}]}]},{"type":"heading","attrs":{"level":2,"id":"hallucinations-confident-but-untrue-text"},"content":[{"type":"text","text":"Hallucinations: confident but untrue text"}]},{"type":"paragraph","content":[{"type":"text","text":"A "},{"type":"text","text":"hallucination","marks":[{"type":"bold"}]},{"type":"text","text":" is a fluent, convincing but false answer. It is not a bug in the model's code but a natural consequence of its training objective: the model generates "},{"type":"text","text":"probable","marks":[{"type":"italic"}]},{"type":"text","text":" text, and \"sounds credible\" does not mean \"true\". When the training data lacked the information (Halina's menu), the model will still produce something that fits stylistically."}]},{"type":"paragraph","content":[{"type":"text","text":"How to deal with it:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Grounding","marks":[{"type":"bold"}]},{"type":"text","text":" – attach the source of truth to the context (menu, terms) and instruct the model to answer only from it. For large document sets, "},{"type":"text","text":"RAG","marks":[{"type":"link","attrs":{"href":"/en/topics/rag"}}]},{"type":"text","text":" does this."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Permission to say \"I don't know\"","marks":[{"type":"bold"}]},{"type":"text","text":" – state explicitly in the prompt what the model should do when data is missing. Without it, it will try to help at any cost."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Citations and verification","marks":[{"type":"bold"}]},{"type":"text","text":" – ask for the supporting source fragment, and in critical places (allergens!) check the answer with a rule or a second call."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Tools instead of memory","marks":[{"type":"bold"}]},{"type":"text","text":" – fetch the order status from your API through "},{"type":"text","text":"tool use","marks":[{"type":"link","attrs":{"href":"/en/topics/tool-use"}}]},{"type":"text","text":" instead of hoping the model will \"guess\" it."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Measurement","marks":[{"type":"bold"}]},{"type":"text","text":" – a set of test questions with expected answers ("},{"type":"text","text":"evals","marks":[{"type":"link","attrs":{"href":"/en/topics/evals"}}]},{"type":"text","text":") tells you whether a prompt change reduced the hallucination rate."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"costs-simple-maths-big-numbers"},"content":[{"type":"text","text":"Costs: simple maths, big numbers"}]},{"type":"paragraph","content":[{"type":"text","text":"Call cost = input tokens × input price + output tokens × output price (+ any cache reads and writes). Prices are quoted per million tokens."}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Model"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Context window"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Max output"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Input / output per 1M tokens"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"claude-opus-5-5","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"1M"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"128K"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"USD 4 / USD 20"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"claude-sonnet-5-5","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"1M"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"128K"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"USD 2 / USD 10"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"claude-haiku-5-5","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"1M"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"128K"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"USD 0.10 / USD 0.50 (prompts up to 100K tokens)"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Anthropic API list prices as of November 2026 – check the current price list before budgeting.","marks":[{"type":"italic"}]}]},{"type":"paragraph","content":[{"type":"text","text":"Let's price the pierogi chat: 50,000 conversations a month, 4 turns each, on average 6,000 input and 400 output tokens per turn. That is 1.2 billion input tokens and 80 million output tokens a month:"}]},{"type":"chart","attrs":{"type":"bar","title":"Monthly cost of the pierogi chat by model","caption":"Illustrative scenario: 200k calls × 6,000 input and 400 output tokens, list prices from November 2026, no caching.","unit":"USD","stacked":true,"data":{"labels":["Opus 5.5","Sonnet 5.5","Haiku 5.5"],"series":[{"name":"Input tokens","values":[4800,2400,120]},{"name":"Output tokens","values":[1600,800,40]}]}}},{"type":"paragraph","content":[{"type":"text","text":"The takeaway: in conversational applications the "},{"type":"text","text":"input","marks":[{"type":"bold"}]},{"type":"text","text":" cost dominates, because history and context are sent over and over. The cheapest optimizations are a shorter context, prefix caching and matching the model to the task – simple ticket classification does not need the largest model."}]},{"type":"heading","attrs":{"level":2,"id":"when-an-llm-and-when-plain-code"},"content":[{"type":"text","text":"When an LLM, and when plain code"}]},{"type":"prosCons","attrs":{"pros":["understanding and generating natural language, including unstructured text","summarizing, classifying and extracting data from text without writing rules","generating and explaining code, translation, changing style","one model handles hundreds of tasks – you only change the prompt"],"cons":["no guarantee of correctness: hallucinations and factual errors","non-determinism makes classic unit tests hard","cost and latency grow with context and answer length","knowledge frozen at the training cutoff","vulnerable to prompt injection when processing untrusted text"],"prosTitle":"Strengths","consTitle":"Weaknesses"}},{"type":"callout","attrs":{"variant":"danger","title":"A common mistake"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Using an LLM where deterministic code is enough: validating a tax number, summing a cart, checking opening hours. The model can get it wrong, costs money and is slower. Give it language tasks and leave calculations and business rules to code – or expose them to the model as "},{"type":"text","text":"tools","marks":[{"type":"link","attrs":{"href":"/en/topics/tool-use"}}]},{"type":"text","text":"."}]}]},{"type":"heading","attrs":{"level":2,"id":"pre-production-checklist"},"content":[{"type":"text","text":"Pre-production checklist"}]},{"type":"taskList","content":[{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"type":"text","text":"The system prompt says what to do when data is missing (\"I don't know\" instead of guessing)"}]}]},{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"type":"text","text":"Facts (menu, prices, allergens) come from the context or tools, not from the model's memory"}]}]},{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"type":"text","text":"Every response checks "},{"type":"text","text":"stop_reason","marks":[{"type":"code"}]},{"type":"text","text":" ("},{"type":"text","text":"max_tokens","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"refusal","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]},{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"type":"text","text":"usage","marks":[{"type":"code"}]},{"type":"text","text":" is logged per request and per application feature; you have a cost alert"}]}]},{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"type":"text","text":"Conversation history has a trimming or summarizing strategy – deliberate, not accidental"}]}]},{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"type":"text","text":"The stable prompt prefix is cached and contains no variable data (dates, IDs)"}]}]},{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"type":"text","text":"Answers are streamed in the user interface"}]}]},{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"type":"text","text":"An evaluation set runs on every prompt or model change"}]}]}]},{"type":"heading","attrs":{"level":2,"id":"test-yourself"},"content":[{"type":"text","text":"Test yourself"}]},{"type":"quiz","attrs":{"question":"An application sends the model only the user's latest message. What happens on the third turn of the conversation?","multiple":false,"options":[{"text":"The model remembers the previous turns because the API keeps a session","correct":false,"explanation":"The Messages API is stateless – it does not store the conversation between calls."},{"text":"The model does not know the earlier turns and answers without their context","correct":true,"explanation":"Correct. Conversation \"memory\" exists only when the application sends the whole history in the messages array."},{"text":"The model reads the history from the previous call's context window","correct":false,"explanation":"A context window belongs to a single call; nothing remains after it ends."}]}},{"type":"quiz","attrs":{"question":"Why does an output token cost several times more than an input token?","multiple":false,"options":[{"text":"Because output tokens are longer","correct":false,"explanation":"Input and output tokens come from the same vocabulary."},{"text":"Because output is generated sequentially, token by token, while input is processed in parallel","correct":true,"explanation":"Exactly – the decode phase needs a separate pass through the network for every token."},{"text":"Because the provider adds the cost of moderating answers","correct":false,"explanation":"The price ratio reflects compute cost, not moderation."}]}},{"type":"details","content":[{"type":"detailsSummary","content":[{"type":"text","text":"Interview question: how does the context window differ from training knowledge?"}]},{"type":"detailsContent","content":[{"type":"paragraph","content":[{"type":"text","text":"Training knowledge is stored in the model's parameters – \"frozen\" at the cutoff date, imprecise and impossible to change without retraining or "},{"type":"text","text":"fine-tuning","marks":[{"type":"link","attrs":{"href":"/en/topics/fine-tuning"}}]},{"type":"text","text":". The context window is the data supplied in a specific call: the model uses it literally and up to date, but only in that single request and only up to the token limit. That is why current and company-specific facts are passed in the context (prompt, RAG, tools) rather than relying on the model's memory."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"what-s-next"},"content":[{"type":"text","text":"What's next"}]},{"type":"paragraph","content":[{"type":"text","text":"You know the mechanics – now learn to steer them. The next steps on the \"AI for developers\" path:"}]},{"type":"linkCard","attrs":{"url":"/en/topics/prompt-engineering","title":"Prompt engineering","description":"How to write instructions, examples and output formats so the model does what you want","kind":"topic","ref":"prompt-engineering"}},{"type":"linkCard","attrs":{"url":"/en/topics/embeddings-vector-db","title":"Embeddings and vector databases","description":"Turning text into meaning vectors and searching by similarity","kind":"topic","ref":"embeddings-vector-db"}},{"type":"linkCard","attrs":{"url":"/en/topics/rag","title":"RAG","description":"Answers grounded in your own documents instead of the model's memory","kind":"topic","ref":"rag"}},{"type":"linkCard","attrs":{"url":"/en/topics/evals","title":"Evaluation (evals)","description":"How to measure whether a prompt or model change really improved anything","kind":"topic","ref":"evals"}},{"type":"resourceRef","attrs":{"resourceId":"6b0854ad1a40d7e6c24c8ef3"}},{"type":"resourceRef","attrs":{"resourceId":"6b0854ad1a40d7e6c24c8ee4"}}]},"toc":[{"id":"the-problem-an-assistant-that-invents-allergens","text":"The problem: an assistant that invents allergens","level":2,"locked":false},{"id":"intuition-autocomplete-that-has-read-the-internet","text":"Intuition: autocomplete that has read the internet","level":2,"locked":false},{"id":"tokens-the-currency-of-language-models","text":"Tokens: the currency of language models","level":2,"locked":false},{"id":"the-context-window-everything-the-model-sees-at-once","text":"The context window: everything the model sees at once","level":2,"locked":false},{"id":"what-happens-inside-the-transformer-in-five-sentences","text":"What happens inside: the transformer in five sentences","level":2,"locked":false},{"id":"sampling-why-the-same-request-gives-different-answers","text":"Sampling: why the same request gives different answers","level":2,"locked":false},{"id":"your-first-api-call","text":"Your first API call","level":2,"locked":false},{"id":"streaming-the-answer-before-it-is-complete","text":"Streaming: the answer before it is complete","level":3,"locked":false},{"id":"where-the-model-knows-anything-from-training-stages","text":"Where the model \"knows\" anything from: training stages","level":2,"locked":false},{"id":"hallucinations-confident-but-untrue-text","text":"Hallucinations: confident but untrue text","level":2,"locked":false},{"id":"costs-simple-maths-big-numbers","text":"Costs: simple maths, big numbers","level":2,"locked":false},{"id":"when-an-llm-and-when-plain-code","text":"When an LLM, and when plain code","level":2,"locked":false},{"id":"pre-production-checklist","text":"Pre-production checklist","level":2,"locked":false},{"id":"test-yourself","text":"Test yourself","level":2,"locked":false},{"id":"what-s-next","text":"What's next","level":2,"locked":false}],"locked":false,"paywall":null,"previewRatio":0.3,"totalBlocks":75,"visibleBlocks":75,"resources":[{"id":"6b0857a73c96f2d34d0b3236","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=LPZh9BOjkQs","embedUrl":"https://www.youtube-nocookie.com/embed/LPZh9BOjkQs","title":"Large Language Models explained briefly","description":"","author":"3Blue1Brown","thumbnailUrl":"https://i.ytimg.com/vi/LPZh9BOjkQs/hqdefault.jpg","durationSec":null,"lang":"en","topics":["llm-fundamentals"],"techs":["general"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"seed","publishedAt":null,"popularity":0,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:39.665Z","updatedAt":"2026-11-26T16:00:39.665Z"},{"id":"6b0857a73c96f2d34d0b3230","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=zjkBMFhNj_g","embedUrl":"https://www.youtube-nocookie.com/embed/zjkBMFhNj_g","title":"[1hr Talk] Intro to Large Language Models","description":"","author":"Andrej Karpathy","thumbnailUrl":"https://i.ytimg.com/vi/zjkBMFhNj_g/hqdefault.jpg","durationSec":null,"lang":"en","topics":["llm-fundamentals"],"techs":["general"],"tags":[],"price":"free","featured":true,"featuredOrder":14,"packageName":null,"source":"seed","publishedAt":null,"popularity":0,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:39.248Z","updatedAt":"2026-11-26T16:00:39.248Z"},{"id":"6b0857c53c96f2d34d0b47bf","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=zduSFxRajkE","embedUrl":"https://www.youtube-nocookie.com/embed/zduSFxRajkE","title":"Let's build the GPT Tokenizer","description":"The Tokenizer is a necessary and pervasive component of Large Language Models (LLMs), where it translates between strings and tokens (text chunks). Tokenizers are a completely separate stage of the LLM pipeline: they have their own training sets, training algorithms (Byte Pair Encoding), and after…","author":"Andrej Karpathy","thumbnailUrl":"https://i.ytimg.com/vi/zduSFxRajkE/hqdefault.jpg","durationSec":null,"lang":"en","topics":["llm-fundamentals"],"techs":["general"],"tags":["llm","ai"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2024-02-20T17:11:35.000Z","popularity":91,"verifiedAt":"2026-11-26T10:55:28.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:07.480Z","updatedAt":"2026-11-26T16:01:07.480Z"},{"id":"6b0857b43c96f2d34d0b37fd","type":"article","provider":"web","url":"https://poloclub.github.io/transformer-explainer","embedUrl":null,"title":"Transformers Explained Visually","description":"An interactive visualization tool showing you how transformer models work in large language models (LLM) like GPT.","author":"poloclub.github.io","thumbnailUrl":"https://poloclub.github.io/transformer-explainer/preview/summary.png","durationSec":null,"lang":"en","topics":["llm-fundamentals"],"techs":["general"],"tags":["llm","ai","hacker-news"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"hn","publishedAt":"2026-09-21T19:43:49.000Z","popularity":81,"verifiedAt":"2026-11-26T11:17:51.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:51.221Z","updatedAt":"2026-11-26T16:00:51.221Z"},{"id":"6b0857a83c96f2d34d0b323b","type":"course","provider":"huggingface","url":"https://huggingface.co/learn/llm-course","embedUrl":null,"title":"LLM Course","description":"Free course on large language models with the Hugging Face ecosystem: transformers, datasets, tokenizers, fine-tuning and building LLM applications.","author":"Hugging Face","thumbnailUrl":"https://cdn-thumbnails.huggingface.co/social-thumbnails/learn/llm-course/chapter1/1.png","durationSec":null,"lang":"en","topics":["llm-fundamentals","fine-tuning","ai-in-python"],"techs":["python"],"tags":[],"price":"free","featured":true,"featuredOrder":1,"packageName":null,"source":"seed","publishedAt":null,"popularity":0,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:40.075Z","updatedAt":"2026-11-26T16:00:40.075Z"},{"id":"6b0857a73c96f2d34d0b3232","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=7xTGNNLPyMI","embedUrl":"https://www.youtube-nocookie.com/embed/7xTGNNLPyMI","title":"Deep Dive into LLMs like ChatGPT","description":"","author":"Andrej Karpathy","thumbnailUrl":"https://i.ytimg.com/vi/7xTGNNLPyMI/hqdefault.jpg","durationSec":null,"lang":"en","topics":["llm-fundamentals","fine-tuning"],"techs":["general"],"tags":[],"price":"free","featured":true,"featuredOrder":16,"packageName":null,"source":"seed","publishedAt":null,"popularity":0,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:39.419Z","updatedAt":"2026-11-26T16:00:39.419Z"}],"challenges":[],"attachments":[],"hasCode":true,"repoUrl":null,"series":[{"slug":"ai-path","title":"AI for developers","items":[{"slug":"llm-fundamentals","title":"LLM fundamentals: tokens, context windows and next-token prediction","current":true},{"slug":"prompt-engineering","title":"Prompt engineering: writing instructions a model will actually follow","current":false},{"slug":"embeddings-vector-db","title":"Embeddings and vector databases: searching by meaning","current":false},{"slug":"rag","title":"RAG: answers grounded in your own documents","current":false},{"slug":"tool-use","title":"Tool use: how a language model calls your application's functions","current":false},{"slug":"ai-agents","title":"AI agents: a model in a loop with tools – and when a plain workflow is enough","current":false},{"slug":"mcp","title":"MCP (Model Context Protocol): one standard for connecting AI to tools and data","current":false},{"slug":"evals","title":"Evaluating LLM applications (evals): tests for systems that are not deterministic","current":false},{"slug":"llm-ops","title":"LLMOps: model gateways, caching, limits, observability and costs in production","current":false},{"slug":"ai-guardrails","title":"Guardrails and security for LLM applications: prompt injection, data leaks and tool permissions","current":false},{"slug":"local-llms","title":"Local language models: Ollama, llama.cpp, vLLM, quantization and the real trade-offs","current":false},{"slug":"fine-tuning","title":"Fine-tuning language models: when it pays off, LoRA and QLoRA in practice","current":false},{"slug":"ai-coding-assistants","title":"AI coding assistants: from editor suggestions to an agent that opens pull requests","current":false}]}],"prev":null,"next":{"slug":"prompt-engineering","title":"Prompt engineering: writing instructions a model will actually follow"},"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":38}]}}