VIDHAIX / AI ENGINEERING / INTERVIEW PREP

Top 43 Generative AI Interview Questions & Answers (2026)

LLMs, RAG, embeddings, evals, tool calling, agents, MCP and production GenAI trade-offs, with answers.

43 questions with answersUpdated 22 October 2026Reviewed by VidhaiX trainers

These Generative AI interview questions are for software engineers, data engineers and freshers applying to AI engineer, GenAI developer or LLM application roles. The focus is applied engineering: building reliable products on top of language models, not training models from scratch or deriving the maths of backpropagation. Most hiring teams in 2026 assume you can call a model API. What separates candidates is whether you can make the result accurate, affordable, observable and safe.

In interviews at Indian product companies, IT services firms and startups, the probing usually goes deep on RAG (chunking, hybrid search, reranking), evaluation, tool calling and agents, MCP, cost and latency, and prompt injection. The questions below were compiled by VidhaiX trainers from the mock interviews they run. They are grouped into freshers, intermediate, experienced (3+ years) and scenario-based rounds, with Python examples where code makes the point clearer.

How to Prepare for a Generative AI Interview

  • Build a small RAG app end to end over a real document set, such as a college handbook or a product manual, with chunking, embeddings, hybrid search and cited answers.
  • Create a golden set of at least 50 questions for that app and measure retrieval recall and faithfulness before and after each change, so you can talk about real numbers.
  • Implement a tool-calling agent loop by hand once, without a framework, including step limits, error handling and tool result messages, then compare it with a LangGraph version.
  • Write a small MCP server exposing two or three tools, connect it to an MCP client such as an IDE assistant, and note how tool descriptions change model behaviour.
  • Store embeddings in PostgreSQL with pgvector, add an HNSW index, and practise explaining the recall versus speed trade-off when metadata filters are applied.
  • Instrument your app with tracing for prompts, tool calls, tokens, cost and latency, so you can walk an interviewer through debugging one bad answer from its trace.
  • Try to break your own app with prompt injection, including instructions hidden inside an uploaded document, and be ready to explain the defences you added and why.
  • Practise explaining trade-offs aloud: prompting versus RAG versus fine-tuning, API versus self-hosted models, single agent versus multi-agent, with a concrete example for each.

Generative AI Interview Questions for Freshers

12 questions

Q1.What is a token, and why do token counts matter when you build on an LLM?

A token is the unit a model reads and writes: a word piece produced by a tokenizer such as BPE. In English a token is roughly three quarters of a word, but Tamil, Hindi and source code often need far more tokens per word. Token counts drive three things you care about in production: cost (billed per input and output token), latency (output tokens are generated one at a time) and whether the request fits in the context window. A weak answer says a token is a word; a strong one mentions counting tokens with the provider's tokenizer before sending large prompts.

Q2.What is a context window, and what happens when your prompt gets close to the limit?

The context window is the maximum number of tokens the model can handle in one request, covering the system prompt, history, retrieved documents, tool results and the generated output. Exceed it and the API rejects the call, or your framework silently truncates something, often the oldest messages. Even well below the limit, quality degrades: models recall facts buried in the middle of long contexts less reliably, and every extra token adds cost and latency. Interviewers like candidates who say a bigger window is not a substitute for retrieving the right ten paragraphs.

Q3.How do temperature and top-p change model output, and what would you set for an extraction task?

Temperature rescales the probability distribution over the next token: low values let the most likely token dominate, high values flatten the distribution and increase variety. Top-p (nucleus sampling) keeps only the smallest set of tokens whose cumulative probability reaches p and samples from that set. Tune one, not both. For extraction, classification or JSON generation, use temperature 0 or close to it.

The trap: temperature 0 reduces randomness but does not guarantee identical outputs, because batching and floating-point effects on the provider side still cause nondeterminism. Some reasoning models also restrict or ignore these parameters.

Q4.Explain self-attention in a transformer without using any maths.

Each token builds a query (what am I looking for), a key (what do I contain) and a value (what I pass on). For every token, the model compares its query with the keys of the other tokens, turns those scores into weights and takes a weighted mix of their values. That is how 'it' in a sentence learns to point at the right noun. Many attention heads run in parallel and layers stack. Two practical consequences: compute grows with sequence length, which is why long contexts are expensive, and decoder models attend only backwards, generating one token at a time.

