AI Engineering

LLM Interview Preparation: Complete Crash Course

Baljeet Dogra Baljeet Dogra
β€’ β€’ 45 min read

Preparing for an LLM engineering interview? This comprehensive crash course covers everything you need to know across 15 essential topicsβ€”from prompt engineering fundamentals to production deployment strategies. By the end of this guide, you'll be ready to confidently tackle technical interviews at top AI companies.

This article includes theory, practical examples, interview questions with answers, and a complete hands-on case study where you'll build an LLM Chat Assistant with dynamic context using RAG.

LLM Interview Preparation Roadmap

15-Topic Roadmap for LLM Interview Preparation

1. Prompt Engineering & LLM Basics

Core Concepts

What is an LLM?

Large Language Models (LLMs) are neural networks trained on massive text datasets to predict the next token in a sequence. They use the Transformer architecture and are trained in two main phases:

  • β€’ Pre-training: Unsupervised learning on vast text corpora to learn language patterns
  • β€’ Fine-tuning: Supervised learning on specific tasks or instruction-following

Tokens Explained

Tokens are the basic units of text processing in LLMs. A token is roughly:

  • β€’ ~4 characters in English
  • β€’ ~0.75 words on average
  • β€’ Can be a word, subword, or character depending on the tokenizer

Example: "Hello, world!" β†’ ["Hello", ",", " world", "!"] = 4 tokens

Temperature Parameter

Temperature controls randomness in token selection:

  • β€’ Low (0-0.3): Deterministic, focused outputs (good for factual tasks, code)
  • β€’ Medium (0.5-0.7): Balanced creativity and coherence
  • β€’ High (0.8-1.0): Creative, varied outputs (good for brainstorming, creative writing)

Prompt Engineering Techniques

Zero-Shot Prompting

Asking the model to perform a task without examples.

Classify the sentiment: "I love this product!" β†’ Positive

Few-Shot Prompting

Providing examples to guide the model's behavior.

Sentiment examples:
"Great!" β†’ Positive
"Terrible" β†’ Negative
"It's okay" β†’ Neutral

Now classify: "Amazing product!" β†’ Positive

Chain-of-Thought (CoT)

Asking the model to show its reasoning step-by-step.

Q: Roger has 5 tennis balls. He buys 2 more cans of 3 balls each. How many does he have?
A: Let's think step by step:
1. Roger starts with 5 balls
2. He buys 2 cans Γ— 3 balls = 6 balls
3. Total: 5 + 6 = 11 balls

Role Prompting

Assigning a specific role or persona to the model.

You are an expert Python developer. Review this code and suggest improvements...

Common Interview Questions

Q: What's the difference between Predictive AI and Generative AI?

A: Predictive AI (discriminative models) classifies or predicts from existing data (e.g., spam detection, image classification). Generative AI creates new content by learning data distributions (e.g., text generation, image synthesis). LLMs are generative models.

Q: How do you estimate LLM API costs?

A: Cost = (Input tokens Γ— Input price) + (Output tokens Γ— Output price)

Example: GPT-4 costs ~$0.03/1K input tokens, $0.06/1K output tokens. For 1000 requests with 500 input + 200 output tokens each: Cost = (500K Γ— $0.03) + (200K Γ— $0.06) = $15 + $12 = $27

Q: What are different decoding strategies?

A:

  • β€’ Greedy: Always pick highest probability token (deterministic but repetitive)
  • β€’ Beam Search: Keep top-k sequences, explore multiple paths
  • β€’ Top-k Sampling: Sample from top k most likely tokens
  • β€’ Top-p (Nucleus): Sample from smallest set of tokens with cumulative probability β‰₯ p

Q: How to control hallucinations with prompt engineering?

A:

  • β€’ Use explicit instructions: "Only use information from the provided context"
  • β€’ Request citations: "Cite sources for each claim"
  • β€’ Add uncertainty handling: "If unsure, say 'I don't know'"
  • β€’ Use Chain-of-Thought to expose reasoning
  • β€’ Lower temperature for factual tasks

2. Retrieval Augmented Generation (RAG)

What is RAG?

RAG combines retrieval systems with LLMs to provide accurate, up-to-date, and verifiable responses. Instead of relying solely on the model's training data, RAG retrieves relevant information from external sources and includes it in the prompt.

RAG Pipeline

  1. 1. User Query: User asks a question
  2. 2. Retrieval: Query is embedded and used to search vector database for relevant documents
  3. 3. Augmentation: Retrieved documents are added to the prompt as context
  4. 4. Generation: LLM generates response based on query + retrieved context

