AI / GenAI Essentials Interview questions
Last updated
1. What is Generative AI?
Generative AI refers to models that create new content - text, images, code, audio or video - instead of only labelling or predicting something about existing data. They learn the statistical patterns in huge training datasets and then produce fresh output that follows those patterns.
A classic machine learning model might say whether an email is spam. A generative model can write the email, summarise it, or draft a reply.
- Text: chatbots, summarisation, translation
- Code: completion, test generation, refactoring
- Images and audio: text-to-image, speech synthesis
Most of today's generative systems are built on large neural networks such as transformers and diffusion models.
Take quiz
It produces new content rather than only assigning a label
It never needs training data
It only works on numeric spreadsheets
It always runs without a neural network
Linear regression and k-means
Transformers and diffusion models
Decision stumps and naive Bayes
Apriori and PageRank
2. What is a Large Language Model (LLM)?
A Large Language Model is a neural network, almost always a transformer, trained on very large text corpora to predict the next token in a sequence. That one simple objective, repeated over trillions of tokens, is what gives the model grammar, facts, reasoning patterns and coding skill.
"Large" refers to both the training data and the parameter count, which commonly runs from a few billion to hundreds of billions of weights.
At inference time the model reads your prompt, predicts one token, appends it, and repeats until it hits a stop condition. It does not look answers up unless you connect it to a retrieval or search tool.
Take quiz
Classifying images into categories
Clustering users by behaviour
Compressing files losslessly
Predicting the next token in a sequence
Training data volume and number of parameters
The physical size of the server rack
The length of the user's prompt
The number of programming languages supported
3. What is a token in an LLM?
A token is the basic unit of text a model reads and writes. It can be a whole word, part of a word, a punctuation mark or even a single byte, depending on the tokenizer.
As a rough rule for English, one token is about four characters or three quarters of a word. Other languages and source code often need more tokens for the same meaning.
Tokens matter because pricing, rate limits and context windows are all measured in tokens, not words. A long prompt with a long answer can use up both your budget and the available window quickly.
| Text | Possible tokens (tokenizer dependent) |
| Hello | Hello |
| unbelievable | un, believ, able |
| GenAI | Gen, AI |
Take quiz
Tokens decide the font used in the reply
Tokens control which GPU brand is used
Cost, rate limits and the context window are measured in tokens
Tokens only matter for image models
About forty characters
Exactly one sentence
Always exactly one word
About four characters
4. What is a prompt?
A prompt is the input you send to a generative model: the instructions, context and data it uses to produce a response. In chat APIs it is usually a list of messages with roles such as system, user and assistant.
A well-built prompt typically contains:
- a clear instruction or task
- relevant context or reference text
- the input data to work on
- the desired output format
- optional examples of good answers
The model has no memory beyond what is in the prompt, so anything it needs to know must be included there.
Take quiz
In the model's temporary RAM only
Inside the prompt (or tools the prompt enables)
In the user's browser cookies
It is always remembered from earlier chats
An instruction
Reference context
The model's GPU temperature
Output format requirements
5. What is a context window?
The context window is the maximum number of tokens a model can consider in a single request. It normally covers the prompt, any retrieved documents, the conversation history and the generated answer together.
If a model has a 128K-token window and your input uses 120K, only about 8K tokens remain for the reply. Go past the limit and the API either returns an error or older content has to be dropped, depending on how the application handles it.
A bigger window lets you pass whole documents at once, but longer inputs cost more and can slow responses.
Take quiz
Total tokens (input plus output) handled in one request
How many users can chat at once
The number of training epochs
The size of the model file on disk
128K tokens
Roughly 8K tokens
Unlimited tokens
Zero tokens, always
6. What is prompt engineering?
Prompt engineering is the practice of designing and refining prompts so a model gives accurate, consistent and well-formatted output. It is mostly iterative testing: change the wording, compare results, keep what works.
Common habits that help:
- State the task and audience explicitly
- Provide examples of the exact output you want
- Ask for a specific format such as JSON or a table
- Break big tasks into smaller steps
- Tell the model what to do when it is unsure
It is cheaper than fine-tuning, which is why it is usually the first thing to try.
Take quiz
It permanently changes the model weights
It needs a GPU cluster
It guarantees zero errors
It is faster and cheaper because no model training is needed
Showing examples of the exact output format wanted
Keeping instructions as vague as possible
Hiding the task from the model
Avoiding any output format
7. What are the types of prompting techniques?
The most common prompting techniques differ in how much guidance you put into the prompt:
| Technique | What you do | Typical use |
| Zero-shot | Give only the instruction | Simple, well-known tasks |
| One/few-shot | Add 1-5 worked examples | Custom formats, classification |
| Chain-of-thought | Ask for step-by-step reasoning | Math, logic, multi-step problems |
| Role prompting | Assign a persona or role | Tone and domain framing |
| ReAct | Interleave reasoning with tool calls | Agents that search or use APIs |
In practice these are combined, for example a role plus few-shot examples plus a requested output schema.
Take quiz
Zero-shot prompting
Temperature prompting
Few-shot prompting
Token prompting
Compressing images
Encrypting prompts
Training embeddings from scratch
Agents that mix reasoning with tool calls
8. What is hallucination in GenAI?
A hallucination is output that sounds fluent and confident but is false, made up or not supported by the provided source. Typical examples are invented citations, wrong dates, non-existent API functions or fabricated quotes.
The model is not lying. It generates the most plausible continuation, and plausible is not always true.
Hallucinations are especially risky in legal, medical and financial settings, so production systems add grounding (such as RAG), citations and human review. A good habit is to treat every factual claim from a model as a draft that needs a source, especially names, numbers, quotes and links.
Take quiz
A crash caused by running out of GPU memory
Fluent output that is false or unsupported by sources
A tokenization error in the input
A slow response from the API
A correct summary of the supplied article
A response delayed by network latency
An invented citation for a paper that does not exist
A refusal to answer a harmful request
9. What is the temperature parameter?
Temperature controls how random the model's token choices are. Before sampling, the model's scores are divided by the temperature: low values sharpen the distribution so the top token wins almost every time, and high values flatten it so less likely tokens get a chance.
- Low (0 to 0.3): focused, repeatable - good for extraction, code, Q&A
- Medium (0.5 to 0.8): balanced writing
- High (1.0+): varied, creative, more risk of drift
Even at 0 some providers do not guarantee identical output on every run, so do not rely on temperature alone when you need strict repeatability. If the task has one correct answer, keep it low. If you want several different drafts to choose from, raise it. Values that are too high tend to produce rambling or off-topic text, which is why most production assistants stay in the low to medium range.
Take quiz
A low temperature
A very high temperature
Temperature has no effect on extraction
Exactly 5
Increases the context window
Flattens the probability distribution so more varied tokens are chosen
Reduces the number of tokens billed
Makes the model faster
10. What is an embedding?
An embedding is a list of numbers (a vector) that represents the meaning of a piece of text, image or other data. Items with similar meaning end up close together in this vector space, even when they share no words.
For example, "reset my password" and "I can't log in" land near each other, while "quarterly revenue" lands far away. Typical embedding models output vectors with hundreds to a few thousand dimensions.
Embeddings power semantic search, recommendations, clustering and the retrieval step of RAG.
Take quiz
They store each word's spelling
They sort text alphabetically
They copy the text into a database column
Similar meanings map to nearby vectors
Semantic search
Compiling Java
Rendering CSS
Hashing passwords
11. What is a vector database?
A vector database stores embeddings and quickly finds the ones nearest to a query vector. Instead of exact matching, it does approximate nearest neighbour (ANN) search using indexes such as HNSW or IVF, trading a tiny bit of accuracy for large speed gains.
Examples include Pinecone, Weaviate, Milvus and Chroma, and extensions like pgvector for PostgreSQL. Most also store metadata so you can filter by tenant, date or document type alongside similarity.
It is the usual storage layer behind RAG and semantic search.
Take quiz
Train the language model
Tokenize the prompts
Find stored embeddings closest to a query embedding
Encrypt API keys
Prompt templates
Tokenizer algorithms
Loss functions
Approximate nearest neighbour index types
12. What is Retrieval-Augmented Generation (RAG)?
RAG is a pattern where the system first retrieves relevant documents from an external knowledge source and then passes them to the LLM along with the question. The model answers using that supplied evidence instead of relying only on what it memorised during training.
- Convert the user question to an embedding
- Search a vector (or hybrid) index for the closest chunks
- Insert those chunks into the prompt
- Let the model generate an answer, ideally with citations
RAG lets you use private or fresh data without retraining, and it cuts hallucinations because the answer is grounded in retrieved text.
Take quiz
Extra GPU layers
Retrieved external documents as context
A larger tokenizer vocabulary
A higher temperature
Making the model smaller
Removing the need for prompts
Using private or recent data without retraining the model
Guaranteeing zero latency
13. What is fine-tuning?
Fine-tuning means continuing the training of a pre-trained model on a smaller, task-specific dataset so its weights shift toward the behaviour you want. The data is usually prompt and ideal-response pairs.
It works well for teaching a consistent style, output format, tone or domain vocabulary, or for getting a small model to match a big one on a narrow task.
It is a poor way to add frequently changing facts. For that, retrieval is cheaper and easier to update. Parameter-efficient methods such as LoRA make fine-tuning affordable by training only a small set of extra weights.
Take quiz
The model's weights, using task-specific examples
Only the user's prompt
The tokenizer's spelling rules
The network cable speed
Teaching a consistent output style
Injecting facts that change every day
Adapting tone for a brand
Making a small model good at one narrow task
14. What is a transformer model?
A transformer is a neural network architecture introduced in the 2017 paper "Attention Is All You Need". It replaced recurrent networks by using self-attention, which lets every token look at every other token in the sequence at once.
Each transformer layer combines a multi-head attention block with a feed-forward network, wrapped in residual connections and normalisation. Positional information is added so the model knows token order.
Because tokens are processed in parallel, transformers train efficiently on GPUs, which is why they scaled into modern LLMs.
Take quiz
Convolution over pixels only
Recurrent hidden states
Decision tree splits
Self-attention
Tokens are processed in parallel during training
They need no training data
They never use GPUs
They process one character per step
15. List some common use cases of GenAI?
GenAI shows up wherever people write, read or search a lot. Common use cases include:
- Conversational assistants for support and internal helpdesks
- Summarisation of meetings, tickets and long reports
- Code assistance: completion, tests, explanation, migration
- Document Q&A using RAG over company knowledge
- Data extraction from invoices, contracts and emails into JSON
- Content drafting and translation
- Image and audio generation for marketing and media
The best early projects have a clear owner, measurable outcome and a human who can check the output.
Take quiz
Replacing a CPU scheduler
Formatting a hard drive
Extracting structured fields from invoices
Routing network packets
No success metric is defined
It runs on unreviewed legal decisions
Nobody owns it
A human can review the output
16. What is a system prompt?
A system prompt is a high-priority instruction set, written by the developer, that defines the model's role, tone, rules and constraints for the whole conversation. It sits in a separate message role from the user's text.
Typical contents are the persona ("you are a billing support assistant"), allowed and forbidden topics, answer format, and what to do when information is missing.
It guides behaviour but is not a security boundary. A determined user can sometimes override or extract it, so never place secrets or credentials inside. Keep it short, specific and testable, and version it like code so changes can be reviewed and rolled back.
Take quiz
The end user in each message
The application developer
The GPU driver
The vector database
Yes, it is fully encrypted
Yes, users can never see it
No, it can be leaked or overridden
Yes, but only on Tuesdays
17. What is multimodal AI?
Multimodal AI handles more than one type of data - such as text, images, audio and video - as input, output or both. A single model can, for instance, read a chart screenshot and answer questions about it in text.
Common patterns are image-to-text (describe or read a photo), text-to-image generation, speech-to-text, and text-to-speech.
Under the hood, each modality is converted into tokens or embeddings that live in a shared representation the model can reason over. Typical business uses include reading receipts and forms, describing product photos, transcribing calls and answering questions about diagrams. Cost and latency are usually higher than text-only calls, because images and audio expand into many tokens.
Take quiz
Answering questions about an uploaded chart image
Sorting an integer array
Compressing a ZIP file
Running a SQL JOIN
By deleting all but text
By mapping them into shared representations or tokens
By printing images as ASCII only
By training a separate unrelated model per request
18. What is a foundation model?
A foundation model is a large model pre-trained on broad, mostly unlabelled data so it can be adapted to many downstream tasks. LLMs, image models like Stable Diffusion, and embedding models such as CLIP are all examples.
Instead of training a new model per task, teams reuse one foundation model and adapt it with prompting, retrieval, fine-tuning or tools.
The expensive pre-training is done once by a few providers, while most organisations only pay for adaptation and inference. This is why choosing which foundation model to build on is one of the first architectural decisions in a GenAI project, since it affects cost, quality, licensing and data-handling terms.
Take quiz
They only solve one fixed task
They need new pre-training for each prompt
They contain no neural networks
They are pre-trained broadly and adapted to many tasks
A general-purpose pre-trained LLM
A single-purpose regex
A CSS stylesheet
A SQL view
19. What is an AI agent?
An AI agent is an LLM-driven system that pursues a goal by deciding what to do next, calling tools, reading the results and repeating until the task is done. A plain chatbot answers once, while an agent acts in a loop.
The main ingredients are the model, a set of tools (search, code runner, APIs), instructions, and some memory of what has happened so far.
Because agents can take real actions, they need limits such as step budgets, permission scopes and human approval for risky steps.
Take quiz
It never uses an LLM
It only answers yes or no
It loops: decides, calls tools, observes, repeats
It runs without any instructions
They cannot read text
They always produce identical output
They have no tools
They can take real actions and may loop or err
20. What is function calling (tool use) in LLMs?
Function calling lets a model request an action by returning a structured message - the function name plus JSON arguments - instead of plain text. You describe the available functions with a name, description and parameter schema, and the model picks one when it fits.
Your application, not the model, executes the function and sends the result back so the model can write the final answer.
{"name": "get_weather", "arguments": {"city": "Charlotte", "unit": "F"}}
This is how LLMs query databases, call APIs and trigger workflows safely.
Take quiz
The LLM itself, inside its weights
Your application code
The tokenizer
The vector database
A compiled binary
A PNG screenshot
A function name with JSON arguments
A new set of weights
21. What is the difference between discriminative and generative models?
A discriminative model learns the boundary between classes, estimating P(label | input). A generative model learns how the data itself is distributed, so it can sample new examples.
| Aspect | Discriminative | Generative |
| Learns | P(y | x), decision boundary | P(x) or P(x | y), data distribution |
| Output | Label or score | New text, image, audio |
| Examples | Logistic regression, classifier heads, BERT classifiers | GPT-style LLMs, diffusion models, VAEs |
| Typical task | Spam detection, sentiment | Drafting, image creation, code writing |
Generative models can also be used for classification by prompting, but a small discriminative model is often cheaper and more predictable for a fixed label set.
Take quiz
Discriminative
Generative
A diffusion model
A tokenizer
It only draws a boundary between labels
It models the data distribution and can sample new examples
It cannot create new outputs
It works only on tabular numbers
22. How does the self-attention mechanism work?
In self-attention each token is turned into three vectors: a query (what I am looking for), a key (what I offer) and a value (the information I carry). A token's query is compared with every key to get relevance scores.
- Compute scores: query dot key for every pair of tokens
- Scale by the square root of the key dimension
- Apply softmax so scores become weights that sum to 1
- Take a weighted sum of the value vectors
Attention(Q, K, V) = softmax(Q K^T / sqrt(d_k)) V
Multi-head attention runs this several times in parallel with different learned projections, letting heads specialise (syntax, coreference, position). In decoder LLMs a causal mask stops a token from seeing future tokens.
Take quiz
To convert tokens into words
To remove the value vectors
To compress the context window
To keep dot products from growing too large before softmax
Blocks each token from attending to future tokens
Hides the query vectors
Deletes the first token
Randomises token order
23. Why do LLMs hallucinate?
LLMs are trained to produce the most plausible next token, not to verify truth. A fluent wrong answer scores just as well as a right one during generation.
- Knowledge gaps: rare or niche facts were barely seen in training
- Stale data: the training cutoff hides newer events
- No calibrated uncertainty: the model does not reliably know what it does not know
- Ambiguous or leading prompts push it to fill in blanks
- Sampling randomness can drift into a wrong branch that later tokens then justify
- Long context: relevant details buried mid-prompt may be ignored
Grounding with retrieved sources, allowing "I don't know" and lowering temperature all reduce, but never fully remove, the problem.
Take quiz
The GPU rounds numbers badly
The tokenizer deletes facts
The model optimises for plausible continuations, not verified truth
Prompts are always encrypted
Demanding an answer no matter what
Removing all source material
Raising temperature to maximum
Permitting the model to say it does not know
24. What is the difference between RAG and fine-tuning?
RAG changes what the model sees at request time, while fine-tuning changes how the model behaves by updating its weights.
| Aspect | RAG | Fine-tuning |
| Best for | Fresh or private knowledge | Style, format, narrow skills |
| Updating data | Re-index documents, minutes | Retrain, hours or days |
| Citations | Easy, source chunks known | Hard, knowledge is baked in |
| Upfront cost | Pipeline and index setup | Data curation and GPU training |
| Per-request cost | Longer prompts from retrieved text | Often shorter prompts |
| Access control | Filter per user at retrieval | Weights are shared by everyone |
Start with prompting and RAG. Add fine-tuning when you need consistent behaviour that prompting cannot deliver. Many production systems use both.
Take quiz
Full fine-tuning each week
RAG
Training a new model from scratch
Raising the temperature
Answering from a document updated hourly
Showing the source page for each fact
Enforcing a consistent house writing style
Per-user document permissions
25. How does a RAG pipeline work end to end?
A RAG system has two phases: an offline indexing phase and an online query phase.
flowchart LR
subgraph Indexing
A["Load documents"] --> B["Clean and chunk"]
B --> C["Create embeddings"]
C --> D[(Vector index)]
end
subgraph Query
Q["User question"] --> E["Embed query"]
E --> F["Retrieve top-k chunks"]
D --> F
F --> G["Rerank and filter"]
G --> H["Build prompt"]
H --> I["LLM generates answer"]
I --> J["Answer with citations"]
end
- Index: load, clean, chunk, embed and store documents with metadata
- Retrieve: embed the question and fetch the nearest chunks
- Rerank (optional): a cross-encoder reorders results by true relevance
- Augment: place the best chunks in the prompt with instructions to use only them
- Generate: the LLM answers and cites sources
Quality problems usually come from the retrieval half, so evaluate retrieval separately from generation.
Take quiz
Chunking documents and storing their embeddings
Generating the final answer
Embedding the user's live question
Streaming tokens to the browser
Splits documents into chunks
Reorders retrieved chunks by relevance to the question
Generates the final answer text
Trains the embedding model
26. Why is chunking important in RAG?
Chunking decides what each embedding represents and what text the model receives. It directly controls retrieval quality.
- Too large: one vector blends several topics, so matches get fuzzy and prompt tokens are wasted
- Too small: a chunk loses the surrounding meaning, such as which product a sentence refers to
Common strategies are fixed-size splits, recursive splitting on headings and paragraphs, and semantic splitting where topic changes mark the boundary. A 10 to 20 percent overlap helps keep sentences from being cut off mid-thought.
Attach metadata such as title, section and date to each chunk so you can filter and cite properly.
Take quiz
Embeddings become exact and perfect
The tokenizer stops working
The index shrinks to zero
Embeddings blur several topics and waste prompt tokens
To avoid cutting an idea in half at a boundary
To double the storage cost on purpose
To remove metadata
To lower the temperature
27. How can you optimize retrieval quality in a RAG system?
Fix retrieval before touching the generator, because the model can only be as good as the chunks it is given.
- Improve chunking to follow headings and keep context together
- Use hybrid search (BM25 plus vectors) for names, IDs and error codes
- Add a reranker over the top 20 to 50 results
- Rewrite queries: expand abbreviations, split multi-part questions
- Filter by metadata such as product, language or date
- Pick a better embedding model for your domain and language
- Tune top-k: enough recall, not so many chunks that noise drowns the answer
Measure with a labelled question set using recall@k and mean reciprocal rank, so each change is judged by numbers instead of impressions.
Take quiz
Lowering the context window
Using only a higher temperature
Hybrid keyword plus vector search
Removing metadata
BLEU score
Token count
Learning rate
Recall@k
28. What is the difference between temperature and top-p sampling?
Both control randomness, but they act at different points. Temperature reshapes the whole probability distribution. Top-p (nucleus sampling) cuts the candidate list to the smallest group of tokens whose probabilities add up to p, then samples from that group.
| Setting | How it works | Effect |
| Temperature | Divides logits before softmax | Sharper or flatter choices overall |
| Top-p | Keeps tokens until cumulative probability reaches p | Drops the unlikely tail |
| Top-k | Keeps the k most likely tokens | Fixed-size candidate list |
Providers usually advise adjusting one of them, not both, because their effects overlap and become hard to reason about. A practical starting point is to leave top-p at its default and tune temperature, then change one setting at a time while checking output on a fixed test set.
Take quiz
Exactly 9 tokens
The smallest set whose probabilities sum to at least 0.9
All tokens equally
Only the single most likely token
They cannot be used together by design of the GPU
Top-p disables temperature permanently
Their effects overlap and are hard to separate
Only one can be a number
29. How does tokenization work in LLMs?
Most LLMs use subword tokenization, commonly Byte Pair Encoding (BPE). The tokenizer is trained before the model, and its vocabulary is fixed afterwards.
- Start with single characters or bytes as the base vocabulary
- Count the most frequent adjacent pair in the training text
- Merge that pair into a new token
- Repeat until the vocabulary reaches the target size, often 30K to 200K entries
At run time, text is split with the learned merges. Common words become one token, while rare words break into pieces, so there are no out-of-vocabulary failures.
The side effects matter in interviews: non-English text, numbers and code can use more tokens, and models can struggle with letter-level tasks like counting characters in a word.
Take quiz
The most frequent adjacent pair of tokens
The longest sentence in the corpus
The two rarest letters
Random pairs of words
They have no vocabulary
They see subword tokens, not individual characters
They only read numbers
Words are never tokenized
30. Why do LLMs have context window limits?
The limit comes from compute, memory and training, not an arbitrary rule.
- Attention cost: standard self-attention compares every token with every other, so compute grows roughly with the square of the sequence length
- KV cache memory: stored keys and values grow with each token and with each concurrent request
- Training length: models perform best at lengths they were trained on, and position encodings may extrapolate poorly
- Cost and latency: longer inputs mean slower first tokens and higher bills
Techniques such as sparse or sliding-window attention, FlashAttention and position-scaling methods push limits higher. Even with huge windows, models can miss details buried in the middle of long inputs, so retrieval is still useful.
Take quiz
Compute shrinks as text gets longer
Tokens become free past 10K
Only the first token is processed
Compute grows roughly with the square of sequence length
The KV cache
The tokenizer vocabulary
The training dataset
The system prompt only
31. How does chain-of-thought prompting improve reasoning?
Chain-of-thought (CoT) prompting asks the model to write out intermediate steps before the final answer. Since each generated token becomes input for the next, the written steps work like scratch paper, letting the model carry partial results forward instead of jumping straight to a guess.
Q: A shop sells pens at $3 each. I buy 7 and pay with $50. Change? Think step by step, then give the final answer.
It helps most on multi-step arithmetic, logic and planning problems, and does little for simple lookups.
Trade-offs: more output tokens, higher latency and cost, and the written reasoning is not guaranteed to be a faithful picture of what happened inside the model. Dedicated reasoning models do this thinking internally.
Take quiz
It increases the model's parameter count
It deletes the context window
Earlier generated tokens feed later ones, acting like scratch space
It lowers the number of layers
Fewer tokens than normal
A smaller vocabulary
Loss of the system prompt
More output tokens and higher latency
32. What happens when a prompt exceeds the context window?
It depends on the API and your application. Some APIs return an error that the request is too long. Others, or chat frameworks you wrap around them, silently truncate the oldest messages, which can drop instructions or key facts without any warning.
Ways to handle it deliberately:
- Summarise older turns and keep the summary
- Sliding window: keep the system prompt plus the last N turns
- RAG: retrieve only relevant passages instead of pasting whole documents
- Map-reduce: process a long document in parts, then combine results
- Trim tool output before adding it to history
Count tokens before sending and reserve space for the reply.
Take quiz
The model gets faster at math
Important instructions or facts can be lost without warning
The temperature resets to 2
The GPU shuts down
Doubling the temperature
Removing the system prompt
Retrieving only relevant passages with RAG
Using a smaller font
33. How does RLHF align a language model?
Reinforcement Learning from Human Feedback (RLHF) nudges a model toward answers people prefer, such as helpful, honest and harmless ones.
- Supervised fine-tuning: train on human-written ideal responses
- Reward model: humans rank several outputs for the same prompt, and a model learns to predict those preferences
- Policy optimisation: the LLM is tuned with reinforcement learning, commonly PPO, to maximise the reward score
- A KL penalty keeps it from drifting too far from the original model and gaming the reward
Newer alternatives skip the separate reward model: DPO optimises directly on preference pairs, and RLAIF or constitutional methods use AI feedback guided by written principles.
Take quiz
Human rankings of model outputs
Raw pixel data
The tokenizer's merge rules
GPU benchmark scores
To increase the vocabulary
To stop the model drifting too far from its starting behaviour
To shorten the prompts
To delete the reward model
34. What is the difference between pre-training, fine-tuning and instruction tuning?
| Stage | Data | Goal |
| Pre-training | Trillions of raw tokens from web, books, code | Learn language, facts, general patterns by next-token prediction |
| Fine-tuning | Smaller task or domain dataset | Specialise the model for a task, style or domain |
| Instruction tuning | Prompt and ideal-response pairs across many tasks | Make the model follow instructions instead of just continuing text |
A pre-trained base model often just continues your text. Instruction tuning, usually followed by preference tuning such as RLHF, is what turns it into a usable assistant.
Pre-training costs millions in compute and is done by a few labs. Fine-tuning is the stage most teams can afford.
Take quiz
Tokenizer training
Vector indexing
Output caching
Instruction tuning
Trillions of raw tokens, mostly unlabelled
A few hundred labelled rows
Only user chat logs from today
Only images of cats
35. When should you choose LoRA over full fine-tuning?
LoRA (Low-Rank Adaptation) freezes the original weights and trains two small matrices per targeted layer whose product represents the weight update. Often well under 1 percent of the parameters are trained.
| Factor | LoRA | Full fine-tuning |
| GPU memory | Much lower (QLoRA even lower with 4-bit base) | High: weights, gradients, optimizer states |
| Output | Small adapter file, swappable | A full new model copy |
| Multi-task | One base, many adapters | One model per task |
| Max quality | Close for most tasks | Best when the domain shift is large |
Choose LoRA when hardware is limited, you serve several customised variants, or you need quick experiments. Choose full fine-tuning when you have plenty of data and compute and need to shift the model deeply.
Take quiz
The entire model from scratch
Only the tokenizer
Small low-rank matrices while the base weights stay frozen
Nothing, it edits the prompt
20 full model copies
No tuning at all, ever
Training a new tokenizer for each
LoRA adapters
36. How does function calling work between an app and an LLM?
Function calling is a round trip between your app, the model and your tools. The model only asks for a call. Your code decides whether to run it.
sequenceDiagram participant U as User participant A as App participant M as LLM participant T as Tool/API U->>A: Weather in Charlotte? A->>M: Prompt + tool schemas M-->>A: Call get_weather(city=Charlotte) A->>T: Execute get_weather T-->>A: 72F, sunny A->>M: Tool result M-->>A: Final answer text A-->>U: It is 72F and sunny
- Send the user message along with tool definitions (name, description, JSON schema)
- The model replies with a tool call instead of text
- Validate the arguments, then execute the function
- Return the result to the model as a tool message
- The model writes the final response, or requests another call
Always validate arguments and check permissions, since the model's output is untrusted input.
Take quiz
Run them blindly as shell commands
Validate them before executing the function
Ignore them
Store them as the new system prompt
Delete the conversation
Retrain the model
Send the result back to the model
Switch to a different language
37. Explain the execution flow of an AI agent loop?
An agent repeats a think, act, observe cycle until it decides the goal is met or a limit is hit.
flowchart TD
A["Goal from user"] --> B["Model plans next step"]
B --> C{Needs a tool?}
C -- Yes --> D["Call tool"]
D --> E["Observe result"]
E --> F["Update context and memory"]
F --> B
C -- No --> G["Produce final answer"]
F --> H{Step or budget limit hit?}
H -- Yes --> I["Stop and report"]
- Receive the goal and instructions
- The model reasons about the next action
- If a tool is needed, it emits a call and the app runs it
- The result is appended to context
- Loop until a final answer, a failure, or a limit
Common failure modes are infinite loops, repeating failed calls, drifting from the goal and runaway cost. Mitigate with max steps, token budgets, timeouts, logging and human approval for irreversible actions.
Take quiz
Think, act with a tool, observe, repeat
Train, deploy, retire
Tokenize, compress, archive
Index, shard, replicate only once
A higher temperature
A maximum step or budget limit
A longer system prompt
Removing all logs
38. How does cosine similarity help in semantic search?
Cosine similarity measures the angle between two vectors, ignoring their length. It ranges from -1 (opposite) through 0 (unrelated) to 1 (same direction). In semantic search it ranks stored embeddings by how closely their direction matches the query embedding.
import numpy as np def cosine(a, b): return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
Ignoring magnitude is useful because a long document and a short one on the same topic should still match. If embeddings are normalised to length 1, cosine similarity equals the dot product, which is faster and what many vector databases use internally. Always compare vectors produced by the same embedding model, since scores from different models are not comparable.
Take quiz
The file sizes of two documents
The spelling of two words
The number of tokens only
The angle (direction) between two vectors
The dot product
The vector's length squared
Zero always
The number of dimensions
39. When should you use hybrid search instead of pure vector search?
Use hybrid search when queries mix meaning with exact terms. Vector search is good at paraphrases but can miss precise strings, while keyword search (BM25) nails exact matches but misses synonyms.
| Query | Better method |
| How do I get my money back? | Vector (matches 'refund policy') |
| Error ERR_4012 | Keyword (exact code) |
| SKU AX-9921 return window | Hybrid (ID plus meaning) |
The two ranked lists are merged, commonly with Reciprocal Rank Fusion, which scores each document by its position in each list. Many teams then rerank the merged top results.
It is a strong default for enterprise search over product names, ticket IDs, legal clauses and code.
Take quiz
Explaining a concept in other words
Finding a synonym
Searching for the exact code ERR_4012
Summarising a topic
Tokenizing prompts
Compressing embeddings
Training reward models
Merging ranked lists from keyword and vector search
40. How do diffusion models generate images?
Diffusion models learn to remove noise. During training, real images are gradually corrupted with Gaussian noise and a network learns to predict the noise added at each step.
- Start from pure random noise
- Encode the text prompt into an embedding
- At each step, predict the noise and subtract a little of it, guided by the prompt
- Repeat for tens of steps until a clean image appears
Classifier-free guidance strengthens how closely the image follows the prompt. Latent diffusion (used by Stable Diffusion) runs this process in a compressed latent space and decodes to pixels at the end, which makes it much cheaper than working on full-resolution pixels.
Take quiz
The next word in a sentence
The noise that was added to an image
The user's age
The GPU clock speed
It skips the text prompt
It uses no neural network
It denoises in a compressed latent space, not full pixels
It generates only one pixel
41. How can you reduce hallucinations in a production GenAI app?
No single fix works, so layer several controls.
- Ground answers with RAG and instruct the model to use only the supplied context
- Require citations and check that quoted spans exist in the sources
- Allow abstention: tell it to say "not found in the documents"
- Lower temperature for factual tasks
- Constrain output with JSON schemas or enumerated choices
- Add a verification step, such as a second pass or rule-based checks on numbers and IDs
- Route high-risk cases to human review
- Evaluate continuously on a regression set with groundedness metrics
Choose the controls by risk: a marketing draft needs far less than a medical or financial answer.
Take quiz
Answer only from the provided context, or say it is not found
Always guess confidently
Ignore the retrieved documents
Use the highest temperature
It speeds up the GPU
High-risk answers need a check no model can fully replace
It removes the need for evaluation
It makes the model larger
42. What is prompt injection and how do you defend against it?
Prompt injection is an attack where text the model reads contains instructions that override the developer's intent. Direct injection comes from the user ("ignore previous instructions"). Indirect injection hides in retrieved web pages, emails or documents the model processes.
The danger grows when the model can use tools: a poisoned document could tell an agent to send data to an attacker.
- Least privilege: give tools only the permissions the task needs
- Treat retrieved text as data, clearly separated from instructions
- Confirm sensitive or irreversible actions with the user
- Filter and validate inputs and outputs, including links and tool arguments
- Keep secrets out of prompts and sandbox code execution
- Log and monitor tool calls for odd behaviour
There is no complete fix today, so design assuming the model can be tricked.
Take quiz
A user typing a long prompt
A GPU driver bug
A slow network connection
Malicious instructions hidden in content the model retrieves or reads
Giving tools least-privilege permissions
Granting admin rights to every tool
Placing API keys in the system prompt
Disabling all logs
43. How do you evaluate an LLM application?
Evaluate the whole system, not just the model, with a mix of offline and online checks.
- Build a golden set of realistic inputs with expected answers or rubrics
- Automated checks: exact match, schema validity, regex, unit tests for code outputs
- LLM-as-judge with a clear rubric for tone, correctness or faithfulness, spot-checked against human labels
- RAG metrics: context recall, context precision, answer faithfulness, answer relevance
- Human review of samples, especially edge cases
- Regression runs every time the prompt, model or retriever changes
- Online monitoring: thumbs up or down, escalation rate, latency, cost
Classic overlap scores like BLEU or ROUGE are weak for open-ended answers, so use them sparingly.
Take quiz
To replace all human review forever
To increase the context window
To run repeatable regression checks when prompts or models change
To store user passwords
Tokens per second
Embedding dimension
Batch size
Faithfulness (groundedness)
44. How can you reduce LLM latency and cost?
| Technique | How it helps |
| Prompt caching | Reuses the processed static prefix (system prompt, documents) for repeat calls |
| Model routing | Send easy requests to a small model, hard ones to a large model |
| Shorter prompts | Fewer input tokens, faster first token |
| Limit max output | Caps runaway answers and spend |
| Streaming | Does not cut total time, but improves perceived latency |
| Semantic cache | Returns stored answers for near-duplicate questions |
| Batch APIs | Cheaper for non-urgent offline jobs |
| Lower top-k in RAG | Less retrieved text to pay for and read |
Measure first. Track time to first token, tokens per second and cost per request, then fix the biggest contributor. Quality must be re-checked after every optimisation.
Take quiz
Raising max output tokens
Streaming tokens as they are produced
Adding more few-shot examples
Disabling caching
Routes network cables
Encrypts all prompts
Sends simple requests to cheaper models and hard ones to stronger models
Trains embeddings
45. Which is better, a large general model or a smaller specialised model, and why?
Neither wins everywhere. The right choice depends on task difficulty, volume, latency and data sensitivity.
| Factor | Large general model | Small specialised model |
| Reasoning on open-ended tasks | Stronger | Weaker |
| Cost per request | Higher | Much lower |
| Latency | Slower | Faster |
| Narrow, repetitive task after tuning | Often overkill | Can match large model |
| On-device or private hosting | Hard | Practical |
A common pattern is a cascade: try the small model first, and escalate to the large one when confidence is low or the task is complex. Test both on your own evaluation set, since public benchmarks rarely match your workload. Also factor in operational effort, because self-hosting a small model adds deployment, scaling and monitoring work that a hosted API handles for you.
Take quiz
A narrow, high-volume task needing low cost and latency
Open-ended research across many domains
Tasks with no evaluation data
Problems that need maximum reasoning every time
Runs every model on every request
Tries a cheap model first and escalates hard cases to a stronger one
Removes the need for testing
Merges weights permanently
46. How do you troubleshoot poor answers in a RAG system?
First decide whether the failure is in retrieval or generation. Log the retrieved chunks for a bad answer and read them.
- Right chunk missing? It is a retrieval problem. Check chunk size, embedding model, hybrid search, metadata filters, top-k and query rewriting.
- Right chunk present but ignored? It is a generation problem. Shorten the context, put key chunks first, tighten the instructions, or add a reranker.
- Document never indexed? Check ingestion errors, parsing of PDFs and tables, and stale indexes.
- Contradicting chunks? Deduplicate and prefer newer versions using metadata.
- Answer invents details? Require citations and an explicit not-found response.
Turn each failure into a test case so the same bug cannot return unnoticed.
Take quiz
The ingestion pipeline
The tokenizer vocabulary
The vector database hardware
Generation or prompt construction
Inspect the chunks that were retrieved
Retrain the embedding model
Raise the temperature
Delete the index
47. What is the difference between encoder-only, decoder-only and encoder-decoder models?
| Type | Attention | Examples | Best for |
| Encoder-only | Bidirectional, sees full input | BERT, RoBERTa | Classification, embeddings, search |
| Decoder-only | Causal, sees only earlier tokens | GPT-style, Llama, Claude-style chat LLMs | Open-ended text generation |
| Encoder-decoder | Encoder reads input, decoder generates output | T5, BART | Translation, summarisation |
Most modern chat LLMs are decoder-only because one next-token objective scales cleanly and handles many tasks through prompting.
Encoder-only models are still popular for embeddings and rerankers, where understanding a full text matters more than generating one. Encoder-decoder models remain a good fit for tasks with a clear input-to-output mapping, such as translating a sentence or condensing a report into a short summary.
Take quiz
Encoder-only
Recurrent only
Decoder-only
Convolution only
Decoder-only
Encoder-decoder
Diffusion
Encoder-only
48. What is quantization and why is it used for LLMs?
Quantization stores model weights (and sometimes activations) at lower numeric precision, for example 16-bit floats reduced to 8-bit or 4-bit integers. The goal is a smaller, faster model that fits on cheaper hardware.
The memory arithmetic is simple. A 7-billion-parameter model needs about 14 GB at 16-bit (2 bytes per weight) but only around 3.5 GB at 4-bit, plus runtime overhead.
| Approach | Idea |
| Post-training quantization | Convert an already trained model, quick and cheap |
| Quantization-aware training | Train with low precision in mind, better quality retention |
The trade-off is a small, task-dependent quality drop, most visible at 4-bit and below. Always re-run your evaluation set after quantizing.
Take quiz
Around 140 GB
Around 3.5 GB
Around 14 GB
Under 1 MB
A larger model file
Slower training from scratch
A small possible drop in output quality
A smaller vocabulary
49. Why should you add guardrails to a GenAI application?
LLMs are probabilistic, so even a strong prompt cannot guarantee safe, on-topic, correctly formatted output every time. Guardrails are checks placed around the model to catch problems the prompt alone cannot prevent.
- Input side: detect prompt injection, redact PII, block off-topic or disallowed requests
- Output side: validate JSON schemas, run moderation, check groundedness against sources, filter leaked secrets
- Action side: limit tool permissions, cap spend, require approval for irreversible steps
- Operations: log decisions, alert on spikes and keep an audit trail
Treat them as defence in depth. Each layer is imperfect, but together they reduce incidents, protect users and make compliance reviews easier.
Take quiz
Model output is probabilistic and can still go wrong
Prompts are ignored by every model
Prompts are too short to read
Guardrails are illegal
Raising the temperature
Validating the response against a JSON schema
Adding more training data
Increasing the context window
50. How does Model Context Protocol (MCP) differ from function calling?
Function calling is a model capability: you pass tool schemas in the request and the model returns a structured call. MCP is an open protocol that standardises how an AI application discovers and uses tools, data resources and prompt templates from external servers.
| Aspect | Function calling | MCP |
| Level | Model API feature | Client-server protocol |
| Tool definitions | Written inside your app per request | Exposed by an MCP server and discovered dynamically |
| Reuse | Rewritten for each app or provider | One server works across many compatible clients |
| Provides | Tool schemas and call format | Tools, resources and prompts |
| Relationship | Often used underneath by the host app | Sits above it to standardise integration |
They are complementary: an MCP client typically converts the server's tools into function-calling definitions for the model, then routes the model's calls back to the server. Remember that MCP servers still need authentication, scoped permissions and trust review.