Q5.What belongs in a system prompt, and how is it different from the user message?

The system prompt holds durable instructions the application owns: role, scope, tone, output format, refusal rules and facts the model should treat as ground truth. User messages carry the end user's input for that turn. Models are trained to weight system instructions more heavily, but that is a priority, not a security boundary.

Strong candidates keep the system prompt stable and versioned (which also helps prompt caching), put variable data such as retrieved documents in clearly delimited sections, and never place secrets in it, because a determined user can often get the model to reveal it.

Q6.What is few-shot prompting, and when does it beat a longer written instruction?

Few-shot prompting puts a handful of input and output examples in the prompt so the model copies the pattern. It beats prose instructions when the format or judgement is easier to show than describe: classification labels with edge cases, a house writing style, or a tricky extraction. Pitfalls interviewers look for: examples that are too similar make the model overfit to them, label order and imbalance bias the outputs, and every example costs tokens on every call. With structured output support in modern APIs, you need fewer examples for format and can spend them on genuinely hard cases.

Q7.What are embeddings, and how is cosine similarity used to compare them?

An embedding is a fixed-length vector a model produces for a piece of text, positioned so that semantically similar texts land close together. Cosine similarity measures the angle between two vectors, ignoring their length, and is the usual comparison; many embedding models return normalised vectors, so a dot product gives the same ranking. Mention that queries and documents must use the same model, that changing models means re-embedding everything, and that similarity is not relevance: "refund policy" and "no refunds" can sit very close together.

python
import numpy as np

def cosine(a: np.ndarray, b: np.ndarray) -> float:
    return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))

# query_vec and doc_vecs come from the same embedding model
scores = doc_vecs @ query_vec / (
    np.linalg.norm(doc_vecs, axis=1) * np.linalg.norm(query_vec)
)
top_k = np.argsort(-scores)[:5]

Q8.What is retrieval-augmented generation, and why not just paste all your documents into the prompt?

RAG retrieves the passages relevant to a question from your own data, usually through vector or keyword search, and inserts them into the prompt so the model answers from them. It gives the model fresh and private knowledge without retraining and lets you cite sources. Pasting everything fails for real corpora: it exceeds the context window, costs a lot per query, slows responses and buries the relevant paragraph in noise. A good answer adds that RAG quality is mostly a retrieval problem; if the right chunk is not retrieved, no prompt will rescue the answer.

Q9.What is a hallucination, and why do LLMs produce them?

A hallucination is fluent output that is not supported by the input or by reality: an invented API, citation, policy clause or number. It happens because the model is trained to produce likely continuations, not to check facts, and it has no reliable built-in signal for "I do not know". Missing or ambiguous context, questions about rare facts and prompts that pressure the model to always answer make it worse. Strong candidates describe mitigation in layers: ground answers in retrieved sources, allow and reward "not found", require citations, validate outputs and measure the rate with evals.

Q10.How does tool or function calling work, and who actually executes the function?

You describe each tool to the model with a name, a description and a JSON Schema for its arguments (the exact field names differ by provider). When the model decides a tool is needed, it returns a structured tool call instead of text. Your code validates the arguments, executes the function and sends the result back as a tool message, and the model continues.

The point freshers miss: the model never executes anything. Your application owns execution, so it also owns validation, permissions and error handling. Tool descriptions matter as much as prompts, because they are how the model decides when to call.

json
{
  "name": "get_order_status",
  "description": "Look up the delivery status of a customer's order by order ID.",
  "parameters": {
    "type": "object",
    "properties": {
      "order_id": { "type": "string", "description": "Order ID such as ORD-10293" }
    },
    "required": ["order_id"]
  }
}

Q11.Why should a chat feature stream LLM responses, and how would you do it in FastAPI?

Generation is token by token, so a long answer can take several seconds. Streaming sends tokens as they arrive, which makes time to first token the latency users actually feel. In FastAPI you return a StreamingResponse over an async generator, usually as server-sent events. Mention the gotchas: proxies such as Nginx may buffer the stream unless configured not to, you should stop generation when the client disconnects so you do not pay for unread tokens, and output moderation or JSON validation is harder when the answer arrives in pieces.

