Volume 13 · Chapter 2 — AI-Native Software Architecture & Agentic Engineering Handbook
LLM Architecture Fundamentals
2.1 Introduction
To design AI-native systems you need a working mental model of how large language models operate - not to build one, but to reason about their capabilities, limits, costs, and failure modes. An architect who understands tokens, embeddings, context windows, and the difference between grounding and retraining makes far better decisions about cost, latency, accuracy, and security. This chapter builds that model at the level an architect needs.
2.2 What an LLM Actually Does
At its core, an LLM predicts the next token given the preceding ones, trained on vast text. Everything it appears to “know” is patterns learned from that data, which has two consequences an architect must internalize: it has a knowledge cutoff and no access to your private or current data, and it can produce fluent, confident output that is wrong (hallucination). These limits are precisely what grounding patterns like RAG exist to address.
2.3 Transformers and Attention (Conceptually)
Modern LLMs use the transformer architecture, whose key innovation is self-attention: the model weighs the relationships between all tokens in the input, letting it capture context and long-range dependencies. You do not need the math to architect with LLMs, but the intuition matters - attention is why context quality drives output quality, and why what you put in the prompt so strongly shapes what comes out.
flowchart LR Text["Input text"] --> Tok["Tokenizer\n(text -> tokens)"] Tok --> Emb["Embeddings\n(tokens -> vectors)"] Emb --> Attn["Transformer layers\n(self-attention over context)"] Attn --> Next["Next-token prediction\n(one token at a time)"] Next --> Out["Generated text"]
2.4 Tokens, Context Windows, and Cost
LLMs process text as tokens (roughly word-fragments), and the context window is the maximum tokens the model can consider at once - prompt plus response. This is an architectural constraint with direct cost implications: you pay per token, latency grows with tokens, and the window bounds how much retrieved context and conversation history you can include. Managing the context budget - what to include, summarize, or retrieve - is a core AI-native design concern.
2.5 Embeddings and Semantic Search
Embeddings convert text into high-dimensional vectors where semantic similarity is geometric closeness. This enables meaning-based (semantic) search rather than keyword matching, and it is the foundation of RAG: you embed documents and the query, then retrieve the nearest vectors. Vector databases index these embeddings for fast similarity search at scale.
// Embeddings + similarity are the basis of retrieval. (Microsoft.Extensions.AI)
ReadOnlyMemory<float> q = await _embeddingGen.GenerateVectorAsync(userQuestion, ct);
var hits = await _vectorStore.SearchAsync(q, top: 5, ct); // nearest neighbors by meaning
// hits are semantically relevant chunks, even without keyword overlap.
2.6 Grounding: RAG vs Fine-Tuning
The two ways to give a model knowledge or behavior it lacks are fundamentally different. RAG (retrieval-augmented generation) injects relevant enterprise data into the prompt at query time - grounding answers in current, authoritative, access-controlled sources. Fine-tuning adjusts the model’s weights to change its behavior, style, or format. RAG is for knowledge (cheap to keep current, auditable, access-controlled); fine-tuning is for behavior (costly, static). Most enterprise value comes from RAG.
When would you choose RAG over fine-tuning, and can you combine them?
I choose based on whether I need to give the modelknowledgeor change itsbehavior, and they are complementary rather than competing. RAG is the right tool for injecting knowledge: when the application must answer from proprietary, frequently changing, or authoritative data with citations and per-user access control, RAG retrieves the relevant data at query time and puts it in the prompt. It is my default for enterprise knowledge because it keeps information current (you update the documents, not the model), is far cheaper than retraining, is auditable (you can cite sources), and lets you enforce access control at retrieval so users only see what they are entitled to. Fine-tuning is the right tool for changing behavior: teaching the model a consistent tone or style, a specific output format, or improved performance on a narrow, well-defined task - it adjusts the model’s weights, so it is costly to build, does not solve staleness or access control (the knowledge is baked in and frozen), and needs redoing as things change, so I use it sparingly and only for behavior, not facts. They combine well: a sophisticated enterprise assistant might use RAG to ground answers in current, access-controlled knowledge, light fine-tuning (or careful prompting) to shape its behavior and format, and an agentic layer to take actions - each solving a different problem. In an interview the crisp framing is: RAG for knowledge, fine-tuning for behavior, and reach for RAG first because most enterprise needs are about grounding in current proprietary data, which fine-tuning handles poorly and expensively.
Why do LLMs hallucinate, and how do you architect around it?
LLMs hallucinate because of what they fundamentally are: next-token predictors trained to produce fluent, plausible continuations of text, not databases of verified facts. They have no built-in notion of truth or of the boundary of their own knowledge, so when asked about something outside their training data, that is stale, or that they simply have not learned well, they generate a confident, well-formed answer that may be fabricated - the fluency is the same whether the content is right or wrong, which is what makes hallucination dangerous. You cannot eliminate it in the model, so you architect around it. The primary defense is grounding with RAG: retrieve relevant, authoritative enterprise data and instruct the model to answer only from that context and to say it does not know when the answer is not there - this dramatically reduces hallucination and, crucially, lets you cite sources so answers are verifiable. Beyond that, I add output validation and guardrails (checking claims against the retrieved context, constraining formats, verifying against systems of record for critical facts), keep a human in the loop for consequential decisions, and design the UX to present AI output as assistive and cite-backed rather than authoritative. I also evaluate hallucination rates continuously as part of quality monitoring rather than assuming the system is accurate. And for actions, I never let the model’s unverified output directly drive a consequential operation without validation. The principle is that trustworthiness is engineered around the model - grounding, citations, validation, and oversight - because the model itself will always be capable of confident fabrication.
Why does the context window matter architecturally, and how do you manage it?
The context window - the maximum number of tokens (prompt plus response) the model can consider at once - matters because it is simultaneously a capability limit and a cost/latency driver, and managing it is a core AI-native design task. Everything the model reasons about in a single call must fit in the window: the system instructions, any retrieved context, the conversation history, and the user’s input, plus room for the response. This creates real constraints: you cannot simply stuff an entire knowledge base or a long conversation into the prompt, and even where a large window exists, you pay per token and latency grows with token count, so filling the window is expensive and slow, and models can also attend less reliably to information buried in very long contexts. So I manage the context budget deliberately. For knowledge, rather than including everything, I use RAG to retrieve only the most relevant chunks for the query, which is both more accurate and far cheaper than a giant prompt. For conversation memory, I summarize or truncate older turns and keep salient facts in a compact form rather than replaying the whole history. I structure prompts to put the most important instructions and context where the model attends best, and I trim redundant content. I also treat token usage as an observable, monitored cost. In effect, the context window turns prompt construction into a resource-allocation problem - deciding what to retrieve, summarize, or drop to fit the most relevant information into a bounded, paid-for space - which is why retrieval, memory management, and prompt engineering are central to AI-native architecture rather than incidental details.
2.7 Banking Enterprise Scenario
A bank’s AI features are designed around these fundamentals. Because the model has a knowledge cutoff and no access to customer data, every answer that needs bank-specific or current information is grounded with RAG over approved documents, retrieving only the relevant chunks to respect the context budget and control token cost. Embeddings power semantic search over policies and FAQs; the prompt instructs the model to answer only from retrieved context and cite sources, curbing hallucination. Fine-tuning is reserved for shaping tone and format, not for knowledge - keeping information current and auditable through retrieval rather than frozen in weights.
Chapter Revision Notes
- LLMs predict next tokens - hence knowledge cutoffs, no private data, and hallucination.
- Attention means context quality drives output quality; the prompt shapes the answer.
- Tokens and the context window are cost/latency/capability constraints to budget deliberately.
- Embeddings enable semantic search - the foundation of RAG.
- RAG grounds knowledge (current, auditable, access-controlled); fine-tuning shapes behavior.