InterviewTreedInterviewTreed

InterviewTreed Question Bank

Generative AI & LLMs Interview Questions and Answers

Prepare for Generative AI and Large Language Models, including transformer architecture, prompt engineering, embeddings, model training, fine-tuning, evaluation, and practical LLM applications.

Total Questions

100

Beginner

25

Intermediate

50

Advanced

25

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1LLM Fundamentals

What is generative AI?

Generative AI is a class of AI systems that creates new content such as text, code, images, audio, or structured data from learned patterns. A…

Answer

Generative AI is a class of AI systems that creates new content such as text, code, images, audio, or structured data from learned patterns. A text-focused generative model predicts and produces a sequence of tokens in response to its input and generation settings.

Syntax

Input prompt → Model → Generated output

Example

const prompt = "Explain APIs in simple terms."; const output = await llm.generate({ prompt }); console.log(output.text);

Key Points

  • It generates new content rather than only classifying existing input.
  • Output quality depends on the model, context, and instructions.
Q2LLM Fundamentals

What is a large language model (LLM)?

An LLM is a neural network trained on large text or mixed-modality datasets to model language patterns and generate or transform content. Many…

Answer

An LLM is a neural network trained on large text or mixed-modality datasets to model language patterns and generate or transform content. Many modern LLMs use the Transformer architecture and predict the next token repeatedly during generation.

Syntax

Text → Tokenizer → Transformer → Next-token probabilities → Generated sequence

Example

const response = await client.responses.create({ model: "YOUR_MODEL", input: "Define a large language model in one paragraph." }); console.log(response.output_text);

Key Points

  • An LLM does not retrieve truth automatically; it generates likely continuations.
  • Training data, architecture, context length, and post-training affect behavior.
Q3LLM Fundamentals

How does an LLM generate text?

The model converts input into tokens, processes their representations, and estimates a probability distribution for the next token. A decoding…

Answer

The model converts input into tokens, processes their representations, and estimates a probability distribution for the next token. A decoding strategy selects a token, appends it to the sequence, and repeats until a stop condition is reached.

Syntax

Prompt → Tokenize → Model → Select token → Append token ↺

Example

const settings = { maxOutputTokens: 120, temperature: 0.3 }; // The provider SDK determines the exact request shape. const answer = await generateText({ prompt: "Explain recursion.", ...settings });

Key Points

  • Generation is iterative, not usually a single lookup.
  • Sampling settings affect variety and predictability.
Q4LLM Fundamentals

What is a Transformer?

A Transformer is a neural-network architecture that uses attention to relate tokens to one another and feed-forward layers to transform…

Answer

A Transformer is a neural-network architecture that uses attention to relate tokens to one another and feed-forward layers to transform representations. It can process token relationships efficiently in parallel during training, while autoregressive generation usually emits output tokens sequentially.

Syntax

Tokens → Embeddings + positions → Attention → Feed-forward layers → Output logits

Example

// Conceptual pseudocode, not a full Transformer implementation hidden = token_embeddings + position_information for layer in transformer_layers: hidden = layer.self_attention(hidden) hidden = layer.feed_forward(hidden) logits = language_model_head(hidden)

Key Points

  • Self-attention helps represent relationships across context.
  • Real models include normalization, residual paths, and other details.
Q5LLM Fundamentals

What is a token?

A token is a unit used by a model's tokenizer to represent text. It may be a whole word, part of a word, punctuation, whitespace-related text,…

Answer

A token is a unit used by a model's tokenizer to represent text. It may be a whole word, part of a word, punctuation, whitespace-related text, or a special control token. Tokens are not the same as words or characters.

Syntax

Text → Tokenizer → [token₁, token₂, …, tokenₙ]

Example

const tokens = tokenizer.encode("Generative AI is useful."); console.log(tokens.length); // token count depends on tokenizer

Key Points

  • Tokenization is model-specific.
  • Token counts affect context limits, latency, and usage cost.
Q6LLM Fundamentals

What is a tokenizer?

A tokenizer maps text to token IDs and can map token IDs back to text. The model consumes token IDs rather than raw strings, so a tokenizer's…

Answer

A tokenizer maps text to token IDs and can map token IDs back to text. The model consumes token IDs rather than raw strings, so a tokenizer's vocabulary and rules influence how text is segmented and how many tokens a prompt uses.

Syntax

"Hello, world!" → tokenizer → [IDs] → model

Example

const ids = tokenizer.encode("Hello, world!"); const text = tokenizer.decode(ids); console.log({ ids, text });

Key Points

  • Tokenizers may split rare words into subword pieces.
  • Use the tokenizer associated with the target model when estimating tokens.
Q7Prompt Engineering

What is prompt engineering?

Prompt engineering is the practice of designing and refining instructions, context, examples, and output constraints so a model is more likely…

Answer

Prompt engineering is the practice of designing and refining instructions, context, examples, and output constraints so a model is more likely to produce a useful response. It is an iterative process of defining the task, testing representative inputs, and evaluating results.

Syntax

Goal → Instructions + Context + Examples + Constraints → Model output → Evaluate

Example

const prompt = `Task: Summarize the text. Audience: New developers. Length: 3 sentences. Text: ${documentText}`;

Key Points

  • Be explicit about task, audience, format, and constraints.
  • Test prompts on a varied evaluation set rather than one example.
Q8Prompt Engineering

What makes a good prompt?

A good prompt states the desired task clearly, provides relevant context, defines constraints, and specifies the expected output. It avoids…

Answer

A good prompt states the desired task clearly, provides relevant context, defines constraints, and specifies the expected output. It avoids conflicting instructions and unnecessary detail, and it gives examples when the required style or structure is hard to describe.

Syntax

Task + Context + Constraints + Output format → Clearer response

Example

const prompt = `Explain ${topic} to a junior developer in 4 sentences. Include one example and avoid unexplained jargon.`;

Key Points

  • Put essential requirements in direct language.
  • Validate outputs because prompt clarity does not guarantee correctness.
Q9Prompt Engineering

What is a system prompt?

A system prompt provides high-priority behavioral instructions for an assistant, such as its role, boundaries, and response style. Its exact…

Answer

A system prompt provides high-priority behavioral instructions for an assistant, such as its role, boundaries, and response style. Its exact precedence depends on the model platform, but it should not be treated as a security boundary for secrets or as a replacement for application-side authorization.

Syntax

System instructions + User request → Assistant response

Example

const input = [ { role: "system", content: "You are a concise programming tutor." }, { role: "user", content: "Explain a hash table." } ];

Key Points

  • Keep stable role and policy instructions separate from user task data.
  • Enforce permissions in code, not only in a prompt.
Q10Prompt Engineering

What is zero-shot prompting?

Zero-shot prompting asks a model to perform a task without providing worked examples. It works well for familiar tasks with clear instructions,…

Answer

Zero-shot prompting asks a model to perform a task without providing worked examples. It works well for familiar tasks with clear instructions, but complex output schemas or niche conventions may require examples or additional context.

Syntax

Instruction → Model → Answer (no demonstrations)

Example

const prompt = `Classify this review as positive, neutral, or negative. Review: "Delivery was quick and the item works."`;

Key Points

  • It is simple and uses fewer prompt tokens.
  • Measure performance before relying on zero-shot behavior in production.
Q11Prompt Engineering

What is few-shot prompting?

Few-shot prompting includes a small number of input-output examples that demonstrate the expected task or format. The model can infer a pattern…

Answer

Few-shot prompting includes a small number of input-output examples that demonstrate the expected task or format. The model can infer a pattern from these demonstrations without updating its model weights.

Syntax

Examples → New input → Model follows demonstrated pattern

Example

const prompt = `Convert to title case. Input: hello world Output: Hello World Input: prompt engineering Output:`;

Key Points

  • Examples should be representative and consistent.
  • Examples consume context tokens, so choose them carefully.
Q12Prompt Engineering

What is an instruction versus context in a prompt?

An instruction tells the model what to do, while context provides information needed to do it. For example, “summarize the following” is an…

Answer

An instruction tells the model what to do, while context provides information needed to do it. For example, “summarize the following” is an instruction and the article being summarized is context. Separating them helps make prompts easier to inspect and maintain.

Syntax

Instruction + Delimited context → Task output

Example

const prompt = `Instruction: Summarize the source in two sentences. Source: <source>${sourceText}</source>`;

Key Points

  • Use clear delimiters around untrusted or variable content.
  • Context is not automatically verified or trusted.
Q13Prompt Engineering

Why specify an output format?

Specifying a format reduces ambiguity and makes responses easier to consume. A request for JSON, a table, or a fixed set of fields helps…

Answer

