Prev Next

AI / GenAI Essentials Interview questions

Last updated

1. What is Generative AI? 2. What is a Large Language Model (LLM)? 3. What is a token in an LLM? 4. What is a prompt? 5. What is a context window? 6. What is prompt engineering? 7. What are the types of prompting techniques? 8. What is hallucination in GenAI? 9. What is the temperature parameter? 10. What is an embedding? 11. What is a vector database? 12. What is Retrieval-Augmented Generation (RAG)? 13. What is fine-tuning? 14. What is a transformer model? 15. List some common use cases of GenAI? 16. What is a system prompt? 17. What is multimodal AI? 18. What is a foundation model? 19. What is an AI agent? 20. What is function calling (tool use) in LLMs? 21. What is the difference between discriminative and generative models? 22. How does the self-attention mechanism work? 23. Why do LLMs hallucinate? 24. What is the difference between RAG and fine-tuning? 25. How does a RAG pipeline work end to end? 26. Why is chunking important in RAG? 27. How can you optimize retrieval quality in a RAG system? 28. What is the difference between temperature and top-p sampling? 29. How does tokenization work in LLMs? 30. Why do LLMs have context window limits? 31. How does chain-of-thought prompting improve reasoning? 32. What happens when a prompt exceeds the context window? 33. How does RLHF align a language model? 34. What is the difference between pre-training, fine-tuning and instruction tuning? 35. When should you choose LoRA over full fine-tuning? 36. How does function calling work between an app and an LLM? 37. Explain the execution flow of an AI agent loop? 38. How does cosine similarity help in semantic search? 39. When should you use hybrid search instead of pure vector search? 40. How do diffusion models generate images? 41. How can you reduce hallucinations in a production GenAI app? 42. What is prompt injection and how do you defend against it? 43. How do you evaluate an LLM application? 44. How can you reduce LLM latency and cost? 45. Which is better, a large general model or a smaller specialised model, and why? 46. How do you troubleshoot poor answers in a RAG system? 47. What is the difference between encoder-only, decoder-only and encoder-decoder models? 48. What is quantization and why is it used for LLMs? 49. Why should you add guardrails to a GenAI application? 50. How does Model Context Protocol (MCP) differ from function calling?

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
What separates a generative model from a classic spam classifier?
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
Which pair of architectures commonly power generative AI?
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
What is the core training objective of most LLMs?
Classifying images into categories
Clustering users by behaviour
Compressing files losslessly
Predicting the next token in a sequence
What does the 'large' in LLM mostly refer to?
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
Why do developers track token counts closely?
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
Roughly how long is one English token?
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
Where must information live if the model needs it for this request?
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
Which is NOT a typical part of a prompt?
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
What does the context window limit?
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
A 128K window has 120K tokens of input. What remains for the reply?
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
Why is prompt engineering usually tried before fine-tuning?
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
Which habit improves prompt reliability?
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
Which technique adds worked examples to the prompt?
Zero-shot prompting
Temperature prompting
Few-shot prompting
Token prompting
ReAct prompting is mainly used for:
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
What is a hallucination?
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
Which example is a typical hallucination?
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
Which temperature suits structured data extraction best?
A low temperature
A very high temperature
Temperature has no effect on extraction
Exactly 5
What does raising the temperature do?
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
Why can embeddings find related text with no shared words?
They store each word's spelling
They sort text alphabetically
They copy the text into a database column
Similar meanings map to nearby vectors
Which task relies directly on embeddings?
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
What is the main job of a vector database?
Train the language model
Tokenize the prompts
Find stored embeddings closest to a query embedding
Encrypt API keys
HNSW and IVF are examples of:
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.

  1. Convert the user question to an embedding
  2. Search a vector (or hybrid) index for the closest chunks
  3. Insert those chunks into the prompt
  4. 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
