In one line An LLM only knows two things when it answers you: what it learned in training, and what is in its context window right now. Working well with LLMs is mostly about putting the right information into that window, in the right form.

How a chat request looks

When you use a chat app or an LLM API, your message is not sent alone. The application builds a list of messages, each with a role, and sends the whole list to the model every time.

RoleWritten byPurpose
systemThe developer of the appSets behaviour, persona, rules and background ("You are a helpful assistant for EUMETSAT data users…")
userThe personQuestions and instructions
assistantThe modelPrevious replies, sent back so the model "remembers" the conversation
toolThe applicationResults of tool or function calls (search results, database rows, calculations)
messages = [
    {"role": "system",    "content": "You are a concise assistant for satellite data questions."},
    {"role": "user",      "content": "What is a Level-1B product?"},
    {"role": "assistant", "content": "Calibrated, geolocated radiances at full resolution ..."},
    {"role": "user",      "content": "And Level-2?"}   # the model sees ALL of the above
]
LLMs are stateless The model itself keeps no memory between requests. A chatbot "remembers" earlier turns only because the app re-sends the history each time. "Memory" features in chat apps work by saving notes and inserting them into the context of later conversations.

The context window

The context window is the maximum number of tokens the model can process in one request: input and output together. Everything the model uses to answer must fit inside it.

What fills a context window: system prompt, tool definitions, retrieved documents, conversation history, current message and space for the answer Context window (e.g. 128,000 tokens) Systemprompt Tooldefinitions Retrieved documents,files, search results Conversation history(earlier turns) Newmsg Space forthe answer input tokens (you pay for these on every request) output tokens If input + output exceeds the window, the request fails or old content must be removed or summarised. Proportions are illustrative and vary by application.
Figure 1. The context window is shared by everything the model needs, including its own answer.

Context windows have grown quickly:

Model (release year)Context windowRoughly equals
GPT-3 (2020)2,048 tokens~1,500 words, a few pages
GPT-3.5 / ChatGPT (2022)4,096 tokens~3,000 words
GPT-4 (2023)8,192 / 32,768 tokens~6,000 / ~25,000 words
Claude 2.1 (2023)200,000 tokens~150,000 words, a long novel
Llama 3.1 (2024)128,000 tokens~96,000 words
Gemini 1.5 Pro (2024)1,000,000 tokens (later 2M)Several books, hours of transcripts, a whole codebase

Note that there is usually a separate, smaller limit on output tokens (often a few thousand to tens of thousands), so a model with a 200k window cannot necessarily write a 200k-token reply.

Thinking in a token budget

Treat the context window like a budget. A worked example for a 128,000-token window:

ItemTokens
System prompt with rules and examples2,000
Definitions of 10 tools3,000
A 40-page PDF report (~20,000 words)~27,000
Conversation so far (20 turns)12,000
Reserved for the answer4,000
Total used~48,000 (37%)

Because the whole context is re-sent on every turn, a long conversation gets slower and more expensive with each message. Many APIs offer prompt caching, which makes re-sending an unchanged prefix (such as a long system prompt or document) much cheaper and faster.

Long context pitfalls

A bigger window does not mean the model uses every part of it equally well. Liu et al. (2023), "Lost in the Middle", found that models were best at using information placed at the beginning or end of a long input and noticeably worse when the key fact was in the middle. Newer models have improved, but the general advice still holds.

U-shaped curve: accuracy is highest when relevant information is at the start or end of the context key fact buried in the middle Position of the relevant information in the context → startend Answer accuracy
Figure 2. Qualitative shape of the "lost in the middle" effect (Liu et al., 2023).
  • Context rot / distraction: irrelevant text lowers answer quality, even when the right fact is present.
  • Cost and latency grow with every input token.
  • Conflicting information in the context (old and new versions of a document) confuses the model.

Context engineering

Context engineering is the practice of deciding exactly what goes into the context window for each model call: instructions, examples, retrieved knowledge, tool results, memory and history. It is the broader successor to "prompt engineering", and it matters most for agents that run for many steps.

StrategyWhat it meansExample
SelectInclude only what is relevant to this stepRetrieve the 5 most relevant document chunks instead of pasting the whole manual (RAG)
CompressSummarise or trim what you keepReplace 50 old chat turns with a 300-token summary
OrderPut the most important material where the model uses it bestDocuments first, the question and instructions at the end
Write to memoryStore information outside the window and bring it back when neededSave a project's decisions in a notes file that is re-read later
IsolateSplit work so each call has a small, focused contextA sub-agent researches a question and returns only a short conclusion

Prompt engineering

A prompt is the input you give the model. Good prompts are clear and specific, the way a good brief to a new colleague is clear and specific. A useful structure:

Anatomy of a good prompt: role, task, context, examples, output format and constraints Role: You are an experienced IV&V engineer reviewing software requirements. Task: Check each requirement below for ambiguity and testability. Context: <requirements> REQ-001 The system shall respond quickly. … </requirements> Example: "respond quickly" → ambiguous; suggest "within 2 s for 95% of requests". Format: Return a table with columns: ID | Issue | Suggested rewrite. Constraints: Do not invent requirements. If a requirement is fine, write "OK".
Figure 3. Six building blocks of a clear prompt. Not every prompt needs all six.

Prompting techniques