Specifying a format reduces ambiguity and makes responses easier to consume. A request for JSON, a table, or a fixed set of fields helps downstream code, although production systems should validate structured output and handle malformed or incomplete results.

Syntax

Prompt → Model → Expected schema → Validate → Application

Example

const prompt = `Return JSON with keys "title" and "summary" only. Topic: ${topic}`;

Key Points

  • Prefer provider-supported structured-output features when available.
  • Validate required fields, types, and business rules in application code.
Q14Tokens & Context

What is a context window?

A context window is the maximum amount of input and generated content a model can handle in one request, measured in tokens. The effective…

Answer

A context window is the maximum amount of input and generated content a model can handle in one request, measured in tokens. The effective budget may include instructions, conversation history, retrieved documents, tool descriptions, and the output allowance.

Syntax

Instructions + History + Documents + Output budget ≤ Context window

Example

const budget = { system: 500, history: 2000, retrieved: 3000, outputReserve: 1000 }; const estimatedInput = budget.system + budget.history + budget.retrieved;

Key Points

  • Context limits vary by model.
  • A larger context window does not guarantee that every detail will be used accurately.
Q15Tokens & Context

How are tokens different from words?

Words are linguistic units separated by language conventions, while tokens are units defined by a tokenizer. One word can map to several tokens,…

Answer

Words are linguistic units separated by language conventions, while tokens are units defined by a tokenizer. One word can map to several tokens, and punctuation or whitespace can also affect tokenization, so word count is only a rough proxy for token count.

Syntax

Sentence → tokenizer → token IDs (count may differ from word count)

Example

const words = text.trim().split(/\s+/).length; const tokenCount = tokenizer.encode(text).length; console.log({ words, tokenCount });

Key Points

  • Use the actual tokenizer for accurate estimates.
  • Different models may use different tokenization schemes.
Q16Tokens & Context

What are input tokens and output tokens?

Input tokens are the tokens supplied to the model in instructions, user messages, context, and sometimes tool definitions. Output tokens are the…

Answer

Input tokens are the tokens supplied to the model in instructions, user messages, context, and sometimes tool definitions. Output tokens are the tokens generated by the model. Providers may price them differently, so track both when estimating cost.

Syntax

Input tokens → Model → Output tokens

Example

const usage = { inputTokens: result.usage.input_tokens, outputTokens: result.usage.output_tokens };

Key Points

  • Cached input may have separate pricing on some platforms.
  • Tool calls and reasoning tokens may be accounted for differently by provider.
Q17Tokens & Context

What is a special token?

A special token is a dedicated token ID used for control or structure, such as message boundaries, end-of-turn markers, or multimodal markers.…

Answer

A special token is a dedicated token ID used for control or structure, such as message boundaries, end-of-turn markers, or multimodal markers. Its human-readable spelling may appear in debugging output, but applications should follow the target model's protocol rather than inventing special-token strings.

Syntax

Message boundary tokens → Role/content structure → Model

Example

// Use the provider's message API instead of hand-writing internal control tokens. const messages = [{ role: "user", content: "Hi" }];

Key Points

  • Special-token conventions differ across model families.
  • Incorrectly inserting internal tokens can change behavior or be ignored.
Q18Embeddings

What is an embedding?

An embedding is a numerical vector representing an item such as text, an image, or a product. Text embeddings are designed so that semantic…

Answer

An embedding is a numerical vector representing an item such as text, an image, or a product. Text embeddings are designed so that semantic relationships can often be measured using vector similarity, making them useful for semantic search, clustering, and retrieval.

Syntax

Text → Embedding model → [0.12, -0.03, …]

Example

const vector = await embeddingModel.embed("How do I reset my password?"); console.log(vector.length);

Key Points

  • Embeddings are learned representations, not plain-language explanations.
  • Vectors from incompatible models should not be mixed in one similarity index.
Q20Embeddings

What is cosine similarity?

Cosine similarity measures the cosine of the angle between two vectors. It is often used to compare embeddings because it focuses on direction…

Answer

Cosine similarity measures the cosine of the angle between two vectors. It is often used to compare embeddings because it focuses on direction rather than magnitude; its useful interpretation depends on the embedding model and whether vectors are normalized.

Syntax

Vectors A, B → dot(A,B)/(||A||·||B||) → Similarity score

Example

function cosine(a, b) { const dot = a.reduce((s, x, i) => s + x * b[i], 0); const na = Math.sqrt(a.reduce((s, x) => s + x*x, 0)); const nb = Math.sqrt(b.reduce((s, x) => s + x*x, 0)); return dot / (na * nb); }

Key Points

  • Handle zero-length vectors and mismatched dimensions.
  • Similarity scores are not universal probabilities of relevance.
Q21Practical GenAI

What is hallucination in generative AI?

A hallucination is an output that sounds plausible but is unsupported, incorrect, or fabricated. It can occur because language models optimize…

Answer

A hallucination is an output that sounds plausible but is unsupported, incorrect, or fabricated. It can occur because language models optimize generated sequences rather than guaranteeing factual verification. Grounding, citations, validation, and calibrated refusal behavior can reduce the risk.

Syntax

Question → Model guess → Plausible but unsupported answer

Example

const answer = await answerFromSources(question, trustedDocuments); if (!answer.citations?.length) { return { answer: "I could not find support in the provided sources." }; }

Key Points

  • Do not assume fluent wording implies truth.
  • For consequential use, verify claims against authoritative sources.
Q22Practical GenAI

What is temperature in text generation?

Temperature adjusts the sharpness of the next-token probability distribution during sampling. Lower values generally make outputs more…

Answer

Temperature adjusts the sharpness of the next-token probability distribution during sampling. Lower values generally make outputs more predictable, while higher values usually increase variation. Temperature is not a direct quality control and its effect depends on the model and decoding implementation.

Syntax

Logits ÷ temperature → Softmax → Token sampling

Example

const options = { temperature: 0.2 }; // Use only if the selected model/API supports temperature. const result = await generateText({ prompt, ...options });

Key Points

  • Low temperature is useful for consistent extraction tasks.
  • Some reasoning or newer models may not support or respond to temperature in the same way.
Q23Practical GenAI

What is max output token length?

A maximum output-token setting limits how much text a model can generate in a response. If the limit is too small, the response may be…

Answer

A maximum output-token setting limits how much text a model can generate in a response. If the limit is too small, the response may be truncated; if it is too large, cost and latency may increase. Applications should detect incomplete outputs where possible.

Syntax

Prompt + max output budget → Model → Bounded response

Example

const result = await generateText({ prompt, maxOutputTokens: 300 });

Key Points

  • The exact parameter name varies by SDK.
  • Leave enough budget for the expected answer and structured closing syntax.
Q24Practical GenAI

What is a chat completion or model response API?

A model response API accepts input such as messages or a prompt and returns generated content plus metadata. SDKs commonly wrap authentication,…

Answer

A model response API accepts input such as messages or a prompt and returns generated content plus metadata. SDKs commonly wrap authentication, request serialization, retries, streaming, and usage reporting; exact request shapes vary by provider and API version.

Syntax

Application → SDK/API request → Model service → Response

Example

const response = await client.responses.create({ model: "YOUR_MODEL", input: "Give three uses of embeddings." }); console.log(response.output_text);

Key Points

  • Keep API keys on the server, never in browser bundles.
  • Pin and verify SDK/API versions in production.
Q25Practical GenAI

What is streaming output?

Streaming sends generated output in small events as it becomes available instead of waiting for the complete response. It can reduce perceived…

Answer

Streaming sends generated output in small events as it becomes available instead of waiting for the complete response. It can reduce perceived latency and enable live interfaces, but the client must handle partial text, errors, cancellation, and completion events.

Syntax

Request → token/event stream → UI updates → final completion

Example

for await (const event of streamResponse({ prompt })) { if (event.type === "text_delta") appendToUI(event.text); }

Key Points

  • Do not treat a partial stream as a completed answer.
  • Use cancellation and cleanup when a user navigates away.

Intermediate Questions

Implementation details, practical patterns, and common workflows.

Q26Practical GenAI

What is multimodal generative AI?

Multimodal generative AI can accept or produce more than one modality, such as text, images, audio, or video. The model's supported modalities…

Answer

Multimodal generative AI can accept or produce more than one modality, such as text, images, audio, or video. The model's supported modalities and input formats vary, and a text-only model cannot be assumed to interpret an image or audio attachment.

Syntax

Text/image/audio input → Multimodal model → Text/audio/other output

Example

const response = await multimodalModel.generate({ text: "Describe this picture.", image: imageBytes });

Key Points

  • Check model-specific file, size, and modality requirements.
  • Treat extracted text and visual interpretation as fallible.
Q27Practical GenAI

What is an AI model versus an AI application?