What does RAG add to an LLM request?
Extra GPU layers
Retrieved external documents as context
A larger tokenizer vocabulary
A higher temperature
A key benefit of RAG is:
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
What does fine-tuning change?
The model's weights, using task-specific examples
Only the user's prompt
The tokenizer's spelling rules
The network cable speed
What is fine-tuning NOT well suited for?
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
What mechanism is central to transformers?
Convolution over pixels only
Recurrent hidden states
Decision tree splits
Self-attention
Why did transformers scale better than RNNs?
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
Which is a strong GenAI use case?
Replacing a CPU scheduler
Formatting a hard drive
Extracting structured fields from invoices
Routing network packets
What makes an early GenAI project safer?
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
Who normally writes the system prompt?
The end user in each message
The application developer
The GPU driver
The vector database
Is a system prompt a reliable place to store API keys?
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
Which scenario shows multimodal AI?
Answering questions about an uploaded chart image
Sorting an integer array
Compressing a ZIP file
Running a SQL JOIN
How do multimodal models combine data types?
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
Why are foundation models reusable?
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
Which is typically a foundation model?
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
What distinguishes an agent from a single-turn chatbot?
It never uses an LLM
It only answers yes or no
It loops: decides, calls tools, observes, repeats
It runs without any instructions
Why do agents need step and permission limits?
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
Who actually runs the function in function calling?
The LLM itself, inside its weights
Your application code
The tokenizer
The vector database
What does the model return when it wants to call a tool?
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
A spam filter that outputs 'spam' or 'not spam' is typically:
Discriminative
Generative
A diffusion model
A tokenizer
Which statement describes a generative model?
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.

  1. Compute scores: query dot key for every pair of tokens
  2. Scale by the square root of the key dimension
  3. Apply softmax so scores become weights that sum to 1
  4. 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
Why is the score divided by sqrt(d_k) in attention?
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
What does the causal mask do in a decoder model?
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
Why does a fluent but wrong answer happen?
The GPU rounds numbers badly
The tokenizer deletes facts
The model optimises for plausible continuations, not verified truth
Prompts are always encrypted
Which prompt choice reduces hallucination risk?
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
Your policy documents change weekly and need citations. Which fits best?
Full fine-tuning each week
RAG
Training a new model from scratch
Raising the temperature
Which problem is better solved by fine-tuning than RAG?
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
  1. Index: load, clean, chunk, embed and store documents with metadata
  2. Retrieve: embed the question and fetch the nearest chunks
  3. Rerank (optional): a cross-encoder reorders results by true relevance
  4. Augment: place the best chunks in the prompt with instructions to use only them
  5. Generate: the LLM answers and cites sources

Quality problems usually come from the retrieval half, so evaluate retrieval separately from generation.

Take quiz
Which step happens during the offline indexing phase?
Chunking documents and storing their embeddings
Generating the final answer
Embedding the user's live question
Streaming tokens to the browser
What does an optional reranker do?
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
What is the risk of chunks that are too large?
Embeddings become exact and perfect
The tokenizer stops working
The index shrinks to zero
Embeddings blur several topics and waste prompt tokens
Why add overlap between chunks?
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.

  1. Improve chunking to follow headings and keep context together
  2. Use hybrid search (BM25 plus vectors) for names, IDs and error codes
  3. Add a reranker over the top 20 to 50 results
  4. Rewrite queries: expand abbreviations, split multi-part questions
  5. Filter by metadata such as product, language or date
  6. Pick a better embedding model for your domain and language
  7. 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
Which technique helps when users search exact error codes?
Lowering the context window
Using only a higher temperature
Hybrid keyword plus vector search
Removing metadata
Which metric measures whether the right chunk appears in the top k results?
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
With top-p set to 0.9, which tokens are sampled from?
Exactly 9 tokens
The smallest set whose probabilities sum to at least 0.9
All tokens equally
Only the single most likely token
Why do providers suggest tuning only one of temperature or top-p?
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.

  1. Start with single characters or bytes as the base vocabulary
  2. Count the most frequent adjacent pair in the training text
  3. Merge that pair into a new token
  4. 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
In BPE, what is merged repeatedly?
The most frequent adjacent pair of tokens
The longest sentence in the corpus
The two rarest letters
Random pairs of words
Why can LLMs struggle to count letters in a word?
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
Why does long context get expensive in standard attention?
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
What grows as more tokens are processed and must be kept in GPU memory?
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
Why does writing out steps help the model?
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
What is a cost of chain-of-thought prompting?
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
What is a risk of silent truncation of old messages?
The model gets faster at math
Important instructions or facts can be lost without warning
The temperature resets to 2
The GPU shuts down
Which approach avoids pasting an entire long document into a prompt?
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.

  1. Supervised fine-tuning: train on human-written ideal responses
  2. Reward model: humans rank several outputs for the same prompt, and a model learns to predict those preferences
  3. Policy optimisation: the LLM is tuned with reinforcement learning, commonly PPO, to maximise the reward score
  4. 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