Benefits of RAG

  • β€’ Accuracy: Grounds responses in factual, retrieved information
  • β€’ Up-to-date: Can access current information beyond training cutoff
  • β€’ Verifiable: Can cite sources for claims
  • β€’ Domain-specific: Works with proprietary/private data
  • β€’ Cost-effective: Cheaper than fine-tuning for knowledge updates

RAG vs Fine-Tuning

Aspect RAG Fine-Tuning
Use Case Knowledge injection, factual QA Behavior/style adaptation, task-specific
Cost Low (retrieval + inference) High (training compute + data)
Updates Easy (update knowledge base) Hard (requires retraining)
Transparency High (can cite sources) Low (knowledge in weights)
Latency Higher (retrieval overhead) Lower (direct inference)

Interview Questions

Q: How does RAG work?

A: RAG retrieves relevant documents from a knowledge base using semantic search (vector similarity), then includes these documents as context in the LLM prompt. The LLM generates a response grounded in the retrieved information, reducing hallucinations and enabling access to current/private data.

Q: When should you use Fine-tuning instead of RAG?

A: Use fine-tuning when you need to:

  • β€’ Change the model's behavior, tone, or output format consistently
  • β€’ Teach domain-specific reasoning patterns
  • β€’ Minimize latency (no retrieval overhead)
  • β€’ Work with structured outputs or specific task performance

Use RAG when you need to inject knowledge, work with frequently updated information, or require source attribution.

Q: What are architecture patterns for customizing LLMs with proprietary data?

A:

  • β€’ RAG: Retrieve relevant docs and include in prompt
  • β€’ Fine-tuning: Train model on proprietary data
  • β€’ Hybrid: Fine-tune for domain behavior + RAG for knowledge
  • β€’ Prompt Engineering: Include examples/instructions in prompt
  • β€’ Function Calling: LLM calls APIs to access data

3. Chunking Strategies

Why Chunking Matters

Chunking breaks large documents into smaller pieces for efficient retrieval and processing. Chunk size affects retrieval accuracy, context quality, and system performance.

Common Chunking Methods

  • β€’ Fixed-size: Split by character/token count (simple but may break semantic units)
  • β€’ Sentence-based: Split by sentences (preserves meaning)
  • β€’ Paragraph-based: Split by paragraphs (good for structured docs)
  • β€’ Semantic: Split by topic/meaning using embeddings
  • β€’ Recursive: Try multiple separators hierarchically

Key Interview Questions

Q: How to find ideal chunk size?

A: Experiment with different sizes (256, 512, 1024 tokens). Evaluate using retrieval metrics (precision, recall). Consider: embedding model context window, query complexity, document structure. Use overlap (10-20%) to preserve context across chunks.

4. Embedding Models

What are Embeddings?

Embeddings are dense vector representations of text that capture semantic meaning. Similar texts have similar vectors (measured by cosine similarity).

Popular Embedding Models

  • β€’ OpenAI text-embedding-3: High quality, 1536 dimensions
  • β€’ Sentence Transformers: Open source, customizable
  • β€’ Cohere Embed: Multilingual support
  • β€’ BGE/E5: State-of-the-art open models

Interview Questions

Q: How to improve embedding model accuracy?

A: 1) Fine-tune on domain data 2) Use hard negatives in training 3) Adjust similarity threshold 4) Try different models 5) Normalize embeddings 6) Use hybrid search (keyword + semantic)

5. Vector Databases

Vector Database Fundamentals

Vector databases store and retrieve high-dimensional vectors efficiently using specialized indexing algorithms (HNSW, IVF, PQ).

Popular Vector DBs

  • β€’ Pinecone: Managed, scalable, easy to use
  • β€’ Weaviate: Open source, GraphQL API
  • β€’ Qdrant: Rust-based, high performance
  • β€’ Chroma: Lightweight, developer-friendly
  • β€’ Milvus: Highly scalable, cloud-native

6. Advanced Search Algorithms

Search Techniques

  • β€’ Semantic Search: Vector similarity (cosine, dot product)
  • β€’ Keyword Search: BM25, TF-IDF
  • β€’ Hybrid Search: Combine semantic + keyword (RRF for merging)
  • β€’ Re-ranking: Cross-encoder models for better relevance
  • β€’ Query Expansion: Expand query with synonyms/related terms
  • β€’ Multi-hop: Iterative retrieval for complex queries

7. Language Model Internals

Transformer Architecture

Transformers use self-attention to process sequences in parallel, learning relationships between all tokens.

Key Components

  • β€’ Self-Attention: Computes attention scores between all token pairs
  • β€’ Multi-Head Attention: Multiple attention mechanisms in parallel
  • β€’ Feed-Forward Networks: Process each position independently
  • β€’ Positional Encoding: Adds position information to embeddings
  • β€’ Layer Normalization: Stabilizes training

Interview Questions