A model is the learned component that generates predictions or content, while an AI application combines a model with prompts, data access, user…

Answer

A model is the learned component that generates predictions or content, while an AI application combines a model with prompts, data access, user interface, business logic, monitoring, and safety controls. Most useful products depend on this surrounding system as much as the model itself.

Syntax

UI → Application logic → Prompt/context → Model → Validate → UI

Example

async function answerUser(question) { const context = await retrieveContext(question); const draft = await llm.generate({ question, context }); return validateAndFormat(draft); }

Key Points

  • Applications should own authorization, validation, and auditability.
  • Model changes should be evaluated against product requirements.
Q28Prompt Engineering

What is chain-of-thought prompting?

Chain-of-thought prompting encourages a model to work through a problem in steps, but asking for visible reasoning is not a guarantee of…

Answer

Chain-of-thought prompting encourages a model to work through a problem in steps, but asking for visible reasoning is not a guarantee of correctness or a faithful record of internal computation. For applications, request concise explanations, intermediate artifacts, or verifiable calculations as appropriate rather than relying on hidden reasoning alone.

Syntax

Problem → structured steps or checks → answer → verification

Example

const prompt = `Solve the problem and provide a concise explanation plus a final answer. Problem: ${problem}`;

Key Points

  • For math, use a calculator or executable tool to verify arithmetic.
  • Prefer auditable evidence and checks for high-impact decisions.
Q29Prompt Engineering

What is decomposition prompting?

Decomposition prompting breaks a complex task into smaller sub-tasks, often with explicit intermediate outputs. It can make work easier to…

Answer

Decomposition prompting breaks a complex task into smaller sub-tasks, often with explicit intermediate outputs. It can make work easier to validate and retry, but each step needs clear inputs, bounded scope, and error handling so mistakes do not propagate silently.

Syntax

Complex task → Plan → Subtask A/B/C → Validate → Combine

Example

const outline = await llm.generate({ prompt: `Create a 4-step plan for: ${task}` }); const parts = await Promise.all(outline.steps.map(runStep)); const final = await combineAndValidate(parts);

Key Points

  • Use decomposition when subtasks have clear boundaries.
  • Validate each intermediate result before aggregation.
Q30Prompt Engineering

What is role prompting, and what are its limits?

Role prompting frames the model as a specialist or audience, which can influence tone and emphasis. It does not grant real expertise,…

Answer

Role prompting frames the model as a specialist or audience, which can influence tone and emphasis. It does not grant real expertise, credentials, permissions, or access to private data, so outputs still require evidence and domain-specific validation.

Syntax

Role + Task + Context → Output style and focus

Example

const prompt = `Act as a senior database reviewer. Review this query for performance risks; distinguish confirmed issues from hypotheses: ${sql}`;

Key Points

  • Use roles to set perspective, not to replace factual context.
  • Never use role text as an authorization mechanism.
Q31Prompt Engineering

How do delimiters improve prompts?

Delimiters mark boundaries between instructions and variable content, making the prompt easier for the model and maintainers to interpret. They…

Answer

Delimiters mark boundaries between instructions and variable content, making the prompt easier for the model and maintainers to interpret. They can reduce accidental instruction mixing, but delimiters alone do not neutralize prompt injection inside the delimited content.

Syntax

Instruction | <untrusted_data>…</untrusted_data> | Requested task

Example

const prompt = `Summarize the quoted content as data only: <untrusted_data> ${userText} </untrusted_data>`;

Key Points

  • Use a consistent delimiter convention.
  • Pair delimiters with tool permissions and output validation.
Q32Prompt Engineering

What is prompt injection?

Prompt injection is an attempt to manipulate a model through user input or retrieved content so it ignores intended instructions or performs an…

Answer

Prompt injection is an attempt to manipulate a model through user input or retrieved content so it ignores intended instructions or performs an unintended action. Defenses include treating external text as untrusted, limiting tool capabilities, separating instructions from data, and enforcing authorization outside the model.

Syntax

Untrusted input → Model context → Potential instruction conflict → Guardrails/tools

Example

const docs = await retrieve(query); // Retrieval results are data, not trusted commands. const result = await llm.answer({ question: query, context: docs, tools: readOnlyTools });

Key Points

  • Retrieved webpages and uploaded files can contain hostile instructions.
  • Never rely on prompt wording alone to secure a system.
Q33Prompt Engineering

What is constrained decoding or structured output?

Structured output constrains a model response to a target shape, often JSON or a schema. Some APIs provide grammar- or schema-constrained…

Answer

Structured output constrains a model response to a target shape, often JSON or a schema. Some APIs provide grammar- or schema-constrained generation; otherwise, parse and validate the response and handle failures. Schema compliance still does not prove that the content is factually correct.

Syntax

Schema → Constrained generation → Parse → Validate semantics

Example

const result = await client.responses.create({ model: "YOUR_MODEL", input: "Extract title and year from: ...", text: { format: { type: "json_schema", name: "record", schema: recordSchema } } });

Key Points

  • Confirm exact structured-output syntax for the chosen API.
  • Validate both shape and domain constraints.
Q34Prompt Engineering

How should prompts be versioned?

Store prompts as versioned application artifacts with a clear owner, change notes, and test cases. Versioning allows teams to compare outputs,…

Answer

Store prompts as versioned application artifacts with a clear owner, change notes, and test cases. Versioning allows teams to compare outputs, roll back regressions, and trace which instructions produced a result. Keep secrets and user-specific data out of prompt templates.

Syntax

Prompt v1 → Evaluation set → Prompt v2 → Compare metrics → Release/rollback

Example

const promptConfig = { id: "support-answer", version: "3", template: "Answer using only the supplied policy context: {{context}}" };

Key Points

  • Use source control and code review.
  • Track prompt version in traces and evaluation records.
Q35Prompt Engineering

How do you evaluate prompt quality?

Evaluate prompts on a representative, labeled dataset with explicit criteria such as correctness, relevance, completeness, format adherence,…

Answer

Evaluate prompts on a representative, labeled dataset with explicit criteria such as correctness, relevance, completeness, format adherence, safety, and latency. Use both automated checks and human review, and test edge cases and adversarial inputs before deployment.

Syntax

Prompt versions × Evaluation dataset → Metrics + review → Release decision

Example

const scores = await evaluatePrompt({ promptVersions: [v1, v2], dataset: evalCases, metrics: ["accuracy", "format", "groundedness"] });

Key Points

  • A few hand-picked demos are not enough.
  • Compare performance by scenario and failure type, not only one average score.
Q36Prompt Engineering

What is prompt chaining?

Prompt chaining sends the output of one model call into a subsequent step, such as extraction followed by classification or drafting followed by…

Answer

Prompt chaining sends the output of one model call into a subsequent step, such as extraction followed by classification or drafting followed by review. Each step should have a well-defined contract and validation because errors in early outputs can compound.

Syntax

Input → Extract → Validate → Draft → Review → Final

Example

const facts = await llm.generate({ prompt: extractionPrompt }); const validFacts = factsSchema.parse(facts); const draft = await llm.generate({ prompt: draftPrompt(validFacts) });

Key Points

  • Use deterministic code for simple transformations when possible.
  • Set step limits and log intermediate outputs safely.
Q37Prompt Engineering

What is a self-consistency approach?

Self-consistency samples multiple candidate solutions and selects or aggregates them using a task-appropriate method. It may improve reliability…

Answer

Self-consistency samples multiple candidate solutions and selects or aggregates them using a task-appropriate method. It may improve reliability for some reasoning tasks but costs more and can produce correlated errors, so candidates should be checked with external verifiers where possible.

Syntax

Input → Multiple candidates → Vote/verify → Selected result

Example

const candidates = await Promise.all( Array.from({ length: 3 }, () => llm.generate({ prompt })) ); const answer = await verifier.selectBest(candidates);

Key Points

  • Do not use majority vote as proof of truth.
  • Compare added quality with increased latency and cost.
Q38Prompt Engineering

How can a prompt reduce unsupported claims?

Ask the model to use only provided evidence for source-grounded tasks, distinguish facts from uncertainty, cite evidence identifiers, and state…

Answer

Ask the model to use only provided evidence for source-grounded tasks, distinguish facts from uncertainty, cite evidence identifiers, and state when the context is insufficient. The application must verify citations and ideally restrict claims to retrieved passages rather than trusting the model's self-assessment.

Syntax

Question + Evidence → Answer with citations → Citation validator

Example

const prompt = `Use only the evidence below. Cite each factual claim with [doc_id]. If unsupported, say so. Evidence: ${passages} Question: ${question}`;

Key Points

  • Check that cited IDs exist and support the claim.
  • A prompt cannot guarantee hallucination-free output.
