AI Engineering and Data Analysis · Course book
Chapter 2: How AI Systems Are Engineered
An AI engineer's job is to turn models into dependable products. That requires understanding the models well enough to choose and use them sensibly, from classic machine learning through deep learning to large language models, and also knowing the techniques that make language models useful in practice: retrieval-augmented generation, which connects a model to your own documents, and agents, which let a model take actions using tools. This chapter builds that picture layer by layer. It explains how a model learns from data and how to tell when it has learned too much, what neural networks and transformers do, how text becomes numbers that capture meaning, how a retrieval-augmented system answers questions from private documents, and how agents plan and call tools. A worked example calculates the similarity between pieces of text the way a search system does.
How models learn from data
In supervised learning, a model learns from examples that come with the right answer, called labels: house details with their sale prices, or emails marked as spam or not. If the answer is a number, the task is regression; if it is a category, it is classification. In unsupervised learning there are no labels, and the model looks for structure on its own, for example grouping customers with similar buying habits into clusters.
Training works by adjusting the model's internal numbers, its parameters, to reduce a loss, a single number measuring how wrong its predictions are on the training data. The standard method, gradient descent, calculates which direction each parameter should move to reduce the loss and takes a small step that way, repeating many thousands of times. One complete pass through the training data is an epoch.
A model that simply memorises its training data is useless on new data, a failure called overfitting. To detect it, part of the data is held back as a validation set that the model never trains on. While the model is genuinely learning, the loss falls on both sets. When it starts memorising, the training loss keeps falling but the validation loss turns upward. The usual remedy is to stop training at the lowest validation loss, called early stopping, or to add more data or regularisation.
Neural networks, language and transformers
A neural network is built from layers of simple units. Each unit multiplies its inputs by weights, adds them up, and passes the result through a non-linear function. Stacking many layers lets the network build up complex features from simple ones: in an image network, early layers detect edges, middle layers shapes, and later layers whole objects. Training adjusts all the weights by gradient descent, using an algorithm called backpropagation to work out each weight's share of the error.
Language needs special handling because computers work with numbers. Text is first split into tokens, words or pieces of words, and each token is mapped to an embedding, a list of numbers learned during training in which tokens with similar meanings end up close together. Natural language processing tasks such as sentiment analysis, translation and question answering all start from these representations.
The transformer architecture, introduced in 2017, is the basis of today's large language models. Its key mechanism, attention, lets every token look at every other token in the input and decide which ones matter for its meaning, so "bank" can be read differently in "river bank" and "bank loan". A large language model is a transformer trained on vast amounts of text to predict the next token. Scaled up, this simple objective produces models that can summarise, translate, write code and answer questions, though they can also state false things fluently, a problem known as hallucination.
Turning a raw next-token predictor into a helpful assistant takes further stages. Pretraining on broad text gives the model its general knowledge of language. Instruction tuning then trains it on examples of requests paired with good responses, so that it follows instructions rather than simply continuing text. Finally, reinforcement learning from human feedback and related methods use people's comparisons between alternative answers to push the model towards responses that are more helpful, honest and safe. When you choose a model for an application, you are choosing the result of all three stages, along with its size, speed, cost and context window.
Embeddings, similarity and retrieval
Whole sentences and documents can also be turned into embeddings. Texts with similar meanings produce vectors pointing in similar directions, even when they share no words. Similarity is usually measured with cosine similarity: the dot product of the two vectors divided by the product of their lengths. It ranges from 1 for vectors pointing the same way, through 0 for unrelated directions, to −1 for opposite directions.
Retrieval-augmented generation, or RAG, uses this idea to let a language model answer questions about documents it was never trained on, such as a company's policies. In advance, the documents are split into chunks, each chunk is embedded, and the vectors are stored in a vector database. When a question arrives, it is embedded too, the most similar chunks are retrieved, and they are placed in the prompt with an instruction to answer using only that material and to cite it. Because the answer is grounded in retrieved text, hallucination drops, the sources can be shown to the user, and updating the knowledge means re-indexing documents rather than retraining a model.
| Approach | What changes | Best for | Main drawback |
|---|---|---|---|
| Prompt engineering | Only the instructions | Format, tone and simple tasks | Limited to what the model already knows |
| RAG | The context supplied with each question | Answering from private or changing documents | Only as good as the retrieval step |
| Fine-tuning | The model's weights, using extra training | A consistent style or specialised task | Needs good training data and costs more to update |
Agents and putting it into production
An AI agent is a language model placed in a loop where it can act. It is given a goal and a set of tools, functions it may call such as searching the web, querying a database or sending an email. At each step the model decides which tool to use and with what inputs, the application runs the tool and returns the result, and the model decides what to do next until the goal is met. Frameworks such as LangChain, and standards such as the Model Context Protocol, make it easier to describe tools to a model and connect it to many systems. Several agents with different roles can also cooperate, one planning and others carrying out sub-tasks.
Agents are powerful but need guard rails. Each tool should have the narrowest permissions possible, actions with real consequences such as payments or deletions should require human approval, and every step should be logged so that mistakes can be traced. More generally, AI systems in production need what any software needs, plus more: automated evaluation on a fixed set of test questions so that changes can be compared, monitoring of cost, speed and quality, and protection against prompt injection, where text inside a document or web page tries to give the model new instructions.
Evaluation deserves particular care because language model output varies. A practical evaluation set contains a few dozen to a few hundred realistic questions, each with the facts a good answer must contain. Each new prompt, model or retrieval setting is run against the whole set and scored, by simple checks where possible, such as whether the right document was retrieved or the answer contains the correct figure, and by human review or a second model for qualities such as clarity. Comparing scores before and after every change turns "it seems better" into evidence, and catches changes that fix one problem while quietly breaking another.
Practice tasks
- State whether each is regression, classification or clustering: predicting tomorrow's temperature, sorting photos into cats and dogs, grouping news articles by topic.
- In Figure 2.1, explain why the model from epoch 10 would perform worse on new data than the one from epoch 6.
- Calculate the cosine similarity between (3, 0, 4) and (0, 5, 0), and between (3, 0, 4) and (6, 0, 8).
- Describe the steps a RAG system follows from the moment a user asks a question to the moment an answer appears.
- A company wants a chatbot that answers from its 300-page staff handbook, which changes every month. Would you choose fine-tuning or RAG? Explain.
- List three safeguards you would add before letting an agent send emails on a user's behalf.
This course book is available to read online only at chrysolites.org.