Q: How to increase context length?

A: 1) Positional interpolation 2) ALiBi (Attention with Linear Biases) 3) Sparse attention patterns 4) Sliding window attention 5) Memory-augmented architectures

8. Supervised Fine-Tuning

Fine-Tuning Approaches

  • β€’ Full Fine-Tuning: Update all model weights (expensive)
  • β€’ LoRA: Low-Rank Adaptation - train small adapter matrices
  • β€’ QLoRA: Quantized LoRA for consumer hardware
  • β€’ Prefix Tuning: Learn task-specific prefixes
  • β€’ Adapter Layers: Insert trainable layers between frozen layers

Interview Questions

Q: What is catastrophic forgetting?

A: When fine-tuning on new data causes the model to forget previously learned knowledge. Mitigation: 1) Mix old and new data 2) Use LoRA 3) Regularization 4) Multi-task learning 5) Elastic Weight Consolidation

9. Preference Alignment (RLHF/DPO)

Alignment Methods

  • β€’ RLHF: Reinforcement Learning from Human Feedback - train reward model, then optimize with PPO
  • β€’ DPO: Direct Preference Optimization - simpler, no reward model needed
  • β€’ RLAIF: Use AI feedback instead of human
  • β€’ Constitutional AI: Self-critique and revision

10. LLM Evaluation

Evaluation Metrics

  • β€’ Perplexity: How well model predicts next token
  • β€’ BLEU/ROUGE: N-gram overlap with reference
  • β€’ BERTScore: Semantic similarity using embeddings
  • β€’ Human Eval: Manual quality assessment
  • β€’ LLM-as-Judge: Use GPT-4 to evaluate outputs
  • β€’ Task-specific: Accuracy, F1, exact match for QA

11. Hallucination Control

Control Techniques

  • β€’ RAG: Ground responses in retrieved facts
  • β€’ Prompt Engineering: Explicit instructions, citations
  • β€’ Confidence Scoring: Detect uncertain outputs
  • β€’ Fact Verification: Cross-check claims with sources
  • β€’ Chain of Verification: Generate, verify, refine
  • β€’ Constrained Decoding: Limit to factual outputs

12. Deployment & Optimization

Optimization Techniques

  • β€’ Quantization: Reduce precision (INT8, INT4) - minimal accuracy loss
  • β€’ KV Cache: Cache key-value pairs for faster generation
  • β€’ Batching: Process multiple requests together
  • β€’ Speculative Decoding: Use small model to draft, large to verify
  • β€’ Flash Attention: Memory-efficient attention computation
  • β€’ Model Distillation: Train smaller model from larger

13. Agent-Based Systems

Agent Patterns

  • β€’ ReAct: Reasoning + Acting - think, act, observe loop
  • β€’ Plan-and-Execute: Plan steps, then execute
  • β€’ Function Calling: LLM calls predefined tools/APIs
  • β€’ Multi-Agent: Multiple specialized agents collaborate
  • β€’ Reflexion: Self-reflection and learning from mistakes

14. Prompt Hacking & Security

Attack Types

  • β€’ Prompt Injection: Override system instructions
  • β€’ Jailbreaking: Bypass safety guardrails
  • β€’ Data Leakage: Extract training data

Defense Tactics

  • β€’ Input validation and sanitization
  • β€’ Separate system and user prompts
  • β€’ Output filtering and moderation
  • β€’ Rate limiting and monitoring

15. Case Studies & Scenarios

Common Interview Scenarios

Scenario: RAG system not accurate

Steps: 1) Evaluate retrieval quality 2) Improve chunking 3) Fine-tune embeddings 4) Add re-ranking 5) Use hybrid search 6) Optimize prompts

Scenario: High latency in production

Solutions: 1) Quantization 2) Smaller model 3) Caching 4) Batching 5) Async processing 6) Edge deployment

πŸš€ Hands-On: Build an LLM Chat Assistant with Dynamic Context

Now let's put theory into practice! We'll build a complete RAG-based chat assistant that dynamically retrieves relevant context based on user queries.

System Architecture

Our system will have:

  • β€’ Document Ingestion: Load and chunk documents
  • β€’ Vector Store: Store embeddings in Chroma
  • β€’ Retrieval: Find relevant docs for each query
  • β€’ Generation: LLM generates response with context
  • β€’ Chat Interface: Interactive conversation

Step 1: Setup & Dependencies

First, install required packages:

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install langchain langchain-openai chromadb python-dotenv tiktoken

Create a .env file:

OPENAI_API_KEY=your_api_key_here

Step 2: Complete Implementation

Create llm_chat_assistant.py:

import os
from dotenv import load_dotenv
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import Chroma
from langchain.chains import ConversationalRetrievalChain
from langchain.memory import ConversationBufferMemory
from langchain.document_loaders import TextLoader, DirectoryLoader