Q39Tokens & Context

How do you estimate token usage and cost?

Estimate input and output token counts using the target tokenizer or provider usage data, then apply the current model's rates for each token…

Answer

Estimate input and output token counts using the target tokenizer or provider usage data, then apply the current model's rates for each token category. Include retries, tool calls, cached input, embeddings, and any separate reasoning or multimodal charges that apply.

Syntax

Estimated cost = input tokens × input rate + output tokens × output rate

Example

const cost = (inputTokens / 1_000_000) * inputRate + (outputTokens / 1_000_000) * outputRate; console.log(cost);

Key Points

  • Use live provider pricing for actual estimates.
  • Measure real usage distributions and budget for long-tail requests.
Q40Tokens & Context

What happens when a prompt exceeds the context window?

A request that exceeds the model's context limit may be rejected, truncated by application logic, or reduced by a framework. The safe behavior…

Answer

A request that exceeds the model's context limit may be rejected, truncated by application logic, or reduced by a framework. The safe behavior is to estimate tokens before sending, deliberately trim or summarize history, and reserve output space rather than depending on undocumented truncation.

Syntax

Conversation → Token budget check → Trim/summarize → Model

Example

const input = await trimToBudget(messages, { maxInputTokens: contextLimit - outputReserve });

Key Points

  • Keep system instructions and current user intent when trimming.
  • Log that truncation occurred without exposing sensitive content.
Q41Tokens & Context

How should long conversations be managed?

Long conversations can be managed by retaining recent turns, summarizing older turns, and preserving durable facts in structured state.…

Answer

Long conversations can be managed by retaining recent turns, summarizing older turns, and preserving durable facts in structured state. Summaries should distinguish user-provided facts from model inferences and be refreshed when contradictions appear; sensitive information should not be retained unnecessarily.

Syntax

Recent turns + Summary + Current request → Context builder

Example

const context = { summary: await summarizeOlderTurns(history.slice(0, -6)), recent: history.slice(-6), current: userMessage };

Key Points

  • Summaries can omit or distort details; keep provenance where needed.
  • Use explicit retention and deletion policies.
Q42Tokens & Context

What is chunking for long documents?

Chunking divides a long document into smaller segments that fit model or retrieval constraints. Useful chunk boundaries follow semantic…

Answer

Chunking divides a long document into smaller segments that fit model or retrieval constraints. Useful chunk boundaries follow semantic structure such as headings or paragraphs, with overlap added only when it helps preserve cross-boundary context. Poor chunking can split definitions from their explanations.

Syntax

Document → Parse structure → Chunks → Embed/index or process

Example

const chunks = splitByHeadings(documentText, { maxTokens: 700, overlapTokens: 80 });

Key Points

  • Choose chunk sizes based on document structure and retrieval tests.
  • Preserve page, section, and source identifiers as metadata.
Q43Tokens & Context

What is token truncation and why is it dangerous?

Token truncation removes part of a prompt or response to fit a limit. It can silently discard critical constraints, source evidence, or the end…

Answer

Token truncation removes part of a prompt or response to fit a limit. It can silently discard critical constraints, source evidence, or the end of JSON output. Applications should truncate deliberately, record the change, and validate that the remaining content is sufficient for the task.

Syntax

Input → Budget guard → Explicit trim → Validate → Request

Example

if (countTokens(prompt) > maxPromptTokens) { prompt = trimNonessentialContext(prompt, maxPromptTokens); }

Key Points

  • Never assume the provider kept the most important content.
  • Validate JSON and completeness after generation.
Q44Tokens & Context

How do you optimize a prompt for token efficiency?

Remove redundant instructions, include only relevant context, compress repeated metadata, and retrieve targeted passages instead of attaching…

Answer

Remove redundant instructions, include only relevant context, compress repeated metadata, and retrieve targeted passages instead of attaching entire documents. Preserve critical rules and evidence, then evaluate quality before and after compression because shorter prompts can lose necessary nuance.

Syntax

Full context → Relevance filter → Deduplicate → Token check → Model

Example

const context = deduplicate(await retrieveRelevant(query)); const prompt = buildPrompt({ instructions, context, query }); assert(countTokens(prompt) < inputBudget);

Key Points

  • Optimize relevance, not merely raw length.
  • Measure answer quality alongside token savings.
Q45Embeddings

How are text embeddings generated?

An embedding model tokenizes input, processes it through a learned neural network, and returns a fixed-size vector representing the text. Some…

Answer

An embedding model tokenizes input, processes it through a learned neural network, and returns a fixed-size vector representing the text. Some models use pooling or other aggregation over token representations. The same model and preprocessing should normally be used for documents and queries in a vector index.

Syntax

Text → Tokenize → Encoder → Pool/project → Vector

Example

const vectors = await embeddings.create({ model: "YOUR_EMBEDDING_MODEL", input: ["First document", "Second document"] });

Key Points

  • Embedding dimension and normalization depend on the model.
  • Respect maximum input length and any required task prefixes.
Q47Embeddings

What is a vector database?

A vector database stores vectors alongside identifiers and metadata and supports similarity search, filtering, and often indexing or update…

Answer

A vector database stores vectors alongside identifiers and metadata and supports similarity search, filtering, and often indexing or update operations. It is a retrieval component, not a substitute for data governance, authorization, source-of-truth storage, or application-level validation.

Syntax

Documents + metadata → Embeddings → Vector DB → Similarity search

Example

await vectorDb.upsert({ id: chunk.id, vector: chunk.embedding, metadata: { sourceId: chunk.sourceId, tenantId: chunk.tenantId } });

Key Points

  • Choose based on scale, filtering, latency, operations, and cost.
  • Keep original content and canonical metadata in a governed store.
Q49Embeddings

How do you choose a chunk size for retrieval?

Choose chunk size by measuring retrieval quality and downstream answer quality across representative queries. Small chunks provide focused…

Answer

Choose chunk size by measuring retrieval quality and downstream answer quality across representative queries. Small chunks provide focused matches but may lack context; large chunks preserve context but can dilute relevance and consume more prompt tokens. Chunking should respect document structure and metadata.

Syntax

Document → Candidate chunk sizes → Retrieval evaluation → Select

Example

for (const size of [300, 500, 800]) { const index = await buildIndex({ chunkTokens: size }); results.push(await evaluateRetrieval(index, testQueries)); }

Key Points

  • There is no universal best chunk size.
  • Tune overlap, chunk size, and top-k together.
Q50Embeddings

What is metadata filtering in retrieval?

Metadata filtering restricts retrieval to documents matching attributes such as tenant, product, date, language, or access scope. Filters can…

Answer

Metadata filtering restricts retrieval to documents matching attributes such as tenant, product, date, language, or access scope. Filters can improve relevance and enforce isolation, but security-critical authorization should also be checked by trusted application logic and supported by the storage layer.

Syntax

Query + allowed metadata filter → Search → Authorized candidates

Example

const hits = await vectorStore.search(vector, { topK: 8, filter: { tenantId: session.tenantId, visibility: "published" } });

Key Points

  • Derive tenant and permission filters from authenticated server state.
  • Test for cross-tenant leakage and filter bypass.
Q51Embeddings

What is embedding drift?

Embedding drift occurs when document and query representations change in distribution or compatibility, often because of a model or…

Answer

Embedding drift occurs when document and query representations change in distribution or compatibility, often because of a model or preprocessing change. Mixing vectors from incompatible embedding versions can damage ranking. Version the embedding model and migrate indexes deliberately.

Syntax

Model v1 index → Re-embed corpus with v2 → Evaluate → Switch index

Example

const record = { embeddingModel: "embedding-model-v2", preprocessingVersion: "3", vector: embedding };

Key Points

  • Store model and preprocessing versions with index metadata.
  • Use parallel indexes or a controlled backfill for migrations.
Q52Embeddings

When should embeddings be regenerated?

Regenerate embeddings when source content changes materially, the embedding model or preprocessing changes, or evaluation reveals degraded…

Answer

Regenerate embeddings when source content changes materially, the embedding model or preprocessing changes, or evaluation reveals degraded retrieval. Use stable document IDs, content hashes, and a queue to avoid unnecessary recomputation and to track failures.

Syntax

Source update → Hash/version check → Re-embed changed chunks → Upsert

Example

if (hash(newText) !== stored.contentHash) { const vector = await embed(newText); await index.upsert({ id, vector, metadata: { contentHash: hash(newText) } }); }

Key Points

  • Avoid duplicate work with content hashes and idempotent jobs.
  • Retire obsolete chunks so stale facts are not retrieved.
Q53Practical GenAI

What is retrieval-augmented generation (RAG)?

RAG retrieves relevant external information and supplies it to a generative model as context before answering. It can improve freshness and…