python
from fastapi import FastAPI
from fastapi.responses import StreamingResponse

app = FastAPI()

@app.post("/chat")
async def chat(req: ChatRequest):
    async def events():
        async for delta in llm.stream(messages=req.messages):
            yield f"data: {json.dumps({'text': delta})}\n\n"
        yield "data: [DONE]\n\n"
    return StreamingResponse(events(), media_type="text/event-stream")

Q12.What is the difference between a hosted API model and an open-weight model?

A hosted API model runs on the provider's infrastructure: you send requests, pay per token and never see the weights. Open-weight models publish their weights, so you can run them on your own GPUs or a cloud account you control, fine-tune them and keep data inside your network. APIs give the strongest frontier models with zero operations work; open-weight models give control, predictable cost at high volume and data residency, but you own serving, scaling and upgrades. Also note that open-weight is not always open source; licences vary and some restrict commercial use.

Generative AI Intermediate Interview Questions

12 questions

Q13.How do you get reliable JSON out of an LLM?

Use the provider's structured output or JSON Schema mode where available, which constrains decoding so the response matches your schema. Define the schema once, for example with Pydantic, and validate every response anyway. Schema-valid is not the same as correct: the model can still put wrong values in valid fields, so add semantic checks and one bounded retry that feeds the validation error back.

Keep schemas flat, use enums for categories and allow nulls so the model is not forced to invent a value. Regex-parsing free text is the weak answer.

python
from typing import Literal
from pydantic import BaseModel, Field

class Ticket(BaseModel):
    category: Literal["billing", "bug", "account", "other"]
    priority: Literal["low", "medium", "high"]
    summary: str = Field(max_length=200)
    order_id: str | None = None

raw = llm.generate(prompt, response_schema=Ticket.model_json_schema())
ticket = Ticket.model_validate_json(raw)  # raises on mismatch, then retry once

Q14.How do you choose a chunking strategy for a RAG pipeline?

Start from the documents and the questions users ask. Fixed-size chunks of a few hundred tokens with some overlap are a reasonable baseline, but structure-aware splitting by headings, sections, table rows or code functions usually retrieves better. Too small and chunks lose context; too large and the embedding blurs several topics and wastes prompt tokens. Useful techniques: prepend the document title and section path to each chunk, store metadata for filtering, and retrieve small chunks but send the surrounding parent section to the model. The strong answer ends with choosing by measured retrieval recall, not intuition.

Q15.What is hybrid search, and why combine BM25 with vector search?

Vector search captures meaning, so "cancel my plan" finds "subscription termination", but it is weak on exact tokens such as error codes, SKUs, names and rare acronyms. BM25 keyword search has the opposite strengths. Hybrid search runs both and merges the ranked lists. Reciprocal rank fusion is a common merge because it uses ranks rather than scores that are not comparable. Candidates should mention that hybrid search plus a reranker is a strong default for enterprise documents, and that the balance between the two should be tuned on evals.

python
def rrf(result_lists: list[list[str]], k: int = 60) -> list[str]:
    scores: dict[str, float] = {}
    for results in result_lists:
        for rank, doc_id in enumerate(results, start=1):
            scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
    return sorted(scores, key=scores.get, reverse=True)

candidates = rrf([bm25_search(q, 50), vector_search(q, 50)])[:20]

Q16.What does a reranker do, and where does it sit in the retrieval pipeline?

A reranker is usually a cross-encoder that reads the query and a candidate passage together and outputs a relevance score. Reading them jointly is far more accurate than comparing two independently computed embeddings, but too slow to run over the whole corpus. So the pipeline is: retrieve a wide candidate set cheaply (say 50 to 100 via hybrid search), rerank, then send the top 5 to 10 to the LLM. Mention the added latency per query, and that reranking only reorders what retrieval found; it cannot recover a document that was never retrieved.

Q17.How does an HNSW index work, and what are you trading off when you tune it?

