AI Fundamentals

This page follows one request from text on the screen to generated text. The running example is:

"Hello, this is Gary"

1. The request at a glance

text
  → tokenizer
  → token IDs
  → internal token-embedding lookup
  → transformer and attention
  → next-token logits
  → softmax probabilities
  → decoding selects one token ID
  → append and repeat
  → detokenize / stream text

2. Text becomes tokens and token IDs

Illustrative tokenization:

"Hello, this is Gary"
          ↓ tokenizer
["Hello", ",", " this", " is", " Gary"]
          ↓ vocabulary lookup
[882, 11, 341, 291, 9281]

3. Token IDs become internal vectors

token ID 882
      ↓ embedding lookup
[0.83, 0.17, -0.31, ...]

Important boundary:

3.1 The model pipeline is coupled

                    MODEL / CHECKPOINT
                           │
          ┌────────────────┼────────────────┐
          ↓                ↓                ↓
 tokenizer/vocabulary  embedding table  transformer weights
          │                │                │
     token IDs       learned vectors   contextual processing
          └────────────────┼────────────────┘
                           ↓
                  vocabulary logits
                           ↓
                  matching detokenizer

4. Prefill processes the prompt

"Hello, this is Gary"
          ↓
[882, 11, 341, 291, 9281]
          ↓ embedding lookup
[vector, vector, vector, vector, vector]
          ↓
transformer prefill

5. The transformer makes tokens contextual

Engineering mental model:

initial token vectors
        ↓
attention: gather relevant context
        ↓
feed-forward: transform each position
        ↓
residual + normalization
        ↓
repeat through many layers
        ↓
contextual representation used for next-token prediction

6. Contextual representation becomes the next token

Illustrative first assistant-token candidates:

Token Logit Probability after decoding controls
"Hello" 8.4 47%
"Hi" 7.9 28%
"Nice" 7.2 14%
other tokens 11%

7. Output generation is autoregressive

The input/output distinction is fundamental:

prompt context
      ↓
predict token ID for "Hello"
      ↓ append to context
predict token ID for " Gary"
      ↓ append to context
predict token ID for "!"
      ↓ append to context
predict end-of-sequence

8. Token IDs become text again

3912 → "Hello"
9281 → " Gary"
   0 → "!"
        ↓ detokenize
"Hello Gary!"

9. Conversation, context, and context window

The application may build context from:

system/developer instructions
+ previous user messages
+ previous assistant messages
+ retrieved documents
+ tool definitions and tool results
+ current user message
+ space reserved for generated output
Application assembling runtime context from instructions, history, RAG evidence, tools, and a user question before one LLM call
🧩 Runtime context: application inputs become one LLM request
MAX_CONTEXT_TOKENS = 128_000  # illustrative model limit
model_parameters = load_learned_weights()

def llm_call(input_tokens, max_output_tokens):
    assert len(input_tokens) + max_output_tokens <= MAX_CONTEXT_TOKENS
    running_context = list(input_tokens)

    for _ in range(max_output_tokens):
        logits = model_forward(model_parameters, running_context)
        next_token_id = decode(logits)
        running_context.append(next_token_id)
        yield detokenize(next_token_id)
        if is_stop_token(next_token_id):
            break

9.1 A 1,000-token calculation

The diagram used 128K to show the boundary. Shrink it to 1,000 tokens to make the same capacity calculation easier to follow:

input context tokens + generated output tokens ≤ context window

Each call is independent, but resending selected conversation history usually makes later input contexts larger:

CALL 1 — independent request
Input context: [system + user] = 15 tokens
Output:                              8 tokens
Total used:                   15 + 8 = 23 / 1,000
Unused capacity:            1,000 - 23 = 977 tokens
Application stores the 8-token assistant response.

CALL 2 — new independent request
Input context:
[system + previous user + previous assistant + new user] = 29 tokens
Theoretical output headroom:                    1,000 - 29 = 971 tokens
Application stores the new response.

CALL 3 — new independent request
Input context:
[previous context + previous response + new message] = 43 tokens
Theoretical output headroom:                    1,000 - 43 = 957 tokens
available output budget = minimum of:
  configured max output tokens
  model/provider output limit
  context window - input context tokens
Conversation history stored by an application and rebuilt into independent LLM calls
💬 Conversation history and independent context windows

10. Training, fine-tuning, and inference

Fictional thought experiment: assume the base model was trained before Apple Inc. existed, so its weights strongly associate Apple → fruit.

Approach What changes? Result
Prompt Add “Apple means the technology company” to this request. The model can follow that meaning for this request; weights do not change.
RAG Retrieve current Apple documents into this request’s context. The model can answer from supplied evidence; weights do not change.
Fine-tuning Train further on many representative Apple examples. Weights change, making terminology and behavioural associations more consistent.
New pretraining Train a new base model on newer broad data containing Apple Inc. Apple-company associations become part of base training.
old model weights: Apple → mostly fruit
                         +
request context: Apple Inc. is a technology company ...
                         ↓
transformer processes question + current context
                         ↓
answer: Apple is a technology company ...

10.1 Apply it: an Apple support assistant

Apple now builds a support assistant for Gary’s device repair. Apple wants the assistant to behave consistently, but the surrounding application—not the model—must enforce security and transactions.

Need Example Use
Behaviour Apple wants the assistant to call service requests Repairs, use its support tone, and follow its classification conventions. Prompt first → fine-tuning if stronger consistency is needed
Knowledge Gary asks, “Does my battery qualify for service under today’s support policy?” RAG retrieves the current policy
Live state Gary asks, “What is the current status of Repair #123?” API/tool reads the repair system
Identity The application must verify that the signed-in caller is Gary. Authentication
Authorization The application must decide whether Gary may view or approve Repair #123. Authorization / IAM
Transaction integrity After Gary confirms, create one replacement order—even if the request is retried. Deterministic application/database logic
Gary signs in → authenticate → authorize Repair #123
              → retrieve current policy with RAG
              → read live repair status through an API
              → assistant explains the result
Gary confirms → application creates one replacement order transactionally

For deeper treatment, see AI Knowledge Bases, AI Agents, and AI Infrastructure and Evaluation.

11. Hallucination, grounding, and structured output

Fictional example:

Question: "Who is the CEO of Glucolte?"
Trusted evidence in this request: none

After "The CEO of Glucolte is ..."
illustrative next-token probabilities:
  "Gary"     38%
  "John"     21%
  "Michael"  12%
  ...

Generated answer: "The CEO of Glucolte is Gary Lu."
learned weights + supplied context
               ↓
next-token probability distribution
               ↓
plausible continuation
without RAG: weights + question                         → plausible guess
with RAG:    weights + question + authoritative evidence → better-grounded answer

12. What remains outside the model

user request → model proposes tool + arguments
             → application validates identity, policy, schema, and risk
             → tool executes with least privilege
             → model receives bounded observation
             → model produces the next token or final answer

13. Complete request flow

Application builds context
        ↓
Tokenizer
        ↓
Token IDs
        ↓
Internal embedding lookup
        ↓
Transformer / attention
        ↓
Next-token logits
        ↓
Temperature → softmax → top-p / decoding strategy
        ↓
Next token ID
        ↓
Append to context ───────────────┐
        ↑                        │
        └── repeat transformer ──┘
        ↓ stop condition
Detokenize / stream
        ↓
User sees text
Single LLM request from text through tokenization, prefill, decoding, and streamed output
🧠 Complete single-request sequence
Contents