Answer

RAG retrieves relevant external information and supplies it to a generative model as context before answering. It can improve freshness and grounding without retraining the model, but quality depends on retrieval, source quality, context construction, and answer verification.

Syntax

Question → Retrieve → Rank → Context → LLM → Cited answer

Example

const docs = await retriever.search(question, { topK: 5 }); const answer = await llm.generate({ prompt: `Answer from these sources only: ${formatDocs(docs)}\nQuestion: ${question}` });

Key Points

  • RAG is not a guarantee against hallucination.
  • Measure retrieval recall and answer groundedness separately.
Q54Practical GenAI

What is the difference between RAG and fine-tuning?

RAG supplies relevant data at inference time, making it useful for changing facts and source citations. Fine-tuning changes model parameters to…

Answer

RAG supplies relevant data at inference time, making it useful for changing facts and source citations. Fine-tuning changes model parameters to improve task behavior, style, or domain patterns. They can be combined: fine-tune for consistent behavior and use RAG for up-to-date knowledge.

Syntax

RAG: query → retrieve data → model; Fine-tune: examples → training → updated model

Example

// RAG sketch const context = await retrieve(question); const answer = await llm.generate({ question, context });

Key Points

  • Use RAG when knowledge changes frequently or needs traceable sources.
  • Use fine-tuning when behavior or output patterns need systematic adaptation.
Q55Practical GenAI

What is tool or function calling?

Tool calling lets a model propose a structured call to an application-defined function, such as searching records or calculating a value. The…

Answer

Tool calling lets a model propose a structured call to an application-defined function, such as searching records or calculating a value. The application validates the arguments, checks authorization, executes the tool, and returns its result; the model should not directly control privileged operations.

Syntax

Model proposes tool call → Validate args/auth → Execute → Return result → Model response

Example

const call = await llm.chooseTool({ tools: [{ name: "lookupOrder", schema: orderSchema }] }); const args = orderSchema.parse(call.arguments); const result = await lookupOrderForAuthorizedUser(session.userId, args.orderId);

Key Points

  • A tool call is a request, not permission to execute.
  • Use allowlists, schema validation, least privilege, and audit logs.
Q56Practical GenAI

What is an AI agent?

An AI agent is a system that uses a model to select actions or tools toward a goal, often across multiple steps. Reliable agents need bounded…

Answer

An AI agent is a system that uses a model to select actions or tools toward a goal, often across multiple steps. Reliable agents need bounded objectives, explicit state, allowed tools, stopping conditions, error handling, and human approval for consequential actions.

Syntax

Goal → Model decision → Tool → Observation → Next decision or stop

Example

for (let step = 0; step < maxSteps; step++) { const action = await planner.next(state, allowedTools); if (action.type === "finish") break; state = await executeAndObserve(action, state); }

Key Points

  • Autonomy increases the need for limits and observability.
  • Prefer a deterministic workflow when the task is predictable.
Q57Practical GenAI

What is a model temperature versus top-p?

Temperature rescales token logits before sampling, while top-p sampling retains the smallest set of likely tokens whose cumulative probability…

Answer

Temperature rescales token logits before sampling, while top-p sampling retains the smallest set of likely tokens whose cumulative probability reaches a threshold. Both affect diversity, but their combined effects are model-dependent; tune one at a time on a repeatable evaluation set.

Syntax

Logits → Temperature scaling → Candidate distribution → Top-p filter → Sample

Example

const decoding = { temperature: 0.4, topP: 0.9 }; const output = await generateText({ prompt, ...decoding });

Key Points

  • Avoid blindly setting both to extremes.
  • Some model APIs expose different decoding controls or fixed settings.
Q58Practical GenAI

What are stop sequences?

Stop sequences are configured strings or token patterns that signal generation should end when encountered, where supported by the API. They can…

Answer

Stop sequences are configured strings or token patterns that signal generation should end when encountered, where supported by the API. They can help delimit output but may accidentally stop valid content if the sequence appears naturally, so test them against expected responses.

Syntax

Prompt → Generation → Stop marker detected → Return

Example

const output = await generateText({ prompt, stop: ["\nEND_RECORD"] });

Key Points

  • Prefer structured-output mechanisms for robust boundaries.
  • Check whether the provider supports stop sequences for the selected model.
Q59Practical GenAI

What is model grounding?

Grounding ties generated claims to a specific evidence source, such as retrieved documents, database results, or tool outputs. A grounded answer…

Answer

Grounding ties generated claims to a specific evidence source, such as retrieved documents, database results, or tool outputs. A grounded answer should be traceable to that evidence, and the application should check that citations point to valid sources and that sensitive data is not exposed.

Syntax

Question → Trusted data/tool → Evidence IDs → Answer with references

Example

const evidence = await retrieveAuthorized(question, session); const draft = await llm.answer({ question, evidence }); return validateCitations(draft, evidence);

Key Points

  • Grounding improves traceability but does not guarantee correct interpretation.
  • Keep evidence provenance and access controls intact.
Q60Practical GenAI

How should an LLM be used for classification?

For classification, define a finite label set, provide clear criteria and examples for ambiguous cases, and request a constrained label or…

Answer

For classification, define a finite label set, provide clear criteria and examples for ambiguous cases, and request a constrained label or schema. Evaluate precision, recall, and confusion patterns on labeled data; for critical decisions, use a calibrated classifier or human review when appropriate.

Syntax

Text → Prompt/schema → Label → Validate allowed label → Metrics

Example

const allowed = new Set(["billing", "technical", "account"]); const label = await classify(ticket); if (!allowed.has(label)) throw new Error("Unexpected label");

Key Points

  • Define how to handle unknown or multi-label cases.
  • Measure per-class metrics when classes are imbalanced.
Q61Practical GenAI

How can an LLM extract structured data from text?

Provide the source text, field definitions, data types, and missing-value rules, then use schema-constrained output if available. Validate…

Answer

Provide the source text, field definitions, data types, and missing-value rules, then use schema-constrained output if available. Validate parsed data and retain source spans or evidence when traceability matters. Do not let a model invent a missing value just to fill every field.

Syntax

Source text → Extract fields → Schema validation → Business validation

Example

const schema = z.object({ invoiceNumber: z.string().nullable(), total: z.number().nonnegative().nullable() }); const record = schema.parse(await extractInvoice(text));

Key Points

  • Represent unknown values explicitly, such as null.
  • Validate totals, dates, identifiers, and relationships with code.
Q62Practical GenAI

How do you handle model errors and retries?

Handle transient rate limits and server errors with bounded exponential backoff and jitter, while treating invalid requests and schema failures…

Answer

Handle transient rate limits and server errors with bounded exponential backoff and jitter, while treating invalid requests and schema failures differently. Use request timeouts, cancellation, idempotency where available, and a retry budget so failures do not multiply cost or overload the service.

Syntax

Request → Classify error → Backoff/retry or fail → Fallback/log

Example

for (let attempt = 0; attempt < 3; attempt++) { try { return await callModel(); } catch (e) { if (!isRetryable(e) || attempt === 2) throw e; await sleep(backoffWithJitter(attempt)); } }

Key Points

  • Do not retry permanent validation or authorization failures.
  • Respect provider retry headers and rate limits.
Q63Practical GenAI

How do you reduce LLM latency?

Reduce latency by selecting a suitable model, shortening prompts, limiting unnecessary retrieval and tool calls, streaming output, parallelizing…

Answer

Reduce latency by selecting a suitable model, shortening prompts, limiting unnecessary retrieval and tool calls, streaming output, parallelizing independent work, and caching safe reusable results. Measure time to first token and end-to-end latency separately, since each reveals different bottlenecks.

Syntax

Request → Profile stages → Optimize bottleneck → Re-measure

Example

const [profile, preferences] = await Promise.all([ fetchProfile(userId), fetchPreferences(userId) ]); const response = await streamAnswer({ profile, preferences, query });

Key Points

  • Use quality and cost constraints when choosing a smaller model.
  • Do not cache personalized responses across users without correct cache keys.
Q64Practical GenAI

What is semantic caching?

Semantic caching reuses a previous response when a new request is sufficiently similar to a cached request, often using embeddings. It can lower…

Answer

Semantic caching reuses a previous response when a new request is sufficiently similar to a cached request, often using embeddings. It can lower cost and latency, but approximate matching can return stale or inappropriate answers; use strict scope, freshness, authorization, and similarity thresholds.

Syntax

New query → Embed → Similarity threshold → Cache hit or model call

Example

const cached = await semanticCache.find(queryVector, { scope: tenantId, minSimilarity: 0.94 }); if (cached && !isExpired(cached)) return cached.response;