HNSW builds a layered graph: upper layers have few nodes with long links for coarse navigation, lower layers are dense for fine search. A query walks greedily from the top layer down toward its nearest neighbours. It is approximate, so you trade recall for speed and memory. Build parameters (m, ef_construction) control graph density and build time; the query-time ef_search controls how many candidates are explored. Strong candidates mention that HNSW wants the index in memory, that restrictive filters can cut recall, and that you measure recall against exact search before tuning.

Q18.How would you store and search embeddings in PostgreSQL with pgvector?

Enable the vector extension, add a vector(n) column matching your embedding model's dimensions and create an HNSW index whose operator class matches your distance metric. Query with ORDER BY embedding <=> $1 LIMIT k, where <=> is cosine distance. The advantage over a separate vector database is that embeddings sit next to relational data, so tenant filters, permissions and joins happen in one transactional query. Mention that a selective WHERE filter on top of an approximate index can return fewer rows than expected, and that iterative index scans or partial indexes help.

sql
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE chunks (
  id bigserial PRIMARY KEY,
  tenant_id int NOT NULL,
  content text NOT NULL,
  embedding vector(1024) NOT NULL
);

CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);

SELECT id, content, embedding <=> $1 AS distance
FROM chunks
WHERE tenant_id = $2
ORDER BY embedding <=> $1
LIMIT 10;

Q19.How do you make a RAG system cite its sources, and how do you know the citations are real?

Give each retrieved chunk a stable ID and source metadata in the prompt, instruct the model to cite IDs next to each claim, and ask for structured output that lists claims with their supporting chunk IDs. Then verify in code: every cited ID must exist in the retrieved set, and a cheap check (text overlap, an entailment model or a judge) confirms the chunk supports the claim. Render citations as links to the source. The trap is treating citation format as proof; models produce plausible citations to chunks that do not say what is claimed.

Q20.What is an agent loop, and how is it different from a single tool call?

An agent loop lets the model decide repeatedly: call a tool, read the result, choose the next step and stop when it can answer. A single tool call is one round trip that your code orchestrates. Agents handle open-ended tasks but are slower, costlier and less predictable. Strong answers list the guardrails every loop needs: a maximum step count, a token or cost budget, tool timeouts, and errors returned to the model instead of crashing. Also say that a fixed workflow often beats an agent when the steps are known in advance.

python
messages = [system_msg, user_msg]
for step in range(MAX_STEPS):
    reply = llm.chat(messages=messages, tools=TOOLS)
    messages.append(reply.message)
    if not reply.tool_calls:
        return reply.text
    for call in reply.tool_calls:
        result = run_tool(call.name, call.arguments)  # validate + authorise
        messages.append(tool_result(call.id, result))
raise AgentBudgetExceeded("stopped after MAX_STEPS")

Q21.What is the Model Context Protocol (MCP), and what problem does it solve?

MCP is an open protocol for connecting AI applications to tools and data. An MCP server exposes tools, resources and prompts; an MCP client inside a host application, such as an IDE assistant or chat app, discovers and calls them over JSON-RPC, using stdio for local servers or streamable HTTP for remote ones. It replaces one-off integrations per app with a server many clients can reuse. A strong answer adds that MCP standardises the plumbing, not the trust: you still need authentication, least-privilege tools and review of third-party servers.

Q22.What is prompt injection, and why can a stronger system prompt not fix it?

Prompt injection is untrusted text steering the model away from your instructions. Direct injection comes from the user; indirect injection hides in content the model reads, such as a web page, email, PDF or tool result. Prompting cannot fully fix it because instructions and data share the same token stream with no hard boundary. Defences are architectural: treat model output as untrusted, give tools least privilege, require human confirmation for side effects, delimit untrusted data and filter inputs and outputs. Interviewers want "reduce the blast radius", not "add a sentence telling it to ignore attacks".

Q23.How would you build a golden evaluation set for an LLM feature?

Collect 50 to 300 realistic inputs, ideally from anonymised production logs, covering common cases, edge cases, known failures and adversarial inputs. For each, record the expected answer or the properties a good answer must have, and for RAG the documents that should be retrieved. Have domain experts review the labels. Version the set with your prompts, run it on every prompt, model or retrieval change, and add every production bug as a new case. The weak answer is "we tried ten questions manually"; the strong one treats evals like a regression suite in CI.

