Quest Lab · White paper · November 2024

Inside generative AI. From tokens to agents.

November 2024By Muhammad Zohaib Iqbal, PhD7 min read

Summary

Most people meet generative AI through a chat window. Building with it requires a clearer picture of what sits behind that window. This paper explains, without heavy mathematics, how a large language model (LLM) is built, the ways organizations can use one, why retrieval-augmented generation (RAG) has become the standard way to bring in a company's own knowledge, how single models are giving way to composite systems of agents, and how prompt engineering turns an unreliable conversation into a dependable component.

What an LLM is

From a user's point of view, an LLM is surprisingly simple: a file of learned parameters and a small program that runs them. Underneath, it is a deep neural network trained to do one thing: predict the next token in a sequence. Everything else, from answering questions to writing code, emerges from doing that one thing extremely well over an enormous amount of text.

How an LLM is built

1. Data preparation. Building starts with vast amounts of text from books, websites, research papers and more. The scale has grown fast: GPT-3 was trained on a dataset of about 499 billion tokens (2020), Llama 1 on 1.4 trillion tokens and Llama 2 on 2 trillion (2023), and Llama 3 on 15 trillion (April 2024). Preparing that data involves:

  • Gathering, increasingly with the question of whether synthetic data can supplement human-written text.
  • Cleaning: removing noise such as HTML tags and unwanted patterns, filtering offensive language and personal data, removing duplicates to avoid overfitting, and standardizing formats for numbers, dates and times.
  • Sampling: balancing the dataset so no single domain, genre or style dominates, by down-sampling over-represented data and up-sampling under-represented data. The quality and diversity of the data directly decide how well the model handles different styles, contexts and domains.
  • Tokenization: breaking text into the units the model processes. Tokens can be words, parts of words or characters; "machine learning" might become "mach", "ine", "learn", "ing". Common methods include Byte Pair Encoding, Unigram and WordPiece. A model does not generate words, it generates tokens, one at a time.

2. Attention. The attention mechanism lets the model focus on the parts of the input that matter for the current prediction, rather than treating every word equally. It is how a model works out, for example, that "the cat" is the subject of "The cat sat on the mat."

3. Architecture. The architecture defines the number of layers, their size and how they connect. Modern LLMs use the transformer architecture, with layers of attention heads and feed-forward networks that learn complex patterns in language.

4. Pretraining. The model learns language patterns by predicting the next word (or filling in masked words) across the prepared data. This is the computationally intensive step that needs high-performance hardware.

5. The training loop. Data is fed through the model repeatedly, over many cycles (epochs), and the model adjusts its internal parameters, its weights and biases, to reduce prediction errors.

6. Evaluation. Every few epochs, the model is tested on validation data it has not seen, using measures such as perplexity, to make sure it generalizes rather than memorizes.

7. The foundation model. The saved weights hold everything the model has learned. The result is a foundation model: capable of general language understanding, but not yet tailored to specialized tasks such as generating code or understanding medical terminology.

Parameters, in perspective

Parameters are the values a model learns during training: the weights on each connection in the network, plus a bias for each node. Even a toy network with three inputs, two hidden layers of four nodes and one output has 41 parameters. Llama 2's largest version has 70 billion. Stored at two bytes each, that is about 140 GB for the model's weights alone.

Three ways to use an LLM

Organizations have three main options:

  1. Use a public or proprietary service, through its interface or its API.
  2. Run a custom LLM locally, on the organization's own hardware.
  3. Deploy a custom LLM and access it through an API.

Each has trade-offs in cost, control, privacy and capability. The right choice depends on the application.

Why RAG became the standard

Organizations want answers from their own knowledge: policies, procedures, minutes, emails, manuals. That knowledge is usually far larger than a model can hold in one prompt. Even generous context windows, such as 128,000 tokens, run out, and beyond them the model keeps no history.

Retrieval-augmented generation solves this by combining retrieval with generation. In simplified form:

  1. Extract the text from the organization's documents.
  2. Divide it into chunks. Chunk size and overlap matter: smaller chunks give more precise matches, larger ones keep more context, and overlap preserves meaning across boundaries. Chunks can be split by characters, recursively by structure, or by meaning.
  3. Create embeddings. Each chunk is converted into a vector of numbers, an embedding, that distills the essence of the text.
  4. Store the embeddings in a vector database.
  5. Analyze the query when a question arrives, and convert it into an embedding too.
  6. Retrieve the most relevant chunks by measuring the distance between vectors. Exact nearest-neighbor search is computationally expensive at scale, so systems use approximate nearest-neighbor methods that make a fast, good guess.
  7. Generate the answer from the retrieved chunks, so the model responds from the organization's own sources.

Frameworks such as LangChain automate each of these steps, with components for connecting to different LLMs, prompt templates, agents, retrieval, memory of past interactions, and callbacks for logging and monitoring.

From single models to composite AI systems

The field is moving from monolithic LLMs to compound AI systems. Instead of one model doing everything, an LLM interprets what the user wants and delegates tasks to other workers, called agents. An agent can be another LLM, a vision-language model, an AI tool such as an image generator, a model fine-tuned on particular data, or an ordinary API function that performs an action.

A useful way to think of agents is as autonomous workers in a company, each with a defined job. A content system might have one worker that answers from the organization's knowledge using RAG, a second that drafts a blog article, a third that sends emails and a fourth that posts to social media, all coordinated by a central model.

These agents can be built in code, with Python or Node.js and frameworks such as LangChain, or assembled in low-code platforms such as Flowise and LangFlow, with automation tools such as Zapier and Make connecting them to other systems.

Prompt engineering: five principles

A prompt is the text we give a model. Prompt engineering is the discipline of finding prompts that reliably produce useful results: systematic, carrying enough information, and giving comparable output every time. Without it, the same request can give very different answers.

Prompt engineering evolves with each generation of models, and old tricks stop mattering. One day the idea may matter more than its phrasing. We are not there yet, and laying out information and requirements clearly will always matter. Five principles cover most of what works:

  1. Give direction. Describe the desired style in detail or reference a relevant persona. Asking for product names for a one-size-fits-all shoe "in the style of" one famous inventor or another produces strikingly different results.
  2. Specify format. Define the rules and structure of the response. Output often feeds another task, so consistency is key; JSON is the most common choice for APIs.
  3. Provide examples. A few examples of the desired output steer the model better than paragraphs of description.
  4. Evaluate quality. Run the prompt many times, identify inconsistencies and errors, and test which changes improve results. It is systematic trial and error.
  5. Divide labor. Split complex goals into steps and chain them, so the response from one prompt becomes the input to the next prompt or agent.

Several further techniques help:

  • Explain like I am five, for clear explanations.
  • Least to most: start with a little information and expand step by step.
  • Clear instructions: "What's the best computer for video editing within a set budget?" beats "What's the best computer?"
  • Role prompting: ask the model to act in a specific role.
  • Meta prompting: use AI to help write the prompt.

Conclusion

Behind the chat window, generative AI is an engineering stack: data carefully prepared and tokenized, a transformer trained to predict the next token, a foundation model accessed through a service, locally or by API, and, increasingly, a system of agents that retrieve, analyze, generate and act. RAG brings in an organization's own knowledge, and prompt engineering makes the whole system dependable. Understanding these layers is the difference between using generative AI and building with it.

Quest is a frontier AI lab. This paper reflects our perspective as of November 2024.

Want to put an LLM to work on your own data?Tell us what you have and we'll talk through the options.
info@questlab.pk →