Key Points

  • Use only where approximate equivalence is safe.
  • Include model, prompt, tenant, and data-version information in cache keys.
Q65Practical GenAI

What is a fallback model strategy?

A fallback strategy routes requests to an alternative model when the primary model is unavailable or exceeds a defined latency or cost…

Answer

A fallback strategy routes requests to an alternative model when the primary model is unavailable or exceeds a defined latency or cost threshold. The fallback must meet the task's minimum quality, privacy, and capability requirements, and the system should log fallback use for evaluation.

Syntax

Primary model → Failure/threshold → Compatible fallback → Record outcome

Example

try { return await primary.generate(input); } catch (error) { if (!shouldFallback(error)) throw error; return await fallback.generate(input); }

Key Points

  • Avoid fallback loops and incompatible response assumptions.
  • Monitor fallback rates and quality degradation.
Q66Practical GenAI

How do you protect API keys used for LLM services?

Store provider credentials in server-side environment configuration or a managed secret store, restrict their permissions, rotate them, and…

Answer

Store provider credentials in server-side environment configuration or a managed secret store, restrict their permissions, rotate them, and avoid logging them. Never embed a private key in browser JavaScript or a public repository, and use a backend proxy that authenticates users and enforces quotas.

Syntax

Browser → Your authenticated backend → Secret store/API key → Model provider

Example

const apiKey = process.env.LLM_API_KEY; if (!apiKey) throw new Error("LLM_API_KEY is not configured"); const client = new LLMClient({ apiKey });

Key Points

  • Use separate credentials for development and production.
  • Apply per-user limits and monitor unusual usage.
Q67Practical GenAI

What is PII and why does it matter for LLM apps?

Personally identifiable information is data that can identify or be linked to a person. LLM applications should minimize collection, redact or…

Answer

Personally identifiable information is data that can identify or be linked to a person. LLM applications should minimize collection, redact or tokenize sensitive fields when appropriate, restrict retention and access, and review provider data handling and applicable legal obligations before sending personal data to an external service.

Syntax

Input → Detect/minimize PII → Policy check → Model → Controlled retention

Example

const safeText = redactPII(userText); const result = await llm.generate({ prompt: safeText });

Key Points

  • Redaction tools can miss context-dependent identifiers.
  • Do not send sensitive data unless the use is authorized and necessary.
Q68Practical GenAI

How do you log LLM requests safely?

Useful observability records include request IDs, model and prompt versions, latency, token usage, tool outcomes, and evaluation signals. Raw…

Answer

Useful observability records include request IDs, model and prompt versions, latency, token usage, tool outcomes, and evaluation signals. Raw prompts and completions may contain secrets or personal data, so logging should be minimized, access-controlled, redacted, and governed by retention rules.

Syntax

Request → Trace metadata + redacted content → Metrics/log store

Example

logger.info({ requestId, model, promptVersion, latencyMs, inputTokens, outputTokens });

Key Points

  • Never log API keys or credentials.
  • Define sampling, redaction, access, and deletion policies.
Q69Practical GenAI

What is an evaluation dataset for a GenAI application?

An evaluation dataset is a curated set of representative inputs with expected outputs, labels, references, or scoring rubrics. It should include…

Answer

An evaluation dataset is a curated set of representative inputs with expected outputs, labels, references, or scoring rubrics. It should include common cases, edge cases, adversarial examples, and failures observed in production, and it should be versioned to make comparisons reproducible.

Syntax

Test cases → Candidate version → Metrics + human review → Regression gate

Example

const report = await runEvalSuite({ dataset: "support-eval-v4", model: candidateModel, prompt: promptVersion });

Key Points

  • Keep a holdout set to reduce overfitting to the test suite.
  • Refresh the set as user behavior and product requirements change.
Q70Practical GenAI

What is an LLM-as-a-judge evaluator?

An LLM-as-a-judge uses a model to score or compare generated outputs against a rubric. It can scale subjective evaluation but may exhibit bias,…

Answer

An LLM-as-a-judge uses a model to score or compare generated outputs against a rubric. It can scale subjective evaluation but may exhibit bias, inconsistent scoring, and preference for longer or stylistically similar answers. Calibrate it against human judgments and use it alongside deterministic checks.

Syntax

Output + Rubric + Reference → Judge model → Score/explanation → Calibration

Example

const judgeScore = await judge.evaluate({ rubric: "Correctness, groundedness, completeness, each 1-5", candidate, reference });

Key Points

  • Use blind pairwise comparisons when appropriate.
  • Do not use a judge model as the only gate for safety-critical behavior.
Q71Practical GenAI

What is retrieval recall and precision?

Retrieval recall measures how much of the relevant evidence was retrieved, while precision measures how much of the retrieved set is relevant. A…

Answer

Retrieval recall measures how much of the relevant evidence was retrieved, while precision measures how much of the retrieved set is relevant. A RAG system can fail because the correct passage was never retrieved or because too much irrelevant context distracted generation, so evaluate retrieval independently.

Syntax

Relevant corpus + Query → Retrieved set → Recall/precision calculation

Example

recall = relevantRetrieved / totalRelevant; precision = relevantRetrieved / totalRetrieved;

Key Points

  • Use judged query-document relevance labels for evaluation.
  • Measure ranking quality as well as top-k set metrics.
Q72Practical GenAI

How should citations be generated in a RAG answer?

Assign stable identifiers to source chunks and pass those identifiers with their text. Ask the model to cite identifiers, then validate every…

Answer

Assign stable identifiers to source chunks and pass those identifiers with their text. Ask the model to cite identifiers, then validate every cited ID and, where feasible, verify claim-to-passage support. Render citations using application-owned source metadata rather than model-invented URLs.

Syntax

Chunks with IDs → Context → Answer [source IDs] → Validate → Render links

Example

const evidence = docs.map((d, i) => ({ id: `S${i+1}`, text: d.text, url: d.url })); const answer = await generateCitedAnswer(question, evidence); const citations = validateSourceIds(answer, evidence);

Key Points

  • Never accept an arbitrary model-generated URL as a trusted citation.
  • Show users when no supporting source was found.
Q73Practical GenAI

What is reranking in retrieval?

Reranking reorders a candidate set using a model that estimates query-document relevance, often after a fast first-stage search. It can improve…

Answer

Reranking reorders a candidate set using a model that estimates query-document relevance, often after a fast first-stage search. It can improve precision at the cost of additional compute and latency; the first-stage retriever must still include relevant candidates.

Syntax

Query → Retrieve top 50 → Reranker → Top 5 context passages

Example

const candidates = await retriever.search(query, { topK: 50 }); const ranked = await reranker.rank(query, candidates); const context = ranked.slice(0, 5);

Key Points

  • Tune candidate count and final context size together.
  • Evaluate whether reranking improves answer outcomes, not only ranking scores.
Q74Practical GenAI

What is query rewriting for RAG?

Query rewriting transforms a user's question into a retrieval-friendly query, for example by resolving references from conversation history or…

Answer

Query rewriting transforms a user's question into a retrieval-friendly query, for example by resolving references from conversation history or expanding terminology. It can help retrieval but may distort intent, so retain the original query and evaluate rewritten queries against the same test set.

Syntax

Conversation + Question → Rewrite → Search → Evidence → Answer

Example

const searchQuery = await llm.generate({ prompt: `Rewrite for document search without changing intent: ${question}` }); const docs = await retrieve(searchQuery);

Key Points

  • Do not let the rewritten query override access filters.
  • Consider multi-query retrieval when a single rewrite is brittle.
Q75Practical GenAI

What is an embedding similarity threshold?

A similarity threshold is a cutoff used to decide whether a retrieved vector match is relevant enough for a downstream action. Scores vary by…

Answer

A similarity threshold is a cutoff used to decide whether a retrieved vector match is relevant enough for a downstream action. Scores vary by model, dataset, and metric, so select the threshold from labeled examples and monitor false positives and false negatives instead of treating a universal value as meaningful.

Syntax

Similarity score → Threshold selected from validation → Accept/reject

Example

const threshold = config.retrievalThreshold; const accepted = matches.filter(m => m.score >= threshold);

Key Points

  • Calibrate by task and embedding model.
  • A high score does not itself prove that a passage answers the question.

Advanced Questions

Architecture, optimization, and design trade-offs.

Q76Practical GenAI

What is grounding versus fine-tuning versus RAG?

Grounding is the broader practice of tying an output to external evidence. RAG is one way to provide evidence through retrieval, while…

Answer

Grounding is the broader practice of tying an output to external evidence. RAG is one way to provide evidence through retrieval, while fine-tuning adapts model parameters to a task or behavior. Grounding may also use tools, databases, or user-provided context without a vector database.

Syntax

