AI & Data18 November 20269 min read

From AI Prototype to Production — Part 3 of 10

Context is the product

Most wrong answers from a capable model are context failures: the wrong passage, stale state, too many tools or a summary that lost the evidence. Part 3 of From AI Prototype to Production sets out the context stack, a token budget with the arithmetic shown, and a selection matrix for RAG patterns, graphs, ontologies and SQL grounding.

#Context Engineering#RAG#Knowledge Graphs#AI Engineering#Production AI
A workbench holding a few loose glass blocks, connected by a cyan line to a large, orderly frame of lit modules with a small yellow status light, in a dark workshop over a faint map of southern Africa.

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.

The context stack for one model callLAYERWHERE IT COMES FROM AND HOW IT IS CONTROLLEDSystem rulesand policyVersioned in code. Stable, so itcan be cached. Owner: productTool definitionsOnly the tools this step may use.Names, descriptions, schemasRetrievedknowledgeRanked passages the user may see,each with a citation and versionCurrent casestateFacts from systems of record,fetched now, not rememberedRecent stepsand tool resultsThe last few turns in full.Older ones trimmed or clearedMemory andsummariesWritten by rule, with receiptspointing back to the evidenceThe questionWhat the user asked, plus whothey are and what they may doSTABLE AT THE TOP, MOST SPECIFIC AT THE BOTTOM
Every model call is assembled from these layers, and each one competes for the same limited budget of tokens. The two highlighted layers carry the facts the answer depends on, so they get the most budget and the strictest controls: retrieved knowledge is filtered by the user's permissions and cited, and current case state is read live from the system of record rather than from memory. Rules and tool definitions change rarely and sit first, so they can be cached.

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.

LayerTokensRule
System rules and policy1,500Versioned; placed first so it can be cached
Tool definitions2,500Only the three read tools this step may use
Current case state1,000Member option, date of service and claim lines, read live
Retrieved knowledge8,000Up to ten passages, filtered by effective date and access
Recent steps and tool results4,000Last two passes in full; older results cleared
Memory and summaries1,000Case notes written by rule, each linked to its source
Reserved for the model's output4,000Explanation plus structured fields
Headroom2,000For long member questions and translated text
Total per call24,0001,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

LayerTypical failureControl
System rulesRules buried in a long prompt and contradicted further downShort, versioned, tested rules; policy enforced in code, not only in text
Tool definitionsDozens of overlapping tools; the model picks the wrong oneFew tools per step, clear descriptions, load more only when needed
Retrieved knowledgeRight topic, wrong version or wrong audienceEffective-date and permission filters inside retrieval; citations
Current case stateFacts remembered from an earlier turn, now staleRead from the system of record each time it matters
Recent stepsOld tool results crowd out the questionClear or trim older results; keep references to them
Memory and summariesA summary drops the fact the decision rests onSummaries 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 signalSmallest pattern that fitsSwartberg question (illustrative)Do not use it when
One fact from well-structured text, coarse accessNaive RAG"What is the waiting period for a new member?"Versions, audiences or permissions differ
Facts that vary by version, audience or permissionAdvanced 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 corpusGraphRAG 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 foundAgentic 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 imagesMultimodal RAG"What did the scanned motivation letter say about the procedure?"Text extraction already captures what matters
Exact numbers, totals or current statusSQL 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.

NeedUseWhat it gives the modelSwartberg exampleWatch for
Shared meaningAn ontology or controlled vocabularyDefinitions, synonyms, allowed statesWhat "benefit option", "dependant" and "short-paid" mean, and which claim states existDefinitions with no business owner
Connections between thingsA knowledge graphEntities and typed relationshipsMember to dependants to providers to networksEntity resolution, which is most of the cost
Exact, current factsSQL against governed viewsNumbers and states from the system of recordRemaining limit, claim status, payment dateFree-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

  1. Name an owner and a source for each layer of the stack.
  2. Write a per-call token budget, measured per language you serve.
  3. Read facts that change, such as status, option and limits, from the system of record on each call.
  4. Filter retrieval by permission and effective date inside the search, not after it.
  5. Offer only the tools the step needs.
  6. Give every summary and memory entry a pointer back to its evidence.
  7. Map each class of question to the smallest pattern that meets its access, semantic and reasoning requirements.
  8. 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 rowEvidence from this partSwartberg state
Context/RAGContext stack with owners and budget; pattern chosen per question class; effective-date and access filters testedtested
DataSystems of record named for live case state; definitions owned; scanned sources identifiedhypothesis
EconomicsTokens per call measured by language; budget per layerhypothesis

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

Found this useful?

Share