# Load environment variables
load_dotenv()

class LLMChatAssistant:
    """RAG-based chat assistant with dynamic context retrieval"""
    
    def __init__(self, docs_path="./documents", persist_directory="./chroma_db"):
        self.docs_path = docs_path
        self.persist_directory = persist_directory
        self.embeddings = OpenAIEmbeddings()
        self.llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.7)
        self.vectorstore = None
        self.chain = None
        
    def load_documents(self):
        """Load documents from directory"""
        print("Loading documents...")
        loader = DirectoryLoader(
            self.docs_path,
            glob="**/*.txt",
            loader_cls=TextLoader
        )
        documents = loader.load()
        print(f"Loaded {len(documents)} documents")
        return documents
    
    def chunk_documents(self, documents):
        """Split documents into chunks"""
        print("Chunking documents...")
        text_splitter = RecursiveCharacterTextSplitter(
            chunk_size=500,
            chunk_overlap=50,
            separators=["\n\n", "\n", " ", ""]
        )
        chunks = text_splitter.split_documents(documents)
        print(f"Created {len(chunks)} chunks")
        return chunks
    
    def create_vectorstore(self, chunks):
        """Create vector store from chunks"""
        print("Creating vector store...")
        self.vectorstore = Chroma.from_documents(
            documents=chunks,
            embedding=self.embeddings,
            persist_directory=self.persist_directory
        )
        print("Vector store created!")
    
    def setup_chain(self):
        """Setup conversational retrieval chain"""
        print("Setting up retrieval chain...")
        
        # Create memory for conversation history
        memory = ConversationBufferMemory(
            memory_key="chat_history",
            return_messages=True,
            output_key="answer"
        )
        
        # Create retrieval chain
        self.chain = ConversationalRetrievalChain.from_llm(
            llm=self.llm,
            retriever=self.vectorstore.as_retriever(
                search_kwargs={"k": 3}  # Retrieve top 3 chunks
            ),
            memory=memory,
            return_source_documents=True
        )
        print("Chain ready!")
    
    def initialize(self):
        """Initialize the complete system"""
        # Load and process documents
        documents = self.load_documents()
        chunks = self.chunk_documents(documents)
        
        # Create vector store
        self.create_vectorstore(chunks)
        
        # Setup chain
        self.setup_chain()
    
    def chat(self, query):
        """Process a query and return response"""
        if not self.chain:
            raise ValueError("System not initialized. Call initialize() first.")
        
        # Get response
        result = self.chain({"question": query})
        
        # Extract answer and sources
        answer = result["answer"]
        sources = result["source_documents"]
        
        return {
            "answer": answer,
            "sources": sources
        }
    
    def interactive_chat(self):
        """Start interactive chat session"""
        print("\n" + "="*50)
        print("LLM Chat Assistant Ready!")
        print("Type 'quit' to exit")
        print("="*50 + "\n")
        
        while True:
            # Get user input
            query = input("\nYou: ").strip()
            
            if query.lower() in ['quit', 'exit', 'q']:
                print("Goodbye!")
                break
            
            if not query:
                continue
            
            # Get response
            try:
                result = self.chat(query)
                
                # Display answer
                print(f"\nAssistant: {result['answer']}")
                
                # Display sources
                if result['sources']:
                    print(f"\nπŸ“š Sources ({len(result['sources'])} documents):")
                    for i, doc in enumerate(result['sources'], 1):
                        preview = doc.page_content[:100].replace('\n', ' ')
                        print(f"  {i}. {preview}...")
                        
            except Exception as e:
                print(f"Error: {e}")

# Main execution
if __name__ == "__main__":
    # Create sample documents directory
    os.makedirs("./documents", exist_ok=True)
    
    # Create sample document if none exist
    sample_doc = "./documents/sample.txt"
    if not os.path.exists(sample_doc):
        with open(sample_doc, "w") as f:
            f.write("""
Large Language Models (LLMs) are neural networks trained on vast amounts of text data.
They use the Transformer architecture which relies on self-attention mechanisms.

RAG (Retrieval-Augmented Generation) combines retrieval with generation.
It retrieves relevant documents and includes them as context for the LLM.
This improves accuracy and allows access to up-to-date information.

Vector databases store embeddings and enable fast similarity search.
Popular options include Pinecone, Weaviate, and Chroma.
They use algorithms like HNSW for efficient nearest neighbor search.
            """)
    
    # Initialize and run
    assistant = LLMChatAssistant()
    assistant.initialize()
    assistant.interactive_chat()

Step 3: Run the Assistant

python llm_chat_assistant.py

Example Interaction:

You: What is RAG?