Q24.What is LLM-as-judge, and what are its pitfalls?

LLM-as-judge uses a model to grade outputs against a rubric, which scales evaluation of open-ended text where exact match does not work. Known biases: a preference for longer answers, for the first option in pairwise comparisons and for outputs from its own model family; results also shift when the judge model changes. Mitigations: narrow binary or small-scale rubrics per criterion, reasoning before the score, swapped positions in pairwise tests, a pinned judge version, and calibration against human labels with tracked agreement. Use deterministic checks first wherever they are possible.

Generative AI Interview Questions for Experienced (3+ Years)

11 questions

Q25.Which metrics would you use to evaluate a RAG system, and how do faithfulness and context recall differ?

Split evaluation into retrieval and generation. Retrieval: context recall (did the retrieved chunks contain what the reference answer needs), context precision (how much of what was retrieved is relevant and ranked high), plus recall@k and MRR when you have labelled relevant documents. Generation: faithfulness (is every claim supported by the retrieved context) and answer relevance (does it address the question). Frameworks such as Ragas compute these with LLM judges. The insight interviewers want: low faithfulness points at the prompt or model, low context recall points at chunking, embeddings or search.

Q26.When would you choose fine-tuning over RAG or better prompting, and where does LoRA fit?

Prompting first, because it is cheapest and fastest to iterate. RAG when the problem is knowledge, especially facts that change or need citations and access control. Fine-tuning when the problem is behaviour: a consistent format or tone, a narrow classification task, domain jargon, or distilling a large model into a smaller, cheaper one. It is a poor way to inject changing facts.

LoRA trains small low-rank adapter matrices while base weights stay frozen, making tuning affordable and letting you serve several adapters on one base. You still need a quality dataset, evals and a plan for when the base model changes.

Q27.How does prompt caching work, and how do you structure prompts to benefit from it?

Providers can cache the processed state of a prompt prefix, so later requests sharing that exact prefix are cheaper and reach the first token faster. Because matching is by prefix, order the prompt from most stable to most variable: tool definitions, system prompt, long reference documents, conversation history, then the new user message. Anything that changes early, such as a timestamp or user name in the system prompt, invalidates everything after it. Some providers cache automatically, others need explicit cache markers, and entries expire after an idle period. Track hit rate from the usage fields in responses.

Q28.How would you design model routing to control cost and latency without hurting quality?

Route each request to the cheapest model that meets the quality bar for that task. Options range from static routing by feature (a small model for classification, a larger one for complex reasoning), to a classifier or rules on the input, to cascades where a small model answers first and escalates when a validator or confidence check fails. Every route needs per-task evals proving the small model is good enough, plus fallbacks to another model or provider on errors and rate limits. Mention the hidden costs: routing adds latency, and each model needs its own tuned prompts.

Q29.When does self-hosting an open-weight model with vLLM make sense, and what are the trade-offs?

It makes sense with high, steady volume where per-token API costs exceed GPU costs, strict data residency, a fine-tuned model, or air-gapped environments. vLLM is popular because PagedAttention manages the KV cache efficiently and continuous batching keeps GPUs busy across concurrent requests; it also exposes an OpenAI-compatible API, so clients barely change.

Trade-offs: you own GPU capacity planning, autoscaling with slow cold starts, quantisation choices, upgrades and on-call. Smaller models often trail frontier APIs on hard reasoning, so run your evals first. Low or spiky traffic rarely justifies idle GPUs.

Q30.How would you design a multi-agent workflow with LangGraph, and when is it overkill?

LangGraph models a workflow as a state graph: nodes are functions or agents that read and update a shared typed state, and edges, including conditional ones, decide what runs next. That gives explicit control flow, bounded loops, checkpointing for resumability and human-in-the-loop interrupts. A common pattern is a supervisor routing to specialists such as a researcher and a writer. It is overkill when one agent with good tools or a fixed pipeline works, since each extra agent adds latency, cost and failure points. Start with one agent and split only when evals justify it.