What does the reward model in RLHF learn from?
Human rankings of model outputs
Raw pixel data
The tokenizer's merge rules
GPU benchmark scores
Why is a KL penalty used during RLHF?
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
Which stage turns a base model into one that follows instructions?
Tokenizer training
Vector indexing
Output caching
Instruction tuning
What data does pre-training use?
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
What does LoRA train?
The entire model from scratch
Only the tokenizer
Small low-rank matrices while the base weights stay frozen
Nothing, it edits the prompt
A team serves 20 customer-specific variants on one base model. Which fits?
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
  1. Send the user message along with tool definitions (name, description, JSON schema)
  2. The model replies with a tool call instead of text
  3. Validate the arguments, then execute the function
  4. Return the result to the model as a tool message
  5. 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
In function calling, what should your app do with the model's arguments?
Run them blindly as shell commands
Validate them before executing the function
Ignore them
Store them as the new system prompt
After running the tool, what is the next step?
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"]
  1. Receive the goal and instructions
  2. The model reasons about the next action
  3. If a tool is needed, it emits a call and the app runs it
  4. The result is appended to context
  5. 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
Which pattern describes an agent loop?
Think, act with a tool, observe, repeat
Train, deploy, retire
Tokenize, compress, archive
Index, shard, replicate only once
Which guard stops a runaway agent?
A higher temperature
A maximum step or budget limit
A longer system prompt
Removing all logs

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.

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.

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.

  1. Start from pure random noise
  2. Encode the text prompt into an embedding
  3. At each step, predict the noise and subtract a little of it, guided by the prompt
  4. 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
What does a diffusion model learn to predict?
The next word in a sentence
The noise that was added to an image
The user's age
The GPU clock speed
Why is latent diffusion cheaper?
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.

  1. Ground answers with RAG and instruct the model to use only the supplied context
  2. Require citations and check that quoted spans exist in the sources
  3. Allow abstention: tell it to say "not found in the documents"
  4. Lower temperature for factual tasks
  5. Constrain output with JSON schemas or enumerated choices
  6. Add a verification step, such as a second pass or rule-based checks on numbers and IDs
  7. Route high-risk cases to human review
  8. 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
Which instruction helps limit made-up answers in RAG?
Answer only from the provided context, or say it is not found
Always guess confidently
Ignore the retrieved documents
Use the highest temperature
Why route some responses to human review?
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
What is indirect prompt injection?
A user typing a long prompt
A GPU driver bug
A slow network connection
Malicious instructions hidden in content the model retrieves or reads
Which defense limits damage if the model is tricked?
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.

  1. Build a golden set of realistic inputs with expected answers or rubrics
  2. Automated checks: exact match, schema validity, regex, unit tests for code outputs
  3. LLM-as-judge with a clear rubric for tone, correctness or faithfulness, spot-checked against human labels
  4. RAG metrics: context recall, context precision, answer faithfulness, answer relevance
  5. Human review of samples, especially edge cases
  6. Regression runs every time the prompt, model or retriever changes
  7. 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
Why keep a golden dataset?
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
Which RAG metric asks whether the answer is supported by the retrieved text?
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
Which technique improves perceived latency without shortening total generation time?
Raising max output tokens
Streaming tokens as they are produced
Adding more few-shot examples
Disabling caching
What does model routing do?
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
When does a small specialised model make the most sense?
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
What does a model cascade do?
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.

  1. Right chunk missing? It is a retrieval problem. Check chunk size, embedding model, hybrid search, metadata filters, top-k and query rewriting.
  2. Right chunk present but ignored? It is a generation problem. Shorten the context, put key chunks first, tighten the instructions, or add a reranker.
  3. Document never indexed? Check ingestion errors, parsing of PDFs and tables, and stale indexes.
  4. Contradicting chunks? Deduplicate and prefer newer versions using metadata.
  5. 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 right passage was retrieved, but the answer ignores it. Where is the problem?
The ingestion pipeline
The tokenizer vocabulary
The vector database hardware
Generation or prompt construction
What is the first debugging step for a bad RAG answer?
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
Which architecture is typical for modern chat LLMs?
Encoder-only
Recurrent only
Decoder-only
Convolution only
BERT is best known as which type?
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
Approximately how much memory do 7B weights need at 4-bit precision?
Around 140 GB
Around 3.5 GB
Around 14 GB
Under 1 MB
What is the main trade-off of quantization?
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
Why can a good prompt alone not be enough?
Model output is probabilistic and can still go wrong
Prompts are ignored by every model
Prompts are too short to read
Guardrails are illegal
Which is an output-side guardrail?
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.

Take quiz
What is MCP?
A tokenizer algorithm
A GPU instruction set
A type of diffusion model
An open protocol for connecting AI apps to external tools and data
How do MCP and function calling relate?
An MCP client usually turns server tools into function-calling definitions
They can never work together
MCP replaces the LLM entirely
Function calling is a database
«
»

Comments & Discussions