Three weeks into production, the bounded agent at Swartberg Health Administrators, our fictional South African medical scheme administrator, told a contact-centre agent that a member's physiotherapy claim had been paid correctly against her annual limit. It had not. The retrieved passage was the right benefit rule for the wrong year. The member's option had changed in January, the index still ranked last year's schedule highest, and nothing in the context said which schedule applied on the date of service. The model reasoned perfectly from what it was given.
That is the usual shape of a production failure. The model is rarely the weakest link. The context is: what was put in front of the model, in what order, from which source, with which permissions and at what freshness. Part 2 showed that every pass round an agent loop resends a transcript. This part is about engineering what goes into it.
Tokens set the budget for everything
Models read and write tokens, which are pieces of text produced by a tokenizer: often a whole short word, sometimes a fragment of a longer one, a number or a punctuation mark. The context window, the price of a call and much of its latency are all measured in tokens. Tool definitions count too: Anthropic's tool use documentation (checked on 18 November 2026) lists the tool names, descriptions and schemas in the request, and the tool-use and tool-result blocks, as billable input.
Token counts are not neutral across languages. Petrov and colleagues (NeurIPS 2023) found that the same text translated into different languages can tokenize to very different lengths, with differences of up to 15 times in some cases, and that the gap persists in tokenizers built for multilingual use. For a South African service that answers in isiXhosa, isiZulu, Sesotho or Afrikaans as well as English, the cost per answer and the room left in the context window can differ by language. Measure it on your own text with your provider's tokenizer before you set budgets.
More tokens also do not mean better answers. Anthropic's engineering guide to context engineering (29 September 2025) calls context "a finite resource with diminishing marginal returns" and describes recall falling as context grows. It defines context engineering as "the set of strategies for curating and maintaining the optimal set of tokens (information) during LLM inference." That is the discipline this part describes.
The context stack
Every model call is assembled from the same layers. Treat each as a component with an owner, a source and a budget.
A context budget makes the trade-offs explicit. Here is the per-call budget Swartberg set for its short-payment agent after the incident. The figures are illustrative, not recommendations.
| Layer | Tokens | Rule |
|---|---|---|
| System rules and policy | 1,500 | Versioned; placed first so it can be cached |
| Tool definitions | 2,500 | Only the three read tools this step may use |
| Current case state | 1,000 | Member option, date of service and claim lines, read live |
| Retrieved knowledge | 8,000 | Up to ten passages, filtered by effective date and access |
| Recent steps and tool results | 4,000 | Last two passes in full; older results cleared |
| Memory and summaries | 1,000 | Case notes written by rule, each linked to its source |
| Reserved for the model's output | 4,000 | Explanation plus structured fields |
| Headroom | 2,000 | For long member questions and translated text |
| Total per call | 24,000 | 1,500 + 2,500 + 1,000 + 8,000 + 4,000 + 1,000 + 4,000 + 2,000 |
The incident fix was not a better prompt. It was two changes to the stack: the member's option and date of service moved into current case state, read from the administration system on every call, and retrieval filtered benefit schedules by effective date before ranking.
What goes wrong in each layer
| Layer | Typical failure | Control |
|---|---|---|
| System rules | Rules buried in a long prompt and contradicted further down | Short, versioned, tested rules; policy enforced in code, not only in text |
| Tool definitions | Dozens of overlapping tools; the model picks the wrong one | Few tools per step, clear descriptions, load more only when needed |
| Retrieved knowledge | Right topic, wrong version or wrong audience | Effective-date and permission filters inside retrieval; citations |
| Current case state | Facts remembered from an earlier turn, now stale | Read from the system of record each time it matters |
| Recent steps | Old tool results crowd out the question | Clear or trim older results; keep references to them |
| Memory and summaries | A summary drops the fact the decision rests on | Summaries with receipts that point back to the evidence |
Two patterns from current practice help with the middle rows. Anthropic's guide describes just-in-time retrieval, where the agent holds lightweight references such as file paths or stored queries and loads content only when it needs it, and compaction, which summarises a long transcript to start a fresh window. Microsoft's agentic AI design patterns catalogue (preview, checked on 18 November 2026) includes progressive tool and skill loading, which starts with a small index of tools and reveals schemas in tiers. CloudNala's context trimming without losing the evidence covers the risk in compaction: trimming the evidence a decision depends on.
Choose the retrieval pattern by requirement, not by rank
Retrieval-augmented generation (RAG) fills the retrieved-knowledge layer. Part 4 of The Enterprise AI Control Plane, RAG is a data product, compares five patterns by best fit and main limitation. This matrix answers a different question: given what a question requires, which pattern is the smallest that can meet it? Score each question on three requirements:
- Access: how finely does visibility vary? By collection, by document, by member or by field?
- Semantics: does the answer depend on shared definitions and entity identity, or only on finding similar text?
- Reasoning: is it a single fact, a comparison across records, a corpus-wide pattern, a multi-step investigation, or does the evidence sit in tables, scans or images?
| Requirement signal | Smallest pattern that fits | Swartberg question (illustrative) | Do not use it when |
|---|---|---|---|
| One fact from well-structured text, coarse access | Naive RAG | "What is the waiting period for a new member?" | Versions, audiences or permissions differ |
| Facts that vary by version, audience or permission | Advanced RAG: hybrid search, filters, reranking | "Which physiotherapy limit applied on 14 March for this option?" | The answer needs relationships across many records |
| Relationships between entities, or themes across the whole corpus | GraphRAG or a curated knowledge graph | "Which providers in this network appear in complaints about the same tariff code?" | Questions are local lookups; graph upkeep has no owner |
| The next search depends on what the last one found | Agentic RAG, bounded | "Reconstruct why this pre-authorisation was declined across three systems" | A fixed sequence of queries would do |
| Evidence in tables, scans, forms or images | Multimodal RAG | "What did the scanned motivation letter say about the procedure?" | Text extraction already captures what matters |
| Exact numbers, totals or current status | SQL grounding, not RAG | "How much of her annual limit is left?" | The source has no governed schema |
Several notes on the matrix. The original research labels differ: Gao and colleagues' survey groups systems into naive, advanced and modular RAG. GraphRAG, as described by Edge and colleagues, targets questions about a whole corpus that conventional vector retrieval handles poorly, at real indexing cost. Agentic RAG embeds agents in the retrieval pipeline so that it is no longer a fixed sequence, as the survey by Singh and colleagues describes; every control from Part 2 then applies to retrieval. CloudNala's multimodal RAG is an information-architecture problem explains routing by modality.
One Swartberg journey used three patterns. The limit question went to SQL, the benefit rule to advanced RAG, and the scanned motivation to a multimodal extraction step that runs at ingestion. None of them is "better". Each matches a requirement.
Ontology, knowledge graph or SQL: three different jobs
These three are often lumped together as "structured grounding". They solve different problems.
| Need | Use | What it gives the model | Swartberg example | Watch for |
|---|---|---|---|---|
| Shared meaning | An ontology or controlled vocabulary | Definitions, synonyms, allowed states | What "benefit option", "dependant" and "short-paid" mean, and which claim states exist | Definitions with no business owner |
| Connections between things | A knowledge graph | Entities and typed relationships | Member to dependants to providers to networks | Entity resolution, which is most of the cost |
| Exact, current facts | SQL against governed views | Numbers and states from the system of record | Remaining limit, claim status, payment date | Free-form generated SQL against raw tables |
An ontology does not have to be a heavy academic artefact. CloudNala's ontologies without the academic fog starts with questions, not the domain. When you need a knowledge graph gives a ladder from simple joins to a graph database. The series Enterprise Knowledge Architecture Beyond Basic RAG covers both in depth.
SQL grounding deserves a caution. Letting a model write SQL against production tables looks easy in a demo. The BIRD benchmark (Li and colleagues, NeurIPS 2023) was built because real databases have messy values and need business knowledge that table names do not carry. At publication the best model it tested reached 40.08% execution accuracy against 92.96% for people. Models have improved since, but the lesson about messy values and business knowledge still applies. For exact facts that a member's money depends on, expose governed views or parameterised queries as tools, and let the model choose the tool, not write the query.
The South African version
Three local conditions shape context engineering.
- Language changes the budget. Members write in many languages and switch between them. Test the token cost and the retrieval quality per language on real, consented samples, and set headroom accordingly.
- Scans are normal. Clinical motivations, referral letters and older scheme rules often arrive as scans or photographs. Their extraction quality sets the ceiling for every answer that depends on them.
- Special personal information travels with context. Retrieved passages and case state can contain health information, which section 26 of POPIA treats as special personal information. Minimising what enters each layer is a privacy control as well as a cost control. This is general information, not legal advice.
Context review checklist
- Name an owner and a source for each layer of the stack.
- Write a per-call token budget, measured per language you serve.
- Read facts that change, such as status, option and limits, from the system of record on each call.
- Filter retrieval by permission and effective date inside the search, not after it.
- Offer only the tools the step needs.
- Give every summary and memory entry a pointer back to its evidence.
- Map each class of question to the smallest pattern that meets its access, semantic and reasoning requirements.
- Use governed views or parameterised queries, not free-form SQL, for exact facts.
Scorecard contribution
This part supplies evidence for three rows of the Production Readiness Scorecard in Part 1. The states for Swartberg are illustrative.
| Scorecard row | Evidence from this part | Swartberg state |
|---|---|---|
| Context/RAG | Context stack with owners and budget; pattern chosen per question class; effective-date and access filters tested | tested |
| Data | Systems of record named for live case state; definitions owned; scanned sources identified | hypothesis |
| Economics | Tokens per call measured by language; budget per layer | hypothesis |
Next: Part 4, RAG at real scale. Previous: Part 2, How an AI agent actually works. All parts are on the series page.
How CloudNala can help
CloudNala runs context engineering reviews on live or near-live AI services. We trace failed answers back to the layer that caused them, write a per-call context budget with measured token costs for the languages you serve, map your question classes to the smallest retrieval or grounding pattern that fits, and replace free-form database access with governed tools. You leave with a context design your product owner can own and your engineers can test.
Work with CloudNala
CloudNala helps organisations move from technology ambition to practical execution across cloud, AI, data, platform engineering and digital services.
Whether you are exploring AI, modernising your cloud environment, building a public-sector digital service, or turning an idea into a working MVP, we can help you shape the roadmap and deliver the next step.
Book a Context Engineering Review or write to us at consult@cloudnala.co.za