python
from typing import TypedDict
from langgraph.graph import StateGraph, START, END

class State(TypedDict):
    question: str
    notes: str
    draft: str

graph = StateGraph(State)
graph.add_node("research", research_node)
graph.add_node("write", write_node)
graph.add_edge(START, "research")
graph.add_edge("research", "write")
graph.add_conditional_edges("write", review_ok, {True: END, False: "research"})
app = graph.compile(checkpointer=checkpointer)

Q31.How would you build an MCP server that exposes internal tools safely?

Use an official MCP SDK, give each tool a clear name, description and typed parameters, and keep tools narrow: get_invoice(invoice_id) rather than run_sql(query). For remote servers use streamable HTTP with OAuth-based authorisation, and enforce per-user permissions inside the server, never in the prompt. Make write operations explicit and idempotent, return concise structured results to save tokens, log every call and rate-limit. Interviewers probe whether you see that the client model may be manipulated by injected content, so the server must treat every tool call as potentially adversarial.

python
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("billing")

@mcp.tool()
def get_invoice(invoice_id: str) -> dict:
    """Return status and amount for one invoice the caller can access."""
    user = current_user()  # resolved from the verified auth token
    invoice = invoices.get(invoice_id, owner_id=user.id)
    return {"id": invoice.id, "status": invoice.status, "amount": invoice.amount}

if __name__ == "__main__":
    mcp.run()

Q32.How do you handle PII and data governance in an LLM application?

Start by mapping what data flows into prompts, logs, vector stores and third-party APIs. Minimise: send only the fields a task needs, and detect and mask PII such as phone numbers, Aadhaar and PAN before prompts and logs, restoring values afterwards where needed. Check each provider's retention and training-use terms and pick regions that satisfy obligations like India's DPDP Act. Enforce access control at retrieval time so users only get chunks from documents they may see, and support deletion, including embeddings. A weak answer forgets that traces and eval datasets contain PII too.

Q33.What would you trace and monitor in a production LLM application?

Trace each request end to end: prompt template and version, model and parameters, retrieved chunk IDs with scores, every tool call with arguments and latency, token counts, cost, time to first token, total latency and errors. Use spans so an agent run appears as a tree; OpenTelemetry has GenAI semantic conventions, and tools such as Langfuse or LangSmith follow similar ideas. Beyond traces, monitor user feedback, refusal and fallback rates, and run online evals on sampled traffic. Redact PII before export. Without traces you cannot explain why one specific answer was wrong.

Q34.How would you design guardrails for a customer-facing LLM assistant?

Layer them. Input: length limits, PII detection, topic classification and injection heuristics. Retrieval: permission filters and source allow-lists. Output: schema validation, moderation, topic checks and grounding checks against retrieved content. Actions: allow-listed tools, server-side authorisation and human confirmation for anything irreversible, such as refunds.

Every guardrail adds latency and false positives, so evaluate them like features with precision and recall, run cheap checks in parallel with generation, and keep a safe fallback message. Guardrails reduce risk; they never make the system fully safe.

Q35.How do you version, test and roll out prompt changes safely?

Treat prompts as code: keep them in the repository or a prompt registry with versions, review changes in pull requests, and tag every trace with the prompt version that produced it. Run the golden eval set in CI on each change and block merges on regressions beyond a threshold. Roll out behind a feature flag or to a percentage of traffic, compare online metrics and feedback, and keep instant rollback. Pin model versions too, because a provider model update is a change you did not write. The trap is editing prompts live in production because it is "just text".

Generative AI Scenario-Based Interview Questions

8 questions

Q36.Your RAG assistant confidently gives a wrong answer about the leave policy, yet the correct policy is in the indexed documents. How do you debug it?

Check retrieval before touching the prompt. Pull the trace: was the correct chunk retrieved, and at what rank? If not, inspect chunking (was the rule split across chunks, or inside a table that parsed badly?), check whether an outdated policy version outranks it, and try the query with keyword search. If the chunk was retrieved but ignored, look at how many chunks were sent, conflicting sources and prompt wording. Fix the root cause, add metadata such as effective date for filtering, and add this question to the golden set so it stays fixed.

