Interview Prep
GenAI Interview Questions — RAG and Agents
Retrieval-Augmented Generation (RAG) and Agents bridge the gap between static model knowledge and dynamic, real-world data requirements. RAG provides factual grounding by injecting relevant context into prompts, while Agents enable autonomous decision-making through tool orchestration. These architectures are essential for building production-grade systems that require high accuracy and complex workflow automation.
The Core Mechanics of RAG
Retrieval-Augmented Generation works by addressing the inherent limitation of static model weights: they are frozen in time and lack access to private, proprietary datasets. By decoupling the knowledge base from the language model, RAG allows a system to query a vector database for relevant information before generating a response. When a user asks a question, the system first transforms that query into a semantic vector, then performs a similarity search to retrieve the most pertinent document chunks. This context is then injected into the prompt as a source of truth, effectively grounding the model's output. The genius of this approach lies in reducing hallucinations, as the model is forced to adhere to the provided retrieved documents rather than relying solely on its internal, potentially outdated training parameters. Understanding this retrieval loop is critical for troubleshooting low-precision results in production systems.
# Simple retrieval logic using cosine similarity on document embeddings
import numpy as np
def retrieve_context(query_vec, document_vecs, documents, top_k=2):
# Calculate cosine similarity between query and all stored documents
scores = np.dot(document_vecs, query_vec) / (np.linalg.norm(document_vecs, axis=1) * np.linalg.norm(query_vec))
# Get indices of the top k highest scoring documents
top_indices = np.argsort(scores)[-top_k:][::-1]
return [documents[i] for i in top_indices]Vector Stores and Semantic Search
Vector databases are the storage engines that make large-scale retrieval feasible within milliseconds. Instead of traditional keyword matching, these stores utilize high-dimensional vector spaces where semantic similarity translates to proximity in that space. When you embed text, you transform linguistic structures into numerical sequences that represent meaning. During search, the database performs a nearest-neighbor calculation to find vectors close to the query vector. The reason this works better than simple keyword lookup is that it handles synonymy and context; a query about 'monetary policy' can successfully retrieve documents about 'interest rate adjustments' even if the exact keywords do not overlap. Maintaining a healthy vector index requires careful consideration of chunking strategies, as the granularity of your text chunks dictates the precision of the information provided to the model during the prompt generation phase.
# Mock indexing for a vector database
class VectorStore:
def __init__(self): self.index = []
def add(self, vector, metadata):
# Stores the vector embedding with associated document source
self.index.append({'vec': vector, 'meta': metadata})
def search(self, query_vec):
# Return documents based on proximity to the query
return sorted(self.index, key=lambda x: np.dot(x['vec'], query_vec), reverse=True)Prompt Engineering for Contextual Grounding
Once the relevant information is retrieved, the challenge shifts to how you integrate it into the model's prompt. The goal is to enforce a strict constraint where the model prioritizes the retrieved context over its pre-trained memory. This is achieved through systematic prompt engineering, where you define clear delimiters for the context and explicitly instruct the model to answer only based on provided materials. By structuring the prompt with a clear 'context' block and a 'question' block, you minimize the risk of the model blending facts. Furthermore, specifying the output format—such as asking for citations from the context—creates a feedback mechanism that encourages the model to 'show its work'. If the model ignores instructions, it is often because the retrieval step returned irrelevant data, which demonstrates that the bottleneck is often the quality of the search rather than the prompt itself.
# Formatting retrieved documents into a grounded system prompt
def construct_prompt(query, context_list):
# Injecting context with clear demarcations to reduce hallucination
context_str = "\n".join([f"Source {i}: {doc}" for i, doc in enumerate(context_list)])
return f"Context:\n{context_str}\n\nQuestion: {query}\nAnswer based strictly on the context above."Introduction to AI Agents
Agents represent an evolution from passive text generation to active task execution. While a RAG system provides facts, an Agent possesses a loop of perception, reasoning, and action. The Agent is given a goal, a set of available tools, and a scratchpad to track its thought process. It breaks a complex query into a sequence of sub-tasks, deciding which tool—such as a calculator, a database query function, or a web search API—is needed to progress. This works because the language model acts as an internal controller, parsing its own outputs to select the next action. The primary challenge in building Agents is managing the 'reasoning loop,' where the agent must determine when it has sufficient information to formulate a final answer, preventing infinite tool-calling cycles that waste resources and degrade response quality.
# A basic ReAct (Reasoning and Acting) loop pattern
def agent_step(task, tools):
thought = "I need to check the inventory to answer this request."
# Selecting the tool based on the model's logical reasoning
tool_call = tools['inventory_lookup'].run(task)
return f"Thought: {thought}\nResult: {tool_call}"Tool Orchestration and Error Handling
Orchestrating tools effectively requires robust error handling and input validation. Because Agents operate by calling functions defined in code, the model might occasionally pass malformed arguments or attempt to use tools that do not exist. To mitigate this, developers should implement a 'guardrail' layer that sanitizes model output before it executes a function. This acts as a safety gate, ensuring that the model's autonomous decision-making does not lead to unauthorized system changes or memory overflows. Additionally, logging the agent's thought chain is critical for debugging; since agents make non-deterministic decisions, you need to see exactly why it chose a particular tool path. By wrapping each tool execution in a try-except block, you allow the agent to receive an error message and attempt a corrective action, which creates a self-healing loop that is essential for reliable autonomous workflows.
# Tool wrapper with safety guardrails
def execute_tool(tool_name, tool_func, params):
try:
# Validate parameters before execution to prevent system crashes
if not isinstance(params, dict): raise ValueError("Invalid input format")
return tool_func(**params)
except Exception as e:
# Return error to model so it can re-plan its task
return f"Tool execution failed: {str(e)}. Attempt a different strategy."Key points
- RAG systems decouple knowledge bases from model weights to ensure information accuracy.
- Semantic search in vector databases improves retrieval relevance by understanding contextual meaning.
- High-quality context injection requires clear delimiters to prevent the model from hallucinating.
- Agents extend language models by enabling autonomous tool usage and task decomposition.
- The ReAct loop allows models to refine their reasoning through iterative tool execution.
- Guardrails are necessary to sanitize agent outputs and prevent execution errors.
- Debugging agent workflows requires full visibility into the model's internal thought process.
- Production-grade systems prioritize retrieval precision to minimize the workload on the language model.
Common mistakes
- Mistake: Confusing RAG with fine-tuning. Why it's wrong: Fine-tuning changes model behavior/knowledge, while RAG provides context. Fix: Use RAG for real-time knowledge retrieval and fine-tuning for specific style or format adjustments.
- Mistake: Assuming an agent is just a prompt chain. Why it's wrong: Agents require reasoning and tool-use loops. Fix: Understand that agents must possess a decision-making capability to decide which tool to call based on input.
- Mistake: Neglecting chunk size optimization. Why it's wrong: Improper chunking leads to missing context or noise. Fix: Experiment with semantic chunking to ensure that retrieved fragments represent coherent concepts.
- Mistake: Over-reliance on vector similarity. Why it's wrong: Vector search might find semantically similar documents that are irrelevant to the specific task. Fix: Implement a re-ranking step after the initial retrieval to boost precision.
- Mistake: Failing to implement guardrails for tool use. Why it's wrong: Agents can enter infinite loops or hallucinate tool parameters. Fix: Introduce strict schema validation for tool inputs and limit the maximum number of reasoning iterations.
Interview questions
What is Retrieval-Augmented Generation (RAG) and why is it essential for enterprise applications?
Retrieval-Augmented Generation, or RAG, is an architectural pattern that enhances a model by retrieving relevant external data before generating a response. It is essential for enterprise use because large language models are trained on static data and can suffer from hallucinations. RAG allows the system to ground its output in proprietary, real-time documentation, ensuring accuracy and reducing the risk of generating outdated or incorrect information. By providing the model with specific context in the prompt, we effectively extend its knowledge base without needing expensive retraining, making it far more reliable for business-critical tasks.
Explain the role of vector databases in a RAG pipeline.
Vector databases are critical in RAG because they store and efficiently search through high-dimensional vector embeddings, which represent the semantic meaning of data. When a user asks a question, the system converts that query into an embedding and performs a similarity search within the vector database to find the most contextually relevant documents. Tools like Pinecone or Weaviate allow for fast retrieval even with millions of records. Without vector search, we would be limited to keyword matching, which fails to capture intent or synonym-based relationships, ultimately leading to poor context retrieval.
What are AI Agents and how do they differ from standard prompt chains?
AI Agents are autonomous entities that use a model as a reasoning engine to decide which tools to call and what actions to take to achieve a goal. Unlike a standard prompt chain, which follows a rigid, linear sequence of instructions, an agent has a feedback loop. It analyzes its own progress, manages its own memory, and can decide to execute Python code, search the web, or query a database based on the current state. An example loop might look like: `thought: I need data, action: search_tool, observation: data_received, final_answer: synthesized_output.` This flexibility allows agents to handle complex, multi-step workflows.
Compare 'Naive RAG' with 'Advanced RAG' techniques like query transformation.
Naive RAG simply retrieves chunks based on a raw user query and passes them to the model, which often leads to poor performance if the query is ambiguous. Advanced RAG, specifically query transformation, improves this by using the model to rewrite, expand, or decompose the user's intent into multiple sub-queries before searching the database. This is superior because it bridges the gap between how a user expresses a thought and how technical documents are stored. By generating multiple retrieval vectors from a single request, the system ensures a much higher recall of relevant information, resulting in more coherent and complete final answers.
How do you handle the 'context window' limitation when implementing RAG for large documents?
To handle context window limitations, we implement a multi-stage process: document chunking, semantic retrieval, and re-ranking. First, documents are split into smaller, overlapping segments to ensure local context is preserved. We use a retriever to pull the top K most relevant chunks, but since these might still be noisy, we apply a cross-encoder re-ranker to score the relevance of the retrieved chunks relative to the query. Finally, we only inject the most pertinent information into the prompt. This keeps the prompt within the model's token limits while maximizing the information density of the context window provided to the model.
Describe the challenges of 'Agentic Loops' and how you mitigate the risk of infinite tool-calling cycles.
Agentic loops are powerful but carry risks, primarily the 'infinite loop' where a model gets stuck repeating a failed tool call or enters a hallucinated circular reasoning path. To mitigate this, we implement explicit constraints such as a 'max_iterations' limit and a structured 'scratchpad' history. We force the model to document its reasoning steps and provide it with a way to stop if the action confidence score falls below a threshold. Furthermore, implementing human-in-the-loop (HITL) checkpoints for sensitive actions ensures that the agent cannot execute critical operations, like deleting records or sending emails, without explicit approval, maintaining security and operational stability.
Check yourself
1. When designing a RAG system, why is the retrieval stage often followed by a re-ranking step?
- A.To reduce the number of tokens sent to the generator
- B.To ensure the model has enough memory to process the input
- C.To refine the order of retrieved documents based on their actual relevance to the query
- D.To compress the vector embeddings for faster computation
Show answer
C. To refine the order of retrieved documents based on their actual relevance to the query
Re-ranking uses a cross-encoder to evaluate relevance more accurately than vector distance. Option 0 is a side effect but not the goal, 1 is unrelated to logic, and 3 refers to indexing, not ranking.
2. What distinguishes an AI agent from a standard chatbot using RAG?
- A.The ability to generate text based on training data
- B.The presence of a reasoning loop that enables decision-making and tool execution
- C.The inclusion of a vector database for knowledge retrieval
- D.The use of multiple models running in parallel
Show answer
B. The presence of a reasoning loop that enables decision-making and tool execution
Agents interact with environments via tools. Standard RAG is just retrieval; agents plan. Options 0, 2, and 3 are features that can exist without agency.
3. How does increasing the chunk overlap in a RAG pipeline impact performance?
- A.It improves the contextual continuity between chunks but increases storage costs
- B.It eliminates the need for a vector database
- C.It guarantees the model will never hallucinate
- D.It automatically optimizes the generation speed of the model
Show answer
A. It improves the contextual continuity between chunks but increases storage costs
Overlap preserves context at boundaries, but extra text increases indexing size. Options 1, 2, and 3 are incorrect because chunking strategies do not guarantee behavior or replace infrastructure.
4. If an agent is consistently failing to pick the correct tool for a task, which architectural improvement should be prioritized?
- A.Increasing the number of total documents in the database
- B.Updating the tool definition and system prompt to improve clarity and reasoning
- C.Switching to a larger context window size
- D.Reducing the number of available tools
Show answer
B. Updating the tool definition and system prompt to improve clarity and reasoning
Agents rely on descriptions to map intent to tool calls. Clarifying definitions is the primary fix. Options 0, 2, and 3 don't address the core logic of tool selection.
5. What is the primary risk of a 'vanilla' RAG system without metadata filtering or hierarchical retrieval?
- A.The system will always generate text in a foreign language
- B.The system may retrieve semantically relevant but contextually irrelevant information
- C.The system will crash if the user asks an off-topic question
- D.The system will delete the vector database entries
Show answer
B. The system may retrieve semantically relevant but contextually irrelevant information
Vector search measures distance, not relevance; noise is common. Options 0, 2, and 3 describe catastrophic errors that don't stem directly from a lack of metadata filtering.