External evidence/tool results → Context or checks → Model output; fine-tuning → adapted weights

Example

const records = await authorizedDatabaseLookup(query); const answer = await llm.generate({ prompt: buildGroundedPrompt(query, records) });

Key Points

  • These techniques solve different problems and can be combined.
  • Use evidence freshness, behavior consistency, and evaluation needs to choose.
Q77Practical GenAI

What is a content moderation layer?

A moderation layer checks inputs or outputs against a defined safety policy, using rules, classifiers, provider moderation tools, or human…

Answer

A moderation layer checks inputs or outputs against a defined safety policy, using rules, classifiers, provider moderation tools, or human review. It should be designed for the product's risk profile, with clear handling for uncertain results and without assuming a single classifier catches every harmful case.

Syntax

Input check → Model/tool workflow → Output check → Allow, refuse, or review

Example

const inputCheck = await moderate(userText); if (inputCheck.blocked) return safeRefusal(); const draft = await llm.generate({ prompt: userText }); return (await moderate(draft)).blocked ? safeFallback() : draft;

Key Points

  • Moderation is one layer, not complete security.
  • Test multilingual and adversarial cases relevant to your users.
Q78Practical GenAI

How do you control GenAI cost in production?

Control cost by selecting fit-for-purpose models, limiting output tokens, caching safe results, reducing unnecessary context, batching…

Answer

Control cost by selecting fit-for-purpose models, limiting output tokens, caching safe results, reducing unnecessary context, batching embeddings, setting per-user budgets, and monitoring cost per successful task. Quality and failure rates must be measured so cheaper configurations do not create expensive retries or poor outcomes.

Syntax

Usage telemetry → Cost per task → Budget/limits → Optimization experiment

Example

if (userMonthlySpend(userId) > budgetLimit) { return useApprovedLowCostPathOrAskForReview(); }

Key Points

  • Track input, output, embedding, and tool costs separately.
  • Use quotas and alerts before hard limits are reached.
Q79Practical GenAI

What is batch inference?

Batch inference processes many independent inputs together or asynchronously to improve throughput and reduce overhead, often for embeddings,…

Answer

Batch inference processes many independent inputs together or asynchronously to improve throughput and reduce overhead, often for embeddings, document extraction, or offline classification. It is unsuitable for every interactive request because waiting for a batch can increase latency.

Syntax

Queue items → Batch model request/job → Results → Persist/retry failures

Example

const jobs = await embeddingApi.createBatch({ inputs: documents }); await pollUntilComplete(jobs.id);

Key Points

  • Follow provider batch limits and expiration rules.
  • Make processing idempotent and track per-item failures.
Q80Practical GenAI

What is caching in an LLM pipeline?

Caching stores reusable results from expensive stages, such as embeddings, retrieval queries, or deterministic model responses. Cache keys must…

Answer

Caching stores reusable results from expensive stages, such as embeddings, retrieval queries, or deterministic model responses. Cache keys must include the relevant prompt/model/data versions and security scope; otherwise, cached results may be stale, incorrect, or leaked across users.

Syntax

Request → Cache lookup → Hit returns result / miss executes pipeline → Store

Example

const key = hash({ promptVersion, model, tenantId, normalizedInput }); const cached = await cache.get(key); if (cached) return cached; const result = await runPipeline(); await cache.set(key, result, { ttlSeconds: 300 });

Key Points

  • Avoid caching sensitive or rapidly changing answers without safeguards.
  • Invalidate on source, policy, or model changes as needed.
Q81Practical GenAI

What is human-in-the-loop review?

Human-in-the-loop review routes uncertain, high-impact, or policy-sensitive cases to a person before final action. The system should present…

Answer

Human-in-the-loop review routes uncertain, high-impact, or policy-sensitive cases to a person before final action. The system should present evidence, uncertainty signals, and proposed actions clearly, and record the review decision while allowing the person to correct the model.

Syntax

Model draft + evidence + risk score → Human review → Approve/edit/reject

Example

if (riskScore >= reviewThreshold) { return await requestHumanApproval({ draft, evidence, proposedAction }); }

Key Points

  • Use review for consequential decisions and irreversible actions.
  • Design escalation paths and measure reviewer agreement and workload.
Q82Practical GenAI

How should an LLM application handle untrusted retrieved documents?

Treat retrieved text as data rather than instructions, restrict the model's available tools, and include only authorized, relevant passages.…

Answer

Treat retrieved text as data rather than instructions, restrict the model's available tools, and include only authorized, relevant passages. Tool execution and access checks must occur in trusted application code, and output should be checked for unsupported claims or leaked secrets.

Syntax

User query → Authorized retrieval → Untrusted passages → Limited model → Validate

Example

const docs = await retrieveWithACL(query, user); const response = await llm.generate({ prompt: promptWithUntrustedData(docs), tools: readOnlyTools }); return outputPolicyCheck(response);

Key Points

  • Prompt injection may be present in documents and metadata.
  • Do not give a retrieval-augmented model unrestricted write tools.
Q83Practical GenAI

What is model routing?

Model routing selects a model or workflow based on task complexity, modality, latency, cost, and quality requirements. A router can use rules, a…

Answer

Model routing selects a model or workflow based on task complexity, modality, latency, cost, and quality requirements. A router can use rules, a classifier, or a model, but it should have a safe default, transparent policy, and evaluation across all routed paths.

Syntax

Request features → Router → Small/large/specialized model → Response

Example

const route = classifyTask(request); const model = route === "simple" ? fastModel : route === "complex" ? strongModel : defaultModel; return model.generate(request);

Key Points

  • Do not route solely on an unvalidated model guess.
  • Monitor quality and cost for each route.
Q84Practical GenAI

What is a model context protocol (MCP) at a high level?

Model Context Protocol (MCP) is an interoperability approach for connecting AI applications to external tools and resources through a defined…

Answer

Model Context Protocol (MCP) is an interoperability approach for connecting AI applications to external tools and resources through a defined client-server protocol. MCP can standardize discovery and invocation, but applications still need to validate server trust, permissions, input/output schemas, and side effects.

Syntax

AI host/client ↔ MCP server ↔ Tools/resources

Example

// Conceptual only: exact SDK methods depend on the MCP implementation. const tools = await mcpClient.listTools(); const safeTools = filterAllowedTools(tools, currentUserPermissions);

Key Points

  • Treat remote MCP servers as external dependencies.
  • Confirm user consent and authorization before sensitive tool actions.
Q85Practical GenAI

What is the difference between a tool call and a normal text answer?

A normal text answer is content intended for the user, while a tool call is a structured request for the application to execute a defined…

Answer

A normal text answer is content intended for the user, while a tool call is a structured request for the application to execute a defined operation. The application should validate the call, run it under appropriate permissions, and return the result as data before the model continues or responds.

Syntax

Model output → {text} OR {tool name, arguments} → Application dispatch

Example

if (message.type === "tool_call") { const args = toolSchema.parse(message.arguments); return executeAllowedTool(message.name, args, session); }

Key Points

  • Do not parse arbitrary natural language as an executable command.
  • Keep tool schemas narrow and side effects explicit.
Q86Practical GenAI

What is a refusal and when should an app use one?

A refusal is a response declining to help with a request that cannot be safely or appropriately fulfilled. Applications should define…

Answer

A refusal is a response declining to help with a request that cannot be safely or appropriately fulfilled. Applications should define policy-specific behavior, explain limits briefly, and offer a safe alternative when possible. A model's refusal behavior should be tested rather than assumed.

Syntax

Request → Policy/risk assessment → Safe response or refusal

Example

if (!policyAllows(request)) { return { answer: "I can't help with that action, but I can explain a safe alternative." }; }

Key Points

  • Distinguish unsafe requests from harmless uncertainty.
  • Enforce policy in orchestration and tools as well as model prompts.
Q87Practical GenAI

What is prompt injection versus jailbreak?

Prompt injection usually refers to malicious instructions placed in user input or external content to alter a model's behavior. A jailbreak is…

Answer

Prompt injection usually refers to malicious instructions placed in user input or external content to alter a model's behavior. A jailbreak is an attempt to bypass the model's safety constraints, often through crafted requests or role-play. Both require layered defenses; neither is solved reliably by adding a single warning sentence.

Syntax

Malicious content → Instruction conflict/bypass attempt → Defense layers

Example

const allowed = enforceToolPolicy(request, session); const safeInput = labelAndIsolateUntrustedContent(request); return runWithLeastPrivilege(safeInput, allowed);

Key Points

  • Use policy checks, sandboxing, and least privilege.
  • Test direct and indirect injection paths.
Q88Practical GenAI

What is a guardrail in a GenAI system?

A guardrail is a control that constrains or checks inputs, outputs, tools, or workflow state. Examples include schema validation, retrieval…

Answer

A guardrail is a control that constrains or checks inputs, outputs, tools, or workflow state. Examples include schema validation, retrieval permissions, output moderation, budget limits, and human approval. Effective guardrails are layered and tested against realistic failure modes.

Syntax

Input controls → Model/tool controls → Output validation → Monitoring

Example

const parsed = outputSchema.safeParse(modelOutput); if (!parsed.success) return retryOrFallback(); if (!withinPolicy(parsed.data)) return safeFallback();

Key Points

  • A prompt instruction alone is a weak guardrail.
  • Each guardrail should have a defined failure response.
Q89Practical GenAI

What is an LLM observability trace?

A trace links the stages of one request, such as prompt construction, retrieval, reranking, model calls, tools, and validation. Traces help…

Answer

A trace links the stages of one request, such as prompt construction, retrieval, reranking, model calls, tools, and validation. Traces help diagnose latency and quality failures, but they must avoid indiscriminate collection of sensitive prompt and response data.

Syntax

Request ID → Retrieval span → Model span → Tool span → Validation span

Example

const trace = startTrace({ requestId, userIdHash, promptVersion }); trace.span("retrieve", () => retrieve(query)); trace.span("generate", () => llm.generate(input)); trace.end();

Key Points

  • Record versions, timing, token usage, and outcomes.
  • Redact sensitive values and restrict trace access.
Q90Practical GenAI

How do you compare two LLM models fairly?

Compare models on the same versioned test cases, prompts, context, and decoding constraints, using task-specific quality metrics alongside…

Answer

Compare models on the same versioned test cases, prompts, context, and decoding constraints, using task-specific quality metrics alongside latency, cost, reliability, and safety. Include enough cases to reveal variation and use blind human review for subjective dimensions where useful.

Syntax

Same dataset + same rubric → Model A/B outputs → Quality/cost/latency comparison

Example

const reportA = await evaluate(modelA, evalSet, config); const reportB = await evaluate(modelB, evalSet, config); compareReports(reportA, reportB);

Key Points

  • Avoid selecting from a few cherry-picked prompts.
  • Test realistic production traffic and edge cases before switching.
Q91Practical GenAI

What is a canary rollout for a model or prompt change?

A canary rollout exposes a new model or prompt to a small share of traffic before broader release. Teams compare safety, quality, latency, and…

Answer

A canary rollout exposes a new model or prompt to a small share of traffic before broader release. Teams compare safety, quality, latency, and cost against the current version and roll back if metrics exceed predefined thresholds.

Syntax

Old version 95% + New version 5% → Monitor → Expand or rollback

Example

const version = hash(userId) % 100 < 5 ? candidate : stable; return runWithVersion(version, request);

Key Points

  • Use stable assignment where comparisons need repeatability.
  • Define rollback thresholds before the rollout begins.
Q92Practical GenAI

What is deterministic post-processing and why use it?

Deterministic post-processing uses ordinary code to validate, normalize, calculate, or enforce rules after generation. It is more reliable than…

Answer

Deterministic post-processing uses ordinary code to validate, normalize, calculate, or enforce rules after generation. It is more reliable than asking a model to perform exact operations repeatedly, and it separates language generation from rules that must always hold.

Syntax

LLM draft → Parse → Deterministic checks/transform → Final response

Example

const parsed = schema.parse(modelOutput); const total = parsed.items.reduce((sum, item) => sum + item.quantity * item.price, 0); return { ...parsed, total };

Key Points

  • Use code for arithmetic, permissions, and exact formatting.
  • Keep generated values untrusted until validated.
Q93Practical GenAI

How can an LLM summarize a document reliably?

Provide a clear target length and audience, preserve important facts and caveats, and use chunked or hierarchical summarization for long…

Answer

Provide a clear target length and audience, preserve important facts and caveats, and use chunked or hierarchical summarization for long documents. For high-stakes summaries, compare the summary against source evidence and retain references to sections so omissions and distortions can be investigated.

Syntax

Document → Section summaries → Combined summary → Evidence check

Example

const sectionSummaries = await Promise.all(sections.map(s => summarize(s.text))); const summary = await summarize(sectionSummaries.join("\n")); return verifyAgainstSource(summary, sections);

Key Points

  • Summaries can omit exceptions and minority viewpoints.
  • Avoid exceeding the context budget with the full source.
Q94Practical GenAI

How should an LLM answer when information is missing?

Define a missing-information policy that tells the model to ask a clarifying question, state an assumption, or say that the evidence is…

Answer

Define a missing-information policy that tells the model to ask a clarifying question, state an assumption, or say that the evidence is insufficient. The application can enforce required fields and prevent downstream actions until essential information is provided.

Syntax

Request → Missing-field check → Clarify / answer with caveat / stop

Example

const missing = requiredFields.filter(k => input[k] == null); if (missing.length) return { needsClarification: true, fields: missing };

Key Points

  • Do not let the model invent required identifiers or facts.
  • Make uncertainty visible and actionable.
Q96Practical GenAI

What is a reranker's difference from an embedding model?

An embedding model independently encodes texts into vectors, enabling fast indexed retrieval. A reranker typically scores a query and candidate…

Answer

An embedding model independently encodes texts into vectors, enabling fast indexed retrieval. A reranker typically scores a query and candidate passage together, often capturing finer relevance at greater per-candidate cost. Systems commonly use embeddings or lexical search to generate candidates and a reranker to refine them.

Syntax

Query + corpus → Embedding/keyword retrieval → Candidates → Query-passage reranker

Example

const candidates = await vectorSearch(queryVector, 40); const ranked = await crossEncoder.rerank(query, candidates);

Key Points

  • Rerankers cannot recover a relevant document absent from candidates.
  • Compare the accuracy-latency trade-off on real queries.
Q97Practical GenAI

How do you safely let an LLM access a database?

Expose narrow, parameterized operations through a service layer rather than unrestricted database credentials or arbitrary SQL execution.…

Answer

Expose narrow, parameterized operations through a service layer rather than unrestricted database credentials or arbitrary SQL execution. Authenticate the user, apply row-level authorization, limit returned fields and row counts, and log actions. Read-only access is safer but still requires controls against sensitive data exposure.

Syntax

User → Authorized service function → Parameterized query → Filtered result → Model

Example

const order = await db.orders.findFirst({ where: { id: requestedId, userId: session.userId }, select: { id: true, status: true, updatedAt: true } });

Key Points

  • Never rely on the model to enforce tenant boundaries.
  • Use least-privilege database roles and query limits.
Q98Practical GenAI

What is a grounding score and how should it be used?

A grounding score estimates whether generated claims are supported by supplied evidence, using a rubric, model evaluator, or specialized metric.…

Answer

A grounding score estimates whether generated claims are supported by supplied evidence, using a rubric, model evaluator, or specialized metric. It is a useful signal but not a proof, so calibrate it with human-labeled examples and combine it with citation checks and domain-specific rules.

Syntax

Answer claims + Evidence → Grounding evaluator → Score → Threshold/review

Example

const score = await evaluateGroundedness({ answer, evidence }); if (score < calibratedThreshold) return requestReview(answer);

Key Points

  • Scores depend on evaluator and task.
  • Do not present an uncalibrated score as a probability of truth.
Q99Practical GenAI

What is a context compression strategy?

Context compression removes irrelevant content or summarizes long history and documents while preserving facts needed for the current task. It…

Answer

Context compression removes irrelevant content or summarizes long history and documents while preserving facts needed for the current task. It can reduce latency and cost, but should be evaluated for lost constraints, citations, numbers, and exceptions. Keep original sources available for verification.

Syntax

Large context → Relevance selection/summarization → Compact context → Model

Example

const compact = await compressContext(context, { query, preserve: ["dates", "amounts", "source_ids", "exceptions"] });

Key Points

  • Compression is task-dependent and can lose nuance.
  • Retain provenance so a summary can be traced back to source material.
Q100Practical GenAI

How should a model's knowledge cutoff affect application design?

A model's training cutoff means it may lack later events or current state, and even older knowledge may be incomplete. Applications needing…

Answer

A model's training cutoff means it may lack later events or current state, and even older knowledge may be incomplete. Applications needing current facts should retrieve authoritative up-to-date sources or call a live system, display source timestamps, and avoid assuming that the model knows current account data.

Syntax

Question about current facts → Live source/tool → Model summarizes evidence

Example

const currentData = await officialApi.fetchLatest(query); return llm.generate({ prompt: buildPrompt({ query, currentData }) });

Key Points

  • Check freshness and source authority.
  • Use application databases for user-specific current state.

Share this question bank

Send this page to someone preparing for an interview.