Q37.Users complain the chatbot takes 10 seconds to respond, and product wants text on screen within 2 seconds. What do you do?

Measure first: break latency into retrieval, reranking, guardrails, time to first token and generation, then attack the largest parts. Stream responses so text appears at the first token. Run retrieval and input checks in parallel, cache embeddings for frequent queries and trim the prompt, since long contexts delay the first token. Use prompt caching for the stable prefix, route simple questions to a smaller, faster model and cap output length. If an agent makes several sequential calls, cut steps or parallelise tool calls. Re-run evals after each change so speed does not silently cost quality.

Q38.Your monthly LLM bill tripled after launch, but traffic only grew 50 percent. How do you investigate?

Break cost down by feature, model, tenant and input versus output tokens using traces. Usual culprits: conversation history growing without bound, too many or too large retrieved chunks, an agent looping or retrying, a change that broke prompt caching (such as a timestamp added to the system prompt), routing accidentally sending everything to the largest model, or one customer or bot hammering the endpoint. Fix with history summarisation or windowing, tighter retrieval, step budgets, per-user rate limits and cost alerts, then put cost per request on a dashboard so the next regression shows up in days.

Q39.A user uploads a PDF with hidden text telling the assistant to email the full customer list, and your agent actually attempts the email tool call. What do you change?

Treat it as a security incident: confirm no data left, search logs for similar attempts and disable the tool if needed. The root problem is that one agent could read untrusted content and also take a sensitive action. Fixes: scope tools to the current user's data with server-side authorisation, require human confirmation for outbound email, restrict recipients to allow-listed domains, and separate the component that reads documents from the one that can act. Add injection detection on uploads and put this PDF in an adversarial eval set. Better prompting alone is not the fix.

Q40.After switching to a newer model version, wrong-answer complaints rise even though public benchmarks say the new model is better. How do you handle it?

Route traffic back to the previous model while you investigate. Run the golden set on both models and diff the failures; the cause is often prompt-model fit, such as the new model following instructions more literally, being more verbose, formatting JSON differently or refusing more. Public benchmarks do not measure your task. Adjust prompts for the new model, re-run evals, then roll out to a small percentage with online metrics. Long term, pin model versions, keep per-model prompt variants and push model changes through the same eval gate as code.

Q41.An agent in production keeps calling the same search tool until it hits the timeout. How do you fix it?

Read the traces. Common causes: the tool returns an error or empty result the model cannot interpret, so it retries; the tool output is too long and gets truncated; or the stopping condition is unclear. Fixes: return clear, actionable tool errors ("no results for X, try a broader term"), detect repeated identical calls and stop or nudge the model, enforce a step and token budget that ends with a graceful answer, and tighten tool descriptions. If the task has predictable steps, replace the free-form agent with a fixed workflow, and add the failing case to evals.

Q42.Your RAG search works well for English questions but fails when users ask in Tamil or Hinglish. What would you try?

Confirm it with an eval set of real queries in those languages, measuring retrieval recall separately from answer quality. Check the embedding model's multilingual support; many models handle native scripts far better than romanised Hinglish or Tanglish. Options: switch to a strong multilingual embedding model, translate or normalise queries to English for retrieval while answering in the user's language, add keyword search with transliteration-aware synonyms, and evaluate the reranker on multilingual pairs. Also check token costs, since Indic scripts can use many more tokens per word.

Q43.A manager wants a chatbot that answers questions like 'What was revenue by region last quarter?' over a large sales table. Would you use RAG over embeddings?

No. Embedding retrieval finds similar text; it cannot sum, filter or group millions of rows. Use text-to-SQL or, better, tool calling against a semantic layer, where the model picks predefined metrics and dimensions and your code builds the query. If you allow generated SQL, run it on a read-only replica with a restricted role, row limits, timeouts and query validation, and show the user the SQL or metric definition used. Evaluate with questions that have known results. RAG still helps for retrieving table schemas and business definitions.

From answers to offers

Prepare for Generative AI interviews with practicing engineers

If you want to build these systems rather than only read about them, the course covers Python, LLM APIs, RAG with pgvector, LangGraph, MCP and FastAPI through hands-on labs with code reviews and mock interviews.