AI and LLM Integration: RAG, Prompts and APIs Interview Questions
2,431 multiple-choice tech interview questions on AI and LLM Integration: RAG, Prompts and APIs: How LLMs work for developers, prompt design and structured output, LLM APIs, streaming, rate limits and cost control, embeddings, vector indexes and hybrid search; retrieval-augmented generation, chunking, reranking, citations and retrieval quality; tool calling, the Model Context Protocol (MCP) and agents; evaluating and testing LLM features, including eval sets, LLM-as-a-judge and online evaluation; AI security, including prompt injection, the OWASP LLM Top 10, agent isolation and output handling; production LLM systems, including latency, cost, model serving and operations. Written for technical phone screens and interview prep, organized by subtopic, with a short explanation for every answer. Learn the 187 key terms with the flashcards first, then test yourself.
Take the practice test · Flashcards · All study tools
What it covers
- 11.1 LLM fundamentals: tokens, models and sampling
- 11.2 Prompt design and structured output
- 11.3 LLM APIs: streaming, limits and cost control
- 11.4 Embeddings and vector search
- 11.5 RAG pipelines and retrieval quality
- 11.6 Tool calling, MCP and agents
- 11.7 Evaluating and testing LLM features
- 11.8 AI security: prompt injection and the OWASP LLM Top 10
- 11.9 Production LLM systems: latency, cost, models and operations
Key terms
11.1 LLM fundamentals: tokens, models and sampling
- BPE
- Byte pair encoding; learns a vocabulary by repeatedly merging frequent adjacent symbol pairs
- Causal attention
- Attention mask that blocks each token from seeing future tokens
- Chinchilla scaling
- Compute-optimal pretraining that balances parameter count with tokens trained
- Context window
- Maximum tokens a model can consider in one request
- Distillation
- Training a small model to imitate a larger one
- DPO
- Direct preference optimization; trains on preference pairs without a separate reward-model RL loop
- GQA
- Grouped-query attention; several query heads share one key/value head
- Grounding
- Tying model answers to supplied sources so claims can be checked
- Hallucination
- Confident output not supported by facts or sources
- Instruction tuning
- Training a base model to follow requests and chat
- Knowledge cutoff
- Date after which a model's training data has little information
- Logprobs
- Log probabilities of generated tokens, used for confidence scores
- Mixture of experts
- Model that routes each token to a few expert subnetworks
- Multimodal model
- Model that handles more than text, such as images or audio
- Open-weight model
- Model whose trained weights can be downloaded and run locally
- Quantization
- Storing model weights at lower precision to save memory and speed inference
- RLHF
- Reinforcement learning from human feedback; tunes models toward preferred answers
- RoPE
- Rotary position embeddings; encode position by rotating query and key vectors
- Stop sequence
- String that ends generation when the model produces it
- Temperature
- Sampling setting; lower values are more deterministic, higher more varied
- Token
- Unit of text a model reads and generates; basis for limits and pricing
- Top-k sampling
- Sample the next token only from the k most likely candidates, then renormalize
- Top-p sampling
- Samples from the smallest token set whose probabilities add up to p
- Transformer
- Neural network architecture built on self-attention; basis of modern LLMs
11.2 Prompt design and structured output
- Chain-of-thought
- Prompting the model to reason step by step before answering
- Context engineering
- Choosing which instructions, data, tools and history fill a model's context
- Delimiters
- Tags or quotes that separate instructions from data in a prompt
- Grammar-constrained decoding
- Restricting token sampling so the completion must stay inside a formal grammar
- In-context learning
- Teaching a task in the prompt with instructions or examples, without updating model weights
- Instruction hierarchy
- A documented order in which some message roles outrank others when instructions conflict
- JSON mode
- API setting that guarantees syntactically valid JSON output
- Least-to-most prompting
- Decomposing a problem and solving easier subproblems first, then the harder one
- Meta-prompting
- Using an LLM to write or improve prompts
- Output parser
- Application code that turns model text into a typed value and fails when the text does not match
- Prefilling
- Starting the assistant's reply with given text to steer it
- Prompt chaining
- Splitting a task into steps, each prompt using the previous output
- Prompt registry
- A catalog of named, versioned prompts that applications can call by identifier
- Prompt template
- Reusable prompt with placeholders filled per request
- Self-consistency
- Sampling several reasoning paths and taking the majority answer
- Step-back prompting
- First answering a more general question, then using that to solve the specific case
- System prompt
- Instructions setting the model's role, rules and tone for a conversation
- Zero-shot prompting
- Asking for a task with instructions but no worked examples
11.3 LLM APIs: streaming, limits and cost control
- Batch API
- Asynchronous bulk requests at a discount, with results returned later
- Chat completions
- API style taking a list of role-tagged messages and returning a reply
- Conversation summarization
- Condensing older chat turns to fit the context window
- Data retention policy
- How long a provider stores prompts and outputs and how it uses them
- Few-shot prompting
- Including examples in the prompt to show the pattern
- Finish reason
- Field saying why generation stopped, such as stop, length or a tool call
- Max output tokens
- A request cap on how many new tokens the model may generate for that reply
- Model fallback
- Switching to another model or provider when the primary fails
- Prompt cache
- A provider-side reuse of a repeated prompt prefix, usually billed at a discount after the prefix is warm
- Realtime API
- Low-latency API streaming audio or text both ways for voice apps
- Reasoning tokens
- Hidden thinking tokens on a reasoning model that are often billed even when the visible reply is short
- Requests per minute
- Rate limit on how many API calls an account, project, or key may start in a minute
- Retry-After
- HTTP header or equivalent field that says how long to wait before retrying a rate-limited or overloaded request
- Server-sent events
- One-way HTTP stream used to deliver tokens as they're generated
- Structured outputs
- Constraining model output to a JSON schema
- Time to first token
- Delay before the first output token arrives
- Token usage
- The response breakdown of input, output, and often cached or reasoning tokens used for billing and attribution
- Tokenizer
- Component that splits text into tokens; used to count tokens before sending
- Tokens per minute
- Rate limit on total tokens an account can process per minute
- Zero data retention
- A provider commitment not to keep prompts and outputs for later use, beyond brief processing
11.4 Embeddings and vector search
- Approximate nearest neighbor
- Fast vector search that trades a little accuracy for speed
- Bi-encoder
- Model embedding queries and documents separately for fast search
- BM25
- Keyword ranking function based on term frequency and rarity
- Cross-encoder
- Model scoring a query and document together; used for reranking
- Embedding
- Vector representation of meaning used for similarity search
- Embedding dimension
- Length of each embedding vector; affects storage and search cost
- HNSW
- Graph-based ANN index (Hierarchical Navigable Small World)
- HyDE
- Embedding a generated hypothetical answer to find real documents
- IVF index
- ANN index that clusters vectors and probes the nearest clusters
- Matryoshka embeddings
- Vectors trained so truncated leading dimensions still work
- Metadata filtering
- Restricting vector results by fields such as tenant or date
- pgvector
- PostgreSQL extension adding vector types and similarity indexes
- RAG
- Retrieve relevant documents and add them to the prompt at query time
- Reciprocal rank fusion
- Merges ranked lists by summing 1/(k + rank)
- Reranker
- Model that rescores retrieved candidates for relevance
- Semantic search
- Search by meaning rather than exact words
- Sparse embedding
- Mostly-zero vector weighting vocabulary terms, like SPLADE
- Product quantization
- Compressing a vector by coding each subvector against a small codebook
- DiskANN
- Graph-based ANN index designed to serve large collections from SSDs
- Maximal marginal relevance
- Reranking that trades some relevance for diversity by penalizing items like those already chosen
- Asymmetric embeddings
- Query and document encodings that use different prefixes, instructions or towers
- MTEB
- Massive Text Embedding Benchmark, a suite for comparing embedding models across tasks
- Binary quantization
- Compressing each dimension to one bit so search can use fast Hamming-style distances
- nprobe
- How many IVF clusters a query searches; trades recall for latency
11.5 RAG pipelines and retrieval quality
- Agentic RAG
- An agent decides when and how to search, possibly iterating
- Chunk overlap
- Shared text between neighboring chunks so ideas aren't split
- Chunking
- Splitting documents into passages for embedding and retrieval
- Contextual retrieval
- Prefixing chunks with context about their source document
- Faithfulness
- Whether an answer's claims are supported by the retrieved context
- GraphRAG
- RAG using a knowledge graph of entities and relations
- Late chunking
- Embed the whole document, then pool token vectors per chunk
- Mean reciprocal rank
- Average of 1 / rank of the first relevant result
- Parent-document retrieval
- Match small chunks, then send their larger parent sections
- Query rewriting
- Reformulating the user's question to retrieve better matches
- Recall@k
- Share of relevant documents found in the top k results
- Text-to-SQL
- Model generates SQL from a question; run read-only with guardrails
- Top-k
- Number of highest-scoring results returned per query
- Lost in the middle
- Models often use evidence at the start or end of a long context less reliably than in the middle
- Query decomposition
- Splitting a complex question into sub-questions and retrieving for each
- Contextual compression
- Reducing retrieved passages to the spans that actually bear on the question
- Self-RAG
- A retrieve-and-generate style where the model can decide to search and then critique the evidence
- Corrective RAG
- A RAG pattern that checks retrieved documents and retries or falls back if they look weak
- Multi-hop retrieval
- Running a later search that depends on what a previous retrieve step found
- nDCG
- Normalized discounted cumulative gain: a graded, position-discounted score of a ranked list
11.6 Tool calling, MCP and agents
- A2A protocol
- Agent2Agent: standard for communication between AI agents
- Agent loop
- Cycle of model decision, tool run and result until a goal is met
- Code sandbox
- Isolated environment for running untrusted, model-written code
- Computer-use agent
- Agent that operates a screen or browser by clicking and typing
- Excessive agency
- Risk from giving an LLM agent too many tools or permissions
- Human in the loop
- A person approves risky agent actions before they run
- MCP
- Open protocol connecting AI apps to tools and data sources
- MCP resource
- Data an MCP server exposes for context, identified by URI
- Multi-agent system
- Several coordinating agents, often under an orchestrator
- Parallel tool calls
- Several independent tool calls requested in one model turn
- Prompt injection
- Untrusted text trying to override an LLM app's instructions
- ReAct
- Pattern interleaving reasoning steps with tool actions and observations
- Streamable HTTP
- MCP's transport for remote servers
- Tool calling
- Model requests a defined function; the app executes it
- Tool choice
- Setting that forces, allows or blocks tool use on a request
- MCP host
- The application that owns the MCP client, the user interface, and approvals
- Tool schema
- JSON Schema describing a tool's parameters so the model can fill them
- MCP tool annotations
- Server hints that a tool is read-only, destructive, idempotent, or open-world
- Plan-and-execute
- An agent drafts a plan first, then carries out steps and revises if needed
- Tool routing
- Selecting a short, relevant subset of tools to send on a request
- Agent handoff
- Passing a task and the needed context from one agent to a specialist
- MCP roots
- Client-advertised filesystem or URI boundaries that limit a server's access
11.7 Evaluating and testing LLM features
- Benchmark contamination
- Test data leaking into training, inflating benchmark scores
- Eval set
- Representative test cases used to measure LLM feature quality
- Golden dataset
- Curated inputs with expected outputs or grading criteria for evals
- Inter-rater agreement
- How consistently different reviewers score the same outputs
- LLM as a judge
- Using a model to grade outputs against a rubric or reference
- Online evaluation
- Measuring quality on live traffic via feedback, sampling or A/B tests
- pass@k
- Chance that at least one of k sampled answers is correct
- Ragas
- Open-source toolkit for evaluating RAG pipelines
- Red teaming
- Deliberately attacking a system to find failures
- Rubric
- Explicit grading criteria that make scores consistent
- Shadow testing
- Running a new model on live requests without showing its output
- Trace evaluation
- Grading an agent's steps and tool calls, not just its answer
- G-Eval
- A rubric-based judging method where the model writes a chain of thought and then a score
- Verbosity bias
- A tendency for judges or raters to score longer, wordier answers more highly than they deserve
- Cohen's kappa
- A chance-corrected measure of agreement between two raters
- BERTScore
- An automatic metric that compares candidate and reference using contextual embeddings
- Eval harness
- Software that runs a suite of cases, applies scorers and records comparable results
- Slice evaluation
- Reporting quality on subsets of cases, such as locale, intent or severity, not only a blended average
- Pairwise judging
- Having a judge or rater compare two outputs on the same input and pick a winner, loser or tie
11.8 AI security: prompt injection and the OWASP LLM Top 10
- Data poisoning
- Corrupting training or retrieval data to change model behavior
- Dual LLM pattern
- Privileged planner model plus a quarantined model for untrusted text
- EU AI Act
- EU law regulating AI by risk level
- Guardrails
- Filters or classifiers checking inputs and outputs for unsafe content
- Improper output handling
- Passing model output unchecked into browsers, shells or databases
- Indirect prompt injection
- Instructions hidden in content the model reads, like web pages or email
- Jailbreak
- Prompt crafted to make a model ignore its safety rules
- Lethal trifecta
- Private data + untrusted content + exfiltration channel in one agent
- Model extraction
- Copying a model's behavior through heavy querying
- OWASP Top 10 for LLM Applications
- OWASP's ranked list of LLM app risks
- Safetensors
- Model weight format that can't run code on load, unlike pickle
- System prompt leakage
- Risk of relying on prompts to hide secrets or rules
- Unbounded consumption
- Uncontrolled usage that drives cost or denies service
- Direct prompt injection
- Malicious instructions typed into a user-controlled input that the app sends to the model
- Markdown exfiltration
- Using rendered images or links in model output to send data to an attacker-controlled URL
- Security trimming
- Filtering retrieval results to documents the requesting user is allowed to see before they reach the model
- Spotlighting
- A prompting technique that marks or encodes untrusted content so the model is more likely to treat it as data
- Many-shot jailbreak
- A jailbreak that packs the context with many harmful examples to weaken refusal behavior
- Embedding inversion
- Recovering an approximation of the original text from a stored or stolen embedding vector
- Prompt canary
- A unique, otherwise useless string placed in a prompt so that seeing it later suggests the prompt was leaked
11.9 Production LLM systems: latency, cost, models and operations
- AI gateway
- Central proxy for model calls handling keys, routing, quotas and logs
- Continuous batching
- Adding requests to a running batch as others finish
- Fine-tuning
- Further training a model on examples to shape style or task behavior
- Graceful degradation
- Falling back to simpler behavior when the model fails
- KV cache
- Stored attention keys and values for earlier tokens during generation
- LoRA
- Low-Rank Adaptation: fine-tuning small adapter matrices instead of all weights
- Model deprecation
- Provider retiring a model version on a published date
- Model routing
- Sending each request to the cheapest model that can handle it
- On-device inference
- Running a model locally on a phone or laptop
- Prefill and decode
- Prompt processing phase vs token-by-token generation phase in inference
- Provisioned throughput
- Reserved model capacity at a fixed price
- Speculative decoding
- Draft model proposes tokens; the large model verifies them
- vLLM
- Open-source high-throughput inference server for LLMs
- PagedAttention
- A block-based way to store the KV cache so a serving engine can pack sequences without huge contiguous reservations
- Tensor parallelism
- Splitting a model's tensors across GPUs that communicate during each inference step
- Disaggregated serving
- Running prefill and decode on separate pools so heavy prompts do not stall token generation
- Automatic prefix caching
- Reusing computed KV blocks for an identical prompt prefix so later requests can skip that prefill
- Multi-LoRA serving
- Keeping many LoRA adapters loaded on one base model and applying the right one per request
- KV cache offloading
- Moving some KV blocks to CPU memory or disk when they do not fit in GPU memory
- Chunked prefill
- Processing a long prompt in slices so the scheduler can run decode work between those slices
Sample practice questions
What is a token in the context of large language models?
- A security credential that authenticates each call to the model API
- A chunk of text, often part of a word; usage and pricing count tokens
- Exactly one character of text, so a 10-letter word is 10 tokens
- One full sentence of text, split wherever a period appears
Answer: B. A chunk of text, often part of a word; usage and pricing count tokens In English, one token is roughly three to four characters on average.
What is the purpose of a system prompt (system or developer message)?
- To securely store the signed-in user's password for later calls
- To configure the GPU's memory and batch size for the request
- To set the model's role, rules and tone, separate from user input
- To record any API errors that happened during the conversation
Answer: C. To set the model's role, rules and tone, separate from user input User messages should not be able to override system rules, though prompt injection tries to.
Why do apps stream LLM responses (for example via server-sent events)?
- Streaming makes the total response noticeably cheaper
- Streaming is required whenever the output must be JSON
- Users see tokens as they arrive, cutting perceived latency
- Streaming hides any errors from the user until the end
Answer: C. Users see tokens as they arrive, cutting perceived latency Time to first token matters more to users than total generation time.
What is an embedding?
- A compressed ZIP archive of a document, stored alongside the original
- A vector of numbers capturing meaning, so similar texts sit close together
- An iframe that embeds a chatbot widget into another website's pages
- A database index created on a text column to speed up LIKE queries
Answer: B. A vector of numbers capturing meaning, so similar texts sit close together Embeddings power semantic search, clustering and RAG retrieval.
What is the difference between fine-tuning and retrieval-augmented generation (RAG) for adding company knowledge?
- RAG adds retrieved docs to the prompt; fine-tuning changes weights, better for style
- Fine-tuning is always cheaper than RAG and much easier to keep up to date
- RAG permanently changes the model's weights with each document retrieved
- They're the same technique, just described with two different names
Answer: A. RAG adds retrieved docs to the prompt; fine-tuning changes weights, better for style RAG is usually the first choice for knowledge that changes or must be cited.
What is tool calling (function calling)?
- The model requests a function you defined; your code runs it and returns the result
- The model directly executes arbitrary code on your servers without any involvement
- Calling the LLM's API from a mobile phone instead of from a web server
- A way for developers to call the model's own internal functions directly
Answer: A. The model requests a function you defined; your code runs it and returns the result Your application stays in control of what actually runs.
How should teams evaluate changes to prompts or models?
- By trying a single example by hand and shipping if it looks fine
- With a graded eval set of representative inputs, run before deploying
- By measuring only the average length of the model's responses
- They don't need to, because LLM output is always deterministic
Answer: B. With a graded eval set of representative inputs, run before deploying Treat prompts like code: version them and test for regressions.
Why must RAG retrieval respect document permissions?
- Otherwise the model may reveal documents the user can't access
- Applying permissions makes the stored embeddings much smaller
- LLMs automatically enforce each document's permissions anyway
- Retrieval doesn't work at all unless permissions are configured
Answer: A. Otherwise the model may reveal documents the user can't access Filter by the user's access (security trimming) before passing chunks to the model.
A team wants to cut LLM costs by half for a high-volume classification feature. Which approach is most sensible?
- Always switch to the largest model the provider offers
- Send each request three times and keep the cheapest answer
- Remove all input validation to save processing time
- Evaluate a smaller model, plus caching and shorter prompts
Answer: D. Evaluate a smaller model, plus caching and shorter prompts Model routing (small model first, escalate to a larger one when needed) is a common pattern.
What is the context window of an LLM?
- The browser window or chat panel where the conversation is shown
- The time limit the API allows for a single response to finish
- The number of users who are allowed to call the model at once
- The most tokens, prompt plus output, the model handles in one request
Answer: D. The most tokens, prompt plus output, the model handles in one request Anything outside the context window is invisible to the model for that request.
More Architecture
- System Design Interview Fundamentals
- Monoliths vs Microservices
- Event-Driven Architecture
- Scalability: Horizontal and Vertical Scaling, Sharding and Partitioning
- CAP Theorem and Distributed Consistency
- High Availability and Fault Tolerance
- API Gateways and Service Meshes
- Domain-Driven Design
- Clean and Hexagonal Architecture
- Security Architecture: Zero Trust and OWASP Top 10