When should you choose RAG over Fine-Tuning (LoRA/SFT) for an enterprise AI application?
Production-Grade Answer: Use RAG when knowledge changes frequently (policies, catalogs, tickets), requires strict source citations, or enforces per-user RBAC permissions — updating vectors is instant and cheap. Use Fine-Tuning (LoRA/DPO) when you need to change model behavior, tone, strict domain jargon, or structured output formatting consistently at lower prompt-token cost. Production systems often combine both.
Q2FreshersRAG Pipeline
Explain the end-to-end architecture of a production RAG pipeline and why chunking strategy matters.
Production-Grade Answer: A RAG pipeline spans: (1) Document parsing (tables/PDF OCR), (2) Chunking (recursive/semantic/parent-child with overlap), (3) Embedding generation, (4) Vector + BM25 indexing (Qdrant/pgvector), (5) Hybrid retrieval + Cross-Encoder Reranking, and (6) Grounded prompt synthesis with inline citations. Bad chunking splits tables or separates headings from clauses, causing retrieval misses and hallucinations regardless of how strong the LLM is.
Q3FreshersTransformer Basics
What is the KV Cache in Transformer LLM inference and why is decoding memory-bandwidth bound?
Production-Grade Answer: During autoregressive generation, each new token attends to all previous tokens. Caching the computed Key (K) and Value (V) tensors avoids recomputing past layers from scratch (turning O(n^2) work per token into O(n)). However, KV Cache grows linearly with sequence length and batch size, making token generation memory-bandwidth bound on GPUs — which engines like vLLM optimize using PagedAttention.
Q4FreshersEmbeddings & Search
Why does pure semantic vector search fail on exact SKUs, error codes, or Indian legal sections?
Production-Grade Answer: Dense embeddings capture broad semantic meaning but compress exact lexical tokens like "ERR_40912" or "Section 43A". Combining Sparse lexical retrieval (BM25) with Dense Vector search via Reciprocal Rank Fusion (RRF) — known as Hybrid Search — captures both exact identifier matches and conceptual similarity.
Q5FreshersStructured Outputs
How do you guarantee 100% valid JSON outputs from an LLM in production APIs?
Production-Grade Answer: Never rely solely on "Please reply in JSON" prompt instructions. Use native Structured Outputs / Constrained Decoding (JSON Schema / Pydantic v2 grammar enforcement supported by OpenAI, Gemini, Anthropic tool schemas, and vLLM guided decoding) paired with Pydantic validation and bounded self-correction retries.
Test Yourself Right Now — 100% Free
Can you clear timed Generative AI, LLM & RAG MCQ & Spoken AI rounds?
What is the "Lost in the Middle" problem and how do Rerankers and Parent-Child Chunking solve it?
Production-Grade Answer: LLMs attend most strongly to context at the very start and end of a prompt while missing facts buried in the middle. Use Parent-Child (Small-to-Big) chunking so precise 150-token child chunks match the query cleanly while retrieving the richer 800-token parent section, then apply a Cross-Encoder Reranker (BGE-Reranker/Cohere) to keep only the top 3–5 highest-signal chunks.
Q7ExperiencedVector DB Trade-offs
How do you choose between pgvector (PostgreSQL), Qdrant, and Pinecone for an Indian enterprise product?
Production-Grade Answer: Choose pgvector when vectors are under ~5–10M and you need strict transactional joins/ACID RBAC filters alongside existing relational tables with zero extra infra. Choose Qdrant (self-hosted or cloud) for high-QPS hybrid search (dense + sparse), SQ8 quantization, payload filtering, and strict India data-residency control. Choose Pinecone when teams want zero-ops managed serverless scale and have budget for SaaS pricing.
Q8ExperiencedAgentic AI & LangGraph
Why does production Agentic AI prefer stateful graph orchestrators (LangGraph) over naive ReAct loops?
Production-Grade Answer: Naive autonomous while-loops get stuck in infinite tool retries, burn tokens uncontrollably, and lose state on crashes. LangGraph models agents as explicit typed state machines with deterministic routing, bounded step budgets, persistent Postgres checkpoints for time-travel debugging, and native Human-in-the-Loop (HITL) interrupts before high-impact actions like issuing refunds or sending emails.
Q9ExperiencedModel Context Protocol
What is MCP (Model Context Protocol) and how does it standardize enterprise LLM tool integration?
Production-Grade Answer: MCP is an open JSON-RPC protocol decoupling AI hosts/agents from external tools, resources, and prompts via standard stdio or Streamable HTTP servers. Instead of building M × N custom connectors for every LLM app and database/CRM, engineering teams expose one governed MCP server with explicit schemas, OAuth/RBAC scopes, and audit logs.
Q10ExperiencedRAG Evaluation
How do you systematically evaluate a RAG system before deploying a prompt or chunking change?
Production-Grade Answer: Maintain a versioned Golden Evaluation Dataset (real queries + expected facts/chunks) and run automated CI evals measuring two layers: (1) Retrieval metrics (Recall@K, MRR, nDCG) to confirm the right documents were fetched, and (2) Generation metrics via RAGAS/DeepEval (Faithfulness/groundedness against context, Answer Relevance, Context Precision) plus latency (TTFT) and cost-per-query regression gates.
Q11System DesignLatency & Cost Optimization
Your enterprise RAG chatbot has 6-second latency and high API bills. How do you cut latency by 70% and cost by 60%?
Production-Grade Answer: Implement: (1) Token streaming via FastAPI SSE so Time-To-First-Token (TTFT) feels instant (< 600ms), (2) Redis Semantic Caching for repeated/similar queries, (3) Prompt Prefix Caching for shared system instructions/documents, (4) Model Routing (fast small 8B/Flash models for intent classification & easy FAQs; frontier models only for complex synthesis), and (5) async parallel retrieval + tight reranked top-K context.
Q12System DesignLLM Security & DPDP
How do you protect a RAG/Agent app against Indirect Prompt Injection and India DPDP Act 2023 PII leaks?
Production-Grade Answer: Treat retrieved documents and web pages as untrusted data — never concatenate raw instructions into system roles, enforce strict least-privilege read-only tool scopes, require HITL approval for write tools, strip/mask Aadhaar/PAN/phone/email PII via Presidio/regex guardrails BEFORE sending prompts to external LLM APIs, and apply document-level ACL metadata filters inside the vector store BEFORE retrieval.
Q13System DesignSelf-Hosted Serving
Explain Continuous Batching and PagedAttention in vLLM and how they boost GPU throughput.
Production-Grade Answer: Static batching wastes GPU cycles waiting for the longest sequence in a batch to finish. Continuous Batching dynamically inserts new incoming requests at the iteration level as soon as any sequence emits EOS. PagedAttention partitions KV Cache into fixed-size non-contiguous GPU memory blocks (like OS virtual memory), eliminating fragmentation and boosting concurrent throughput 3×–10×.
Q14System DesignFine-Tuning (PEFT)
Compare LoRA, QLoRA, and DPO when adapting an open-weights Llama/Qwen model on a single GPU.
Production-Grade Answer: LoRA freezes base weights and trains tiny low-rank adapter matrices (A and B) in attention/MLP projections, cutting trainable params by >98%. QLoRA quantizes the frozen base model to 4-bit NF4 with double quantization so a 7B–8B model fine-tunes on a single 16–24 GB GPU. DPO (Direct Preference Optimization) aligns the SFT model on (chosen, rejected) pairs without training a separate RLHF reward model.
Q15System DesignMulti-Tenant AI Architecture
Design a multi-tenant Enterprise AI Knowledge Assistant for 500 Indian companies with strict data isolation.
Production-Grade Answer: Enforce tenant_id isolation at every layer: authenticated JWT claims inject mandatory tenant_id + role ACL filters into Qdrant/pgvector queries (never trusting LLM-generated filters!), encrypt per-tenant object storage buckets with separate KMS keys, isolate semantic caches by tenant_id, meter token usage per tenant in Postgres/Redis with rate budgets, and log every prompt/retrieval/citation trace in Langfuse/OpenTelemetry.
Write a clean Python implementation of Reciprocal Rank Fusion (RRF) combining BM25 and Vector rankings.
Production-Grade Answer: RRF merges heterogeneous score scales (cosine similarity vs unbounded BM25) purely by rank position using 1 / (k + rank), typically with k=60 — consistently lifting Recall@10 on technical & legal queries.
Reciprocal Rank Fusion (RRF) for Hybrid RAG in Python
def reciprocal_rank_fusion(ranked_lists: list[list[str]], k: int = 60) -> list[tuple[str, float]]:
scores: dict[str, float] = {}
for ranking in ranked_lists:
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
return sorted(scores.items(), key=lambda x: x[1], reverse=True)
Q17FreshersStructured OutputsPYTHON
Show how to enforce strict Pydantic v2 structured extraction from an LLM with zero regex parsing.
Production-Grade Answer: Pass a Pydantic schema directly to the model’s structured output / JSON Schema grammar interface so token sampling guarantees valid keys, enums, and numeric ranges before your application logic runs.
Pydantic v2 Schema for Constrained LLM Decoding
from typing import Literal
from pydantic import BaseModel, Field
class SupportTriage(BaseModel):
intent: Literal["billing", "technical", "refund"]
confidence: float = Field(ge=0.0, le=1.0)
requires_human_approval: bool
citations: list[str]
Q18FreshersAdvanced RAG Patterns
What is Contextual Retrieval and HyDE (Hypothetical Document Embeddings), and when do they help?
Production-Grade Answer: Contextual Retrieval prepends a brief document-level context summary to every chunk before embedding so orphan chunks ("Revenue grew 12%") keep their company and quarter metadata. HyDE prompts an LLM to draft a hypothetical answer and embeds that answer to bridge vocabulary gaps between short user queries and dense technical docs.
Q19ExperiencedLangGraph State MachinesPYTHON
Show a stateful LangGraph Agent with conditional routing and a Human-in-the-Loop interrupt checkpoint.
Production-Grade Answer: Defining explicit TypedDict state, conditional edges, and interrupt_before=["execute_refund"] with a persistent checkpointer ensures risky actions pause for human sign-off and resume cleanly across server restarts.
LangGraph Stateful Agent with HITL Interrupt
from typing import TypedDict
from langgraph.graph import StateGraph, END
class AgentState(TypedDict):
query: str
retrieved_docs: list[str]
needs_refund_tool: bool
answer: str
graph = StateGraph(AgentState)
graph.add_node("retrieve", retrieve_node)
graph.add_node("execute_refund", refund_node)
graph.add_node("synthesize", synthesize_node)
graph.set_entry_point("retrieve")
graph.add_conditional_edges("retrieve", lambda s: "execute_refund" if s["needs_refund_tool"] else "synthesize")
graph.add_edge("execute_refund", "synthesize")
graph.add_edge("synthesize", END)
app = graph.compile(checkpointer=postgres_saver, interrupt_before=["execute_refund"])
Q20ExperiencedCorrective RAG (CRAG)
How do Corrective RAG (CRAG) and Self-RAG reduce hallucinations compared to standard single-shot RAG?
Production-Grade Answer: Standard RAG blindly injects top-K retrieved chunks even when none answer the query. CRAG inserts a lightweight grader step after retrieval: if relevance is low, it rewrites the query or routes to a fallback search/abstention path ("I do not have verified context for this") instead of letting the LLM fabricate.
Q21ExperiencedGraphRAG vs Vector RAG
When does GraphRAG outperform standard Vector RAG, and what are its indexing trade-offs?
Production-Grade Answer: Standard Vector RAG excels at localized fact lookups but fails on multi-hop global synthesis ("Which suppliers impact all Tier-1 pharma products?"). GraphRAG extracts entity-relation graphs and community summaries for multi-hop reasoning, at the cost of higher ingestion LLM spend and graph-sync complexity.
Q22ExperiencedModel Context ProtocolPYTHON
Show a minimal governed MCP (Model Context Protocol) tool definition enforcing read-only tenant scoping.
Production-Grade Answer: MCP servers expose typed tools with strict parameter schemas and inject server-side auth/tenant claims rather than trusting the LLM to pass tenant IDs.
Governed FastMCP Read-Only Tool Server Snippet
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("enterprise-orders-mcp")
@mcp.tool()
async def get_order_status(order_id: str) -> dict:
"""Read-only order lookup scoped to the authenticated tenant."""
tenant_id = get_verified_tenant_from_oauth_context()
return await order_repo.find_scoped(tenant_id=tenant_id, order_id=order_id)
Q23System DesignLLM-as-a-Judge Evals
What biases affect LLM-as-a-Judge evaluations (verbosity, position bias) and how do you mitigate them?
Production-Grade Answer: LLM judges favor longer responses, prefer Option A over Option B (position bias), and self-favor outputs from the same model family. Mitigate by swapping A/B order and averaging, using discrete rubric checklists (1–5 anchored criteria) instead of vague scores, calibrating against human-labeled golden sets, and preferring deterministic code assertions wherever possible.
Q24System DesignModel Quantization
Compare AWQ, GPTQ, FP8, and GGUF quantization when deploying open-weights LLMs.
Production-Grade Answer: AWQ (Activation-Aware Weight Quantization) protects the top ~1% salient weights in FP16 for strong 4-bit GPU accuracy + fast vLLM kernels. FP8 delivers near-lossless throughput on Hopper/Ada GPUs (H100/L40S). GPTQ is classic post-training 4-bit GPU quantization, while GGUF powers local CPU/Apple Silicon hybrid inference via llama.cpp.
Q25System DesignFastAPI SSE StreamingPYTHON
Show how to stream LLM tokens over Server-Sent Events (SSE) in FastAPI with client disconnect handling.
Production-Grade Answer: Streaming tokens cuts perceived latency from 6 seconds to < 500ms TTFT; checking request.is_disconnected() stops wasted upstream LLM generation immediately if the user closes the tab.
FastAPI SSE Token Streaming with Disconnect Guard
from fastapi import Request
from fastapi.responses import StreamingResponse
@app.post("/chat/stream")
async def stream_chat(request: Request, prompt: str):
async def event_gen():
async for token in llm_client.astream(prompt):
if await request.is_disconnected():
break
yield f"data: {token}\n\n"
return StreamingResponse(event_gen(), media_type="text/event-stream")