Working with LLMs
- 1. Foundations of AI
- 2. NLP
- 3. How LLMs work
- 4. Working with LLMs
- 5. Building AI systems
- 6. Practical & responsible AI
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.
| Role | Written by | Purpose |
|---|---|---|
| system | The developer of the app | Sets behaviour, persona, rules and background ("You are a helpful assistant for EUMETSAT data users…") |
| user | The person | Questions and instructions |
| assistant | The model | Previous replies, sent back so the model "remembers" the conversation |
| tool | The application | Results 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
]
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.
Context windows have grown quickly:
| Model (release year) | Context window | Roughly 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:
| Item | Tokens |
|---|---|
| System prompt with rules and examples | 2,000 |
| Definitions of 10 tools | 3,000 |
| A 40-page PDF report (~20,000 words) | ~27,000 |
| Conversation so far (20 turns) | 12,000 |
| Reserved for the answer | 4,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.
- 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.
| Strategy | What it means | Example |
|---|---|---|
| Select | Include only what is relevant to this step | Retrieve the 5 most relevant document chunks instead of pasting the whole manual (RAG) |
| Compress | Summarise or trim what you keep | Replace 50 old chat turns with a 300-token summary |
| Order | Put the most important material where the model uses it best | Documents first, the question and instructions at the end |
| Write to memory | Store information outside the window and bring it back when needed | Save a project's decisions in a notes file that is re-read later |
| Isolate | Split work so each call has a small, focused context | A 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:
Prompting techniques
| Technique | How | When it helps |
|---|---|---|
| Zero-shot | Just ask, with clear instructions | Simple, common tasks |
| Few-shot | Include 2–5 input → output examples | When you need a specific format, style or labelling scheme |
| Chain-of-thought | Ask the model to reason step by step before giving the final answer | Maths, 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 |
| Delimiters | Wrap material in tags such as <document>…</document> or triple quotes | Separates 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 chaining | Split a big task into steps, each its own call | Long 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 |
- 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.
| Cause | Mitigation |
|---|---|
| The fact is not in the training data, or is after the training cutoff | Provide the source in the context (RAG, file upload, web search tool) |
| Rare facts (exact numbers, names, citations) are poorly memorised | Ask for quotes from the provided source; verify citations |
| The prompt pressures the model to always answer | Explicitly allow "I don't know" or "not found in the document" |
| Calculation or counting in text | Give the model a code or calculator tool |
| Long, cluttered context | Context engineering: retrieve less, but more relevant, text |
| High temperature for factual tasks | Use 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"]}
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.
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
| Task | Temperature | Other tips |
|---|---|---|
| Data extraction, classification, Q&A over documents | 0 – 0.2 | Structured output; allow "not found" |
| Code generation | 0 – 0.3 | Run tests on the result |
| Summaries, explanations, emails | 0.3 – 0.7 | Specify audience and length |
| Brainstorming, creative writing | 0.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
| Misconception | Reality |
|---|---|
| "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
Papers
- N. F. Liu et al. (2023). Lost in the Middle: How Language Models Use Long Contexts. TACL 2024.
- J. Wei et al. (2022). Chain-of-Thought Prompting Elicits Reasoning in Large Language Models.
- T. Kojima et al. (2022). Large Language Models are Zero-Shot Reasoners ("Let's think step by step").
- L. Huang et al. (2023). A Survey on Hallucination in Large Language Models.
- T. Schick et al. (2023). Toolformer: Language Models Can Teach Themselves to Use Tools.
Guides
- Anthropic: Prompt engineering overview
- OpenAI: Prompt engineering guide
- Prompt Engineering Guide (DAIR.AI)
- Anthropic: Effective context engineering for AI agents
- JSON Schema: Getting started
- Ollama API (structured outputs and tool calling with local models)
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:
- Visit my pages on Machine learning & Deep learning
- Visit my website on Data engineering
- Visit my website on Data, Big Data, Data-modeling, Datawarehouse, SQL, cloud-compute.