TechniqueHowWhen it helps
Zero-shotJust ask, with clear instructionsSimple, common tasks
Few-shotInclude 2–5 input → output examplesWhen you need a specific format, style or labelling scheme
Chain-of-thoughtAsk the model to reason step by step before giving the final answerMaths, logic, multi-step problems (Wei et al., 2022). Reasoning models do this internally.
Role / persona"You are a senior data engineer…"Sets vocabulary, depth and tone
DelimitersWrap material in tags such as <document>…</document> or triple quotesSeparates instructions from data; reduces confusion and some injection risk
Ask for a format"Answer as JSON with keys …", "Use a table"When output is parsed by code or compared across runs
Prompt chainingSplit a big task into steps, each its own callLong or complex tasks; easier to debug each step
Self-check"Review your answer against the source and correct mistakes"Reduces errors when accuracy matters
Allow "I don't know""If the answer is not in the document, say so."Reduces made-up answers
Practical tips
  • Say what you want, not only what to avoid.
  • Explain why (the purpose and audience); models use the reason to fill in details sensibly.
  • For long documents, put the document first and the question last.
  • Test prompts on several real inputs, not just one, and keep the versions that work.

Hallucinations & grounding

A hallucination is output that sounds confident and fluent but is false or unsupported: an invented citation, a non-existent API function, a wrong date. It happens because the model is trained to produce plausible text, and a plausible-looking answer is not always a true one.

CauseMitigation
The fact is not in the training data, or is after the training cutoffProvide the source in the context (RAG, file upload, web search tool)
Rare facts (exact numbers, names, citations) are poorly memorisedAsk for quotes from the provided source; verify citations
The prompt pressures the model to always answerExplicitly allow "I don't know" or "not found in the document"
Calculation or counting in textGive the model a code or calculator tool
Long, cluttered contextContext engineering: retrieve less, but more relevant, text
High temperature for factual tasksUse a low temperature for extraction and Q&A

Grounding means tying the answer to specific, provided evidence, ideally with citations to the exact passage, so that a human can check it.

Structured output

When code needs to use the answer, ask for a structured format such as JSON. Many APIs and local runtimes (for example Ollama's format parameter) can enforce a JSON Schema, so the output is guaranteed to parse.

# Ask for structured output that matches a schema
schema = {
    "type": "object",
    "properties": {
        "satellite":   {"type": "string"},
        "launch_year": {"type": "integer"},
        "instruments": {"type": "array", "items": {"type": "string"}}
    },
    "required": ["satellite", "launch_year", "instruments"]
}
# Model reply (parsed with json.loads):
# {"satellite": "Sentinel-3A", "launch_year": 2016, "instruments": ["OLCI", "SLSTR", "SRAL"]}
Valid is not the same as correct A schema guarantees the shape of the answer, not that the values are true. Still validate the values.

Tool (function) calling

Tool calling lets an LLM use external functions: search the web, query a database, run code, call an API. The model does not run the tool itself. It outputs a structured request ("call get_weather with city="Darmstadt""), the application runs it, and the result is sent back to the model.

Sequence diagram of a tool call between user, application, LLM and tool User Application LLM Tool / API 1. "Weather in Darmstadt?" 2. messages + tool definitions(name, description, JSON schema) 3. tool_call: get_weather{"city": "Darmstadt"} 4. app runs the function (checks permissions) 5. {"temp_c": 7, "sky": "cloudy"} 6. tool result added to messages 7. "It is 7 °C and cloudy." 8. final answer
Figure 4. The model chooses the tool and its arguments; the application executes it.

Each tool is described to the model with a name, a plain-language description of when to use it, and a JSON Schema for its arguments. Clear descriptions matter as much as a clear prompt. Tool calling is the building block of AI agents and of the Model Context Protocol.

Choosing settings

TaskTemperatureOther tips
Data extraction, classification, Q&A over documents0 – 0.2Structured output; allow "not found"
Code generation0 – 0.3Run tests on the result
Summaries, explanations, emails0.3 – 0.7Specify audience and length
Brainstorming, creative writing0.7 – 1.0+Ask for several options

These are common starting points, not rules; defaults and sensible ranges differ between providers, and some reasoning models fix the temperature. Change temperature or top-p, usually not both. See Temperature, top-k, top-p for what these settings do.

Key terms

  • Context windowMaximum tokens (input + output) per request.
  • System promptDeveloper instructions that frame every conversation.
  • Few-shotGiving examples of the desired input → output inside the prompt.
  • Prompt cachingRe-using an unchanged prompt prefix to cut cost and latency.
  • HallucinationFluent output that is false or unsupported.
  • GroundingBasing the answer on provided, citable evidence.
  • JSON SchemaA standard way to describe the required structure of JSON data.
  • Tool callingThe model requests that the app run a function with given arguments.

Common misconceptions

MisconceptionReality
"The chatbot learns from my corrections."Only within the current context. The weights do not change (although providers may use conversations for future training, depending on their terms and your settings).
"A 1M-token window means I can paste everything."You can, but quality, cost and speed usually improve if you include only what is relevant.
"There are magic words that make prompts work."Clarity, context and examples matter far more than special phrases.
"If it cites a source, the source exists."Citations can be hallucinated too. Check them.

Next: combine these pieces into complete applications in Building AI systems.

References

Books

  • AI Engineering: Building Applications with Foundation Models — Chip Huyen (O'Reilly, 2025)
  • Prompt Engineering for LLMs — John Berryman, Albert Ziegler (O'Reilly, 2024)
  • Hands-On Large Language Models — Jay Alammar, Maarten Grootendorst (O'Reilly, 2024)

Some other interesting things to know: