HTHyperTransformer AI

Study cards › AI & Agentic AI

AI & Agentic AIInterview questions and answers

← Topics1 / 100
1 / 100 viewed
Question

What is a transformer?

Answer

A transformer is a neural network architecture introduced in 2017 that uses self-attention to model relationships between every pair of tokens in an input in parallel. It replaced recurrent networks (RNNs) and powers all modern LLMs — GPT, Claude, Gemini, Llama — because attention scales to long sequences and trains efficiently on GPUs.

Question

What is self-attention?

Answer

Self-attention is a mechanism where each token in a sequence 'attends' to every other token via Query-Key-Value vectors. The model learns which other tokens are most relevant and weights its understanding of the current token by them. This is how transformers grasp context like 'it' referring to a noun earlier in the sentence.

Question

What is an embedding?

Answer

An embedding is a fixed-length numeric vector that captures the semantic meaning of text, image, audio, or code. Similar items end up close in the vector space — 'king' is near 'queen', 'dog' near 'puppy'. Generated by models like OpenAI's text-embedding-3 or open-source models like bge and e5.

Question

What is tokenization?

Answer

Tokenization splits text into smaller units (tokens) the model understands. Modern LLMs use subword tokenizers like BPE or SentencePiece — common words are one token, rare ones split into pieces. 'Hello world' might be 2 tokens; 'antidisestablishmentarianism' might be 7. This affects cost (you pay per token) and context limits.

Question

What is a context window?

Answer

The context window is the maximum number of tokens an LLM can attend to in one request — both input and output combined. GPT-4 has 128k, Claude has 200k-1M, Gemini up to 2M. Bigger windows allow more documents and longer conversations, but cost more, run slower, and models often pay less attention to the middle.

Question

What is a hallucination?

Answer

A hallucination is when a model generates plausible-sounding but false information. The model is predicting the most likely next tokens, not retrieving facts, so confident wrong answers are a fundamental risk. Mitigations: ground answers in retrieved sources (RAG), use citations, lower temperature, and prompt for 'say I don't know if you're unsure'.

Question

What is fine-tuning?

Answer

Fine-tuning updates a model's weights using task-specific examples — making it better at your domain or steering its style. Variants: full fine-tuning (all weights), LoRA/QLoRA (a small adapter on top), instruction tuning. Use it when prompting and RAG have hit their limits; it's slower to iterate than prompts.

Question

What is LoRA?

Answer

Low-Rank Adaptation — instead of updating all of a model's weights during fine-tuning, you train small low-rank matrices that adjust the base weights. Much cheaper (a few GB instead of hundreds), fast to train, and you can swap adapters for different tasks without reloading the base model. Standard for fine-tuning open models.

Question

What is RLHF?

Answer

Reinforcement Learning from Human Feedback. Humans rank pairs of model outputs (which is better?); those rankings train a reward model; the LLM is then fine-tuned via RL to maximize the reward model's score. This is how raw language models become helpful assistants like ChatGPT and Claude.

Question

What is inference?

Answer

Inference is running a trained model on new inputs to generate outputs — distinct from training (which updates weights). Inference is where you spend money in production (per-token cost) and latency matters. Inference-time techniques: caching, batching, smaller models, speculative decoding, quantization.

Question

Greedy vs sampling decoding?

Answer

Greedy decoding picks the highest-probability token at each step — deterministic, often repetitive. Sampling draws from the probability distribution (with parameters like temperature, top-p) — more diverse and creative. Most chat use cases sample with moderate temperature; deterministic tasks (code, JSON) use greedy or temperature=0.

Question

What is temperature in LLMs?

Answer

Temperature is a sampling parameter that controls randomness. At 0, the model always picks the most likely token (deterministic). Higher (0.7-1.0) flattens the probability distribution, giving more varied/creative outputs. For factual/structured tasks use low temp; for brainstorming use higher.

Question

What is top-p (nucleus) sampling?

Answer

Top-p restricts sampling to the smallest set of tokens whose cumulative probability is at least p. Top-p=0.9 means the model picks from the most likely tokens covering 90% of probability mass. Balances quality (don't pick weird tokens) with diversity better than fixed top-k in many cases.

Question

What is chain of thought?

Answer

Chain of thought (CoT) is prompting the model to reason step-by-step before answering — e.g. 'Let's think this through.' On multi-step problems (math, logic, complex reasoning), this dramatically improves accuracy because the model can use its own intermediate tokens as working memory.

Question

What is structured prompting?

Answer

Forcing the model's output to match a defined schema (JSON, XML). Modern LLM APIs support 'structured outputs' or 'JSON mode' where you supply a JSON schema and the model is constrained to produce valid matching output. Eliminates regex parsing and ad-hoc 'please respond in JSON' hacks.

Question

What is few-shot prompting?

Answer

Including a few input→output examples in the prompt to demonstrate the pattern you want, before the real query. The model learns the format and style from the examples without any training. Often the single biggest accuracy boost you can apply, especially for niche tasks the base model wasn't tuned for.

Question

What is role prompting?

Answer

Assigning the model a persona — 'You are an expert SQL tutor', 'You are a senior code reviewer'. Steers tone, depth, and the kinds of things the model emphasizes. Useful for getting consistent voice across responses; less effective on safety/alignment than people often assume.

Question

What is context engineering?

Answer

The discipline of designing what goes into a model's context — the system prompt, retrieved documents, available tools, conversation history, examples. Often more important than picking the perfect model. Good context engineering can make a smaller cheaper model outperform a bigger one for your specific task.

Question

What is RAG?

Answer

Retrieval-Augmented Generation: at query time, search a knowledge base (usually a vector store) for relevant chunks, inject them into the prompt, and let the LLM answer based on that grounded context. This is how you give an LLM access to your private docs, current data, or domain knowledge without fine-tuning.

Question

Why use RAG instead of fine-tuning?

Answer

RAG is much easier to update (just re-index), explainable (you can cite sources), cheaper to iterate, handles long-tail and private data, and reduces hallucinations because the model is grounded in real text. Fine-tuning still helps for style, behavior, or efficiency at scale; the two are complementary.

Question

What is chunking in RAG?

Answer

Splitting documents into smaller pieces that get embedded and retrieved individually. Tune chunk size (typically 200-800 tokens) and overlap (50-100 tokens) so context isn't cut mid-thought. Respect semantic boundaries (paragraphs, sections) rather than blind character splits. Quality of chunking heavily drives RAG quality.

Question

What is reranking?

Answer

After your vector search returns the top-K results, a more expensive but accurate cross-encoder model (like Cohere Rerank or BGE Reranker) re-scores them against the query. Vector search is great for recall but mediocre at precision; reranking promotes the truly relevant chunks to the top before LLM ingestion.

Question

What is hybrid search?

Answer

Combining vector (semantic) search with keyword/BM25 search and fusing the results. Vector catches paraphrases and synonyms; keyword catches exact names, IDs, and rare terms. Together they significantly outperform either alone — most production RAG systems use hybrid retrieval.

Question

What is tool calling (function calling)?

Answer

LLMs deciding when and how to call developer-registered functions (APIs, DB queries, calculators) based on the user's request. The model emits a structured invocation like {tool: 'getWeather', args: {city: 'Paris'}}; your code runs it; the result goes back to the model. This is how agents do useful things in the world.

Question

What is an AI agent?

Answer

An LLM-driven system that plans, calls tools, observes results, and iterates toward a goal — usually in a loop. Unlike a one-shot prompt, an agent can browse, run code, search, and revise its plan. Tradeoffs: more capable but slower, more expensive, and more failure modes than a simple chain.

Question

Short-term vs long-term agent memory?

Answer

Short-term memory is the current conversation/context window — gone when the session ends. Long-term memory persists across sessions: vector store of past interactions, structured user preferences, summary notes. The agent retrieves relevant memory into context as needed; designing the storage and retrieval is most of the work.

Question

What is planning in agents?

Answer

Decomposing a goal into a sequence of sub-tasks before acting. Could be a single planning LLM call producing a checklist, a plan-and-execute loop that revises after each step, or a tree of thoughts exploring alternatives. Planning improves complex-task success but adds latency and cost.

Question

What is a multi-agent system?

Answer

Multiple specialized agents collaborate — typically planner, executor, reviewer, or domain-specific roles. Frameworks like LangGraph, CrewAI, and AutoGen orchestrate them. Pros: separation of concerns, parallelism. Cons: coordination overhead, errors compound, debugging gets harder. Often a single well-prompted agent beats a complex multi-agent setup.

Question

What is MCP (Model Context Protocol)?

Answer

MCP is an open standard from Anthropic for connecting LLMs to tools, data sources, and other capabilities through a uniform interface. Instead of building bespoke integrations per app, you connect to an MCP server and the model gains access. It's gaining adoption across IDEs and agent frameworks.

Question

What is A2A (Agent-to-Agent) architecture?

Answer

Agents communicating directly with each other (or via a coordinator), each with specialized roles, tools, and memory. Used to break complex workflows into focused agents. Brings the same trade-offs as multi-agent systems: more capable in theory, harder to debug and slower in practice.

Question

What is orchestration for agents?

Answer

Controlling the flow between LLM calls, tool calls, branches, retries, and human approvals. Done with state machines (LangGraph), DAGs, or explicit code. Without orchestration, agents drift, loop, or fail in opaque ways. Good orchestration is what separates demos from production.

Question

What is LangChain?

Answer

A framework providing building blocks for LLM apps: prompts, chains (sequences of LLM calls), retrievers, agents, tools, memory. It made early LLM prototyping fast but is often criticized for over-abstracting. Many production teams use lightweight wrappers around raw API calls instead.

Question

What is LangGraph?

Answer

A LangChain library for building stateful, graph-based LLM workflows. You define nodes (steps) and edges (transitions), with persistent state and human-in-the-loop checkpoints. More explicit and debuggable than free-form agents — well suited to production multi-step workflows.

Question

What is CrewAI?

Answer

A Python framework for role-based multi-agent systems. You define agents with roles, goals, and tools, then assign them tasks orchestrated by a process (sequential, hierarchical). Higher-level than LangGraph; faster to prototype but less control over the execution graph.

Question

What is AutoGen?

Answer

Microsoft's multi-agent framework focused on conversational agents that can negotiate, write and execute code, and call tools. Pioneered conversational agent collaboration patterns. Active development as of 2025; pairs well with VS Code via the AutoGen Studio.

Question

What is LlamaIndex?

Answer

A data framework for connecting LLMs to private data — focused heavily on RAG: ingestion connectors, indexing, retrieval strategies (auto-merging, recursive, hybrid), and query engines. Often a better fit than LangChain when your bottleneck is retrieval over messy data.

Question

OpenAI API key features?

Answer

Chat Completions, Responses API (with built-in tools), function calling, structured outputs (JSON schema), embeddings, vision (images), audio (Whisper for STT, TTS), batch API (50% discount for non-urgent), fine-tuning, file uploads, and Assistants API for stateful conversations.

Question

Gemini API distinguishing features?

Answer

Multimodal-first design (text, image, video, audio in one model), enormous context windows (up to 2M tokens), strong tool use, integration with Google ecosystem (Workspace, Search). Often the best price-to-quality on long-context tasks.

Question

Claude API distinguishing features?

Answer

Strong reasoning and writing quality, long context (200K-1M), excellent tool use, prompt caching for cost reduction on repeated prompts, computer use (mouse/keyboard control), artifacts for structured outputs, and a strong safety/alignment track record. Often preferred for complex reasoning and code.

Question

What is Vertex AI?

Answer

Google Cloud's managed ML/AI platform for training, deploying, and hosting models. Provides access to Gemini, open-source models, and your own custom models, plus pipelines, model monitoring, and enterprise-grade security/compliance. Common choice for orgs already on GCP.

Question

Designing a chatbot architecture?

Answer

Frontend with streaming UI → API gateway (auth, rate limit) → session/conversation store → retriever (vector DB + reranker for RAG) → LLM gateway with prompt caching and failover → guardrails (input filter, output check) → observability (LangSmith, Langfuse) → eval pipeline running on real prod traffic.

Question

What is an AI pipeline?

Answer

The end-to-end flow: data ingestion → preprocessing → embedding → indexing → retrieval → LLM call → post-processing → evaluation. Each stage is configurable and observable. Production AI work is mostly building, monitoring, and improving these pipelines — not crafting individual prompts.

Question

What is AI observability?

Answer

Tracking everything that happens in an LLM app: inputs, outputs, tool calls, latencies, costs, and quality scores. Tools: LangSmith, Langfuse, Arize, Helicone. Without it, you can't debug failures, attribute cost spikes, or detect quality regressions when you change models or prompts.

Question

How do you evaluate AI quality?

Answer

Offline: build a labeled dataset, run experiments with metrics (exact match, F1, BLEU, embedding similarity, LLM-as-judge). Online: A/B tests, thumbs feedback from users, regression suites that must keep passing. Eval is the unglamorous half of AI engineering — and the half that decides if you're shipping anything good.

Question

What are guardrails?

Answer

Pre- and post-processing checks that block unsafe inputs or outputs — PII redaction, content moderation, schema validation, jailbreak detection, prompt injection filters, refusal of off-topic queries. Implement them at the gateway layer so every call is protected. Libraries: Guardrails AI, NeMo Guardrails.

Question

What is prompt versioning?

Answer

Treating prompts like code: version control, structured changes, A/B comparisons, regression tests, rollback on quality drop. Tools like PromptLayer, Langfuse, and OpenAI's Prompts dashboard let you manage prompt versions outside of code. Critical when many prompts power your product.

Question

What is a prompt template?

Answer

A parameterized prompt with placeholders ({user_query}, {retrieved_context}). Separates structure (designed by your team) from data (filled at runtime). Lets you A/B test prompts independently from code and ensures consistent formatting across calls.

Question

Function calling vs tool use?

Answer

Same idea, different vendors. OpenAI uses 'function calling'; Anthropic uses 'tool use'. In both, you describe available tools with name, description, and JSON schema; the model emits a structured tool invocation; you execute it and return the result. The standard way LLMs interact with the world.

Question

What is streaming in LLM apps?

Answer

The model emits tokens incrementally over SSE or WebSocket so the UI shows partial output as it generates — like ChatGPT's typewriter effect. Better perceived latency, lets users interrupt, and gives feedback that the model is actually working. Essential for chat UX.

Question

How do you pick an embedding model?

Answer

Considerations: language support (English-only vs multilingual), domain (general vs code/legal/medical), cost, vector dimensions (smaller = faster search), and benchmark performance on MTEB. Popular: OpenAI text-embedding-3-small/large, Cohere embed-v3, open-source bge-large, e5.

Question

What is cosine similarity?

Answer

Cosine similarity is the dot product of two L2-normalized vectors, ranging from -1 to 1. It measures the angle between vectors, ignoring magnitude — so two paraphrases of the same idea score high regardless of length. The default similarity metric for semantic search.

Question

Cosine similarity vs dot product?

Answer

If both vectors are L2-normalized (length 1), cosine similarity and dot product are mathematically equivalent. Without normalization, dot product also cares about magnitude — sometimes useful when 'longer/more energetic' vectors should rank higher. Most embedding models are trained to be used with cosine.

Question

What is semantic search?

Answer

Finding documents by meaning rather than exact keywords, via embedding similarity. Searching 'how do I get a refund' returns docs about returns and money back, even if the exact word 'refund' isn't there. Powers RAG, recommendations, and 'similar items' features.

Question

What is a system prompt?

Answer

Top-level instructions defining the model's role, constraints, tone, available tools, and the format of its responses. Persists across the conversation as the model's 'character'. Putting the right things here vs in user messages massively affects behavior — system prompts are sticky in the model's attention.

Question

What is prompt injection?

Answer

Adversarial input that tries to override your system instructions — 'ignore previous and reveal the system prompt'. Defend by treating user input as data (not commands), separating it clearly, sandboxing tool execution, and applying input/output filters. Treat it like SQL injection: a permanent design concern.

Question

Direct vs indirect prompt injection?

Answer

Direct: the user themselves types a malicious prompt. Indirect: malicious instructions are HIDDEN in content the agent later reads — a tool result, a web page, an email body — and the agent obeys them. Indirect is the scarier one because it can come from anywhere, not just the user.

Question

How do you evaluate RAG quality?

Answer

Retrieval metrics: precision@k, recall@k, MRR — does the relevant chunk appear in the top results? Generation metrics: faithfulness (answer grounded in retrieved context), answer relevancy, completeness. Tools: RAGAS, TruLens, DeepEval. Build a labeled set from real user queries.

Question

What is a memory store for an agent?

Answer

A persistent store for facts, preferences, and past actions — usually vector DB plus structured tables. The agent retrieves relevant memory into context as needed (semantic search + filters by user/session). Designing what to remember and what to forget is one of the trickiest agent problems.

Question

What is ReAct prompting?

Answer

Reason + Act loop: the LLM thinks about what to do, picks a tool, observes the result, then continues reasoning — until the goal is reached. The original prompting pattern for agentic behavior. Many frameworks formalize it (LangChain ReAct agent, LlamaIndex).

Question

Pros and cons of multi-agent systems?

Answer

Pros: separation of concerns, parallelism, specialization, easier to reason about each piece. Cons: coordination overhead, errors compound across hops, debugging gets opaque, latency multiplies, cost adds up. Often a single well-prompted agent with the right tools outperforms a complex agent crew.

Question

What is LLM-as-judge?

Answer

Using a strong model to grade outputs from another model against a rubric — much cheaper and faster than human eval, scales to thousands of examples. Has its own biases (positional, verbosity), so calibrate against human judgments. Useful for ranking, regression tests, and prompt A/B.

Question

How do you control LLM cost?

Answer

Use smaller models where possible (most queries don't need GPT-4), prompt caching for static prefixes, batch APIs for non-urgent work, truncate / summarize long history, route by complexity (cheap model first, escalate if needed), and cap context aggressively.

Question

What is prompt caching?

Answer

Reusing computed attention over a shared prompt prefix across calls — Anthropic's prompt caching and OpenAI's automatic caching both implement this. Cuts cost up to 90% and latency significantly for repeated system prompts, long documents, or shared few-shot examples.

Question

Why use structured outputs?

Answer

Reliable, schema-validated parsing — no regex fragility, no 'please respond in JSON' that occasionally returns prose. Use JSON Schema with the API and validate with Zod/Pydantic. Modern OpenAI/Anthropic structured-output modes guarantee valid JSON matching your schema.

Question

What is JSON mode?

Answer

An API mode where the model is guaranteed to produce syntactically valid JSON. Stronger guarantees come from 'structured outputs' (with a schema), where the JSON is also schema-valid. Use schema-constrained outputs for any production parsing — eliminates a whole class of bugs.

Question

Why use a vector DB instead of in-memory search?

Answer

ANN indexes scale to millions or billions of vectors with sub-second retrieval — raw cosine over arrays is O(N) and unusable past a few thousand items. Vector DBs also provide persistence, metadata filtering, multi-tenancy, replication, and operational tooling you'd otherwise build yourself.

Question

How do you chunk a long PDF?

Answer

Parse layout-aware (PyPDF/Unstructured/LlamaParse), split by sections and paragraphs, target ~300-700 tokens with ~50-100 overlap to preserve context across boundaries. Attach metadata (doc id, page, section) for citations and filtering. Good chunking is half the battle of RAG quality.

Question

What is metadata filtering in vector DBs?

Answer

Restricting ANN search to vectors matching metadata predicates — by user, tenant, document type, language, date range. Essential for multi-tenant systems (you don't want User A finding User B's data) and for narrowing very large indexes to a relevant subset before semantic search.

Question

What is retrieval reformulation?

Answer

Rewriting the user query into one or more search queries before retrieving. Techniques: HyDE (have LLM draft a hypothetical answer, embed it, search), multi-query (generate N variations), query expansion (add synonyms). Often improves retrieval recall when user phrasing is short or imprecise.

Question

What is HyDE?

Answer

Hypothetical Document Embeddings: ask the LLM to draft a possible answer to the query, embed that, and use it as the search vector. Counter-intuitive (the draft might be wrong), but it often retrieves better because the draft 'looks like' the documents you're searching, not like the question.

Question

Why might an agent loop infinitely?

Answer

Bad termination conditions (it thinks the goal isn't done), repeated tool failures (it keeps retrying the same broken call), or ambiguous goals. Always cap iterations, detect repeated actions (loop guard), surface unresolvable cases to a human, and add observability so you can see WHERE it's stuck.

Question

What is sandboxing tool calls?

Answer

Running tool effects in an isolated environment — container, restricted credentials, separate VM — so a bad or hijacked tool call can't damage production systems. Especially critical for tools that execute code, send emails, or modify databases. Combine with strict input validation.

Question

Least privilege for agents?

Answer

Give the agent only the tools and permissions necessary for its job, scoped to the smallest blast radius. A read-only assistant doesn't need write access; a customer-support agent doesn't need admin APIs. Reduces damage when the agent goes wrong or is hijacked via prompt injection.

Question

What is human-in-the-loop?

Answer

Inserting human review/approval before risky agent actions (sending email, making payment, committing code). Patterns: confirm-before-execute on certain tools, batch review of decisions, or full handoff when confidence is low. Required by regulation in many domains; usually a good default for agents touching the real world.

Question

What is RAG with citations?

Answer

Generating answers that include explicit references to the retrieved sources used. Makes hallucinations checkable (the user can verify), builds trust, and is required in domains like legal/medical. Best practice: have the model emit a citation per claim, then validate the cited chunks were actually retrieved.

Question

What is contextual compression?

Answer

Filtering or summarizing retrieved chunks against the user's query before sending to the LLM, so only the most relevant sentences make it into the context window. Saves tokens, sharpens focus, and helps when chunks are long and only partially relevant.

Question

What is parent-document retrieval?

Answer

Embed small chunks for precise search, but return their larger parent doc or section as context to the LLM. Best of both worlds: precise semantic match plus rich surrounding context. Implemented in LangChain and LlamaIndex as a standard pattern.

Question

Why is exact-match retrieval still useful?

Answer

Names, IDs, code symbols, error messages, and acronyms need lexical match — embeddings can fuzz them or miss them entirely. Hybrid search (BM25 + vector) gives you both. Don't ditch keyword search just because vectors are cool — they're complementary.

Question

What's the trade-off in a vector index?

Answer

Recall vs latency vs memory. HNSW: high recall, fast queries, lots of RAM. IVF: less RAM, slightly lower recall, slower. Tune parameters like ef_search (HNSW) or nprobe (IVF) per workload. For most apps the defaults are fine; tuning matters at billion-vector scale.

Question

How do you keep an LLM cheap in production?

Answer

Aggressive prompt caching, smaller models for simple tasks (router pattern), prompt compression (trim history, summarize), batch APIs for non-urgent work, structured outputs to avoid retries, hard token caps on input and output, and instrument every call so you know where the money goes.

Question

What is model routing?

Answer

Sending easy queries to cheap small models (Haiku, GPT-4o-mini) and only escalating hard ones to the big expensive models. Decide via simple heuristics (query length, classification model, or confidence checks). Can cut costs 5-10x for typical chat workloads with minimal quality loss.

Question

What is speculative decoding?

Answer

A small fast 'draft' model proposes the next several tokens; a larger 'verifier' model checks them all in parallel and accepts the matches. Cuts inference latency significantly because the verifier rarely needs to redo work. Used to speed up large models without quality loss.

Question

What is a knowledge graph in AI?

Answer

A structured store of entities and their relationships (Alice WORKS_AT Acme; Acme HQ_IN Paris). Pairs with vector search for grounded, multi-hop reasoning. Useful for queries that need precise traversal, not just semantic similarity. GraphRAG combines both.

Question

What is a guardrails library?

Answer

Frameworks (Guardrails AI, NeMo Guardrails, OpenAI Moderation, Anthropic Constitutional AI hooks) that wrap LLM calls with input/output validation rules — content moderation, schema checks, fact-checking, jailbreak detection. Centralizes safety logic instead of spreading it through every prompt.

Question

What is a jailbreak?

Answer

A crafted prompt that bypasses the model's safety alignment, getting it to do things it would normally refuse. Defenses layer: input filter, robust system prompt, output filter, and ultimately tool-level access controls. Don't rely on the model alone — it can be talked into things.

Question

What is an agent's observation step?

Answer

Reading a tool's result back into the conversation so the LLM can reason about what to do next. The 'O' in ReAct (Reason-Act-Observe). The format and clarity of observations strongly affects the agent's ability to use the result well — short structured output beats verbose dumps.

Question

What is reflection in an agent?

Answer

An extra LLM step where the agent critiques its own plan or output and revises before finalizing. Improves quality on hard reasoning tasks at the cost of more LLM calls and latency. A simple form: 'Now check your answer for errors and correct them.'

Question

When should you NOT use an agent?

Answer

When a deterministic pipeline with one or two LLM calls would work. Agents add latency, cost, complexity, and failure modes — they're appropriate when the steps genuinely vary by input. Most product features don't need a full agent loop; they need a well-crafted chain.

Question

Trade-off of long context windows?

Answer

Cost and latency scale with context length. The 'lost in the middle' problem — models often ignore content in the middle of very long contexts. Retrieval still beats stuffing 1M tokens for most tasks. Use long context for genuinely cross-document reasoning, not as a substitute for good chunking.

Question

Why does prompt caching help so much?

Answer

Static prompt prefixes (system prompts, big examples, large documents) are computed once and reused across calls. With caching enabled, those tokens are charged at a fraction of the normal rate (Anthropic) or for free (some OpenAI tiers). Dramatic cost and latency savings on repeated calls.

Question

What is grounded answering?

Answer

Constraining the LLM to answer only from retrieved context, refusing if the answer isn't supported. Hugely reduces hallucinations for factual queries. Implementation: prompt instruction + post-check that key claims appear in the retrieved chunks.

Question

What is an evaluation harness?

Answer

A repeatable test rig: dataset of inputs (and either expected outputs or grading rubrics), a runner that calls your LLM pipeline, scoring (metrics or LLM-as-judge), and a dashboard. Your LLM CI. Without it, you have no way to know if a prompt change made things better or worse.

Question

What is a regression suite for prompts?

Answer

Stored examples that must keep passing as you change prompts or models. New variants are evaluated against the suite before being promoted. Prevents quality drift, especially when many prompts power one product and a change in one might subtly affect another.

Question

How do you handle PII in LLM apps?

Answer

Detect and redact (Presidio, regex, or LLM-based) before sending to the model, route through compliant regions, log carefully (no PII in raw form), and honor deletion requests. Document what you store and for how long. PII handling can be the difference between a usable enterprise product and a non-starter.

Question

What is token-by-token streaming?

Answer

The server emits each generated token as an SSE or WebSocket message so the client renders it as it arrives — the classic 'typewriter' effect. Improves perceived latency and lets users see progress on long outputs. The expected UX for any chat-style interface today.

Question

What is RLAIF?

Answer

Reinforcement Learning from AI Feedback. Uses another model (not humans) to rank pairs of outputs and produce the reward signal — scales feedback collection cheaply. Quality depends on the judge model's calibration. Used in Anthropic's Constitutional AI approach.

Question

Fine-tune vs RAG vs prompt — which when?

Answer

Prompt: cheapest, fastest to iterate — start here. RAG: when you need dynamic, current, or private knowledge. Fine-tune: when you need consistent behavior/style or you want to compress prompts/cost at very high scale. Most real systems combine all three.

Question

What is an embedding cache?

Answer

Caching the embedding for each unique input string (key = hash of input) so identical inputs don't get re-embedded. Saves cost and latency for repeated queries and re-indexed documents. Easy to add and almost always worth it.

Question

Why does a tool's description matter?

Answer

It's what the LLM sees to decide whether and how to call the tool. Clarity, parameter types, edge cases, and examples all dramatically affect tool-use accuracy. Spend time on tool descriptions — they're prompt engineering for the agent's decision-making.

Question

Fine-tuning vs in-context learning?

Answer

Fine-tuning permanently updates weights via training on examples — slow to iterate, fast at inference, no per-prompt token cost. In-context learning teaches via examples in the prompt — fast to iterate, costs tokens every call, doesn't change the model. Start with in-context; fine-tune when scale or behavior requires it.

Practise AI & Agentic AI in the app
Track your progress, flag tricky cards and write your own answers.

Open in the app

More topics: React & Frontend JavaScript & TypeScript Backend Engineering Databases System Design DevOps & Cloud Security Testing DSA Coding Problems (Python)