Home 01 · Vector DB 02 · LLM Frameworks 03 · AI Systems 04 · Prompt & Tuning 05 · AI Testing 06 · AI Architect 07 · AI Integration

The stack, top to bottom

These five terms describe different layers of the same system, not five separate technologies. A useful mental model: pipeline design is the architecture blueprint, orchestration is the engine that runs each step, RAG is one pattern that engine uses to ground answers in real data, MCP is the standard way that engine connects to outside tools and data sources, and agentic workflows describe what happens when the engine itself starts making decisions instead of following a fixed path.

ConceptWhat it answers
AI Pipeline DesignWhat are the stages, data flows, and failure points of the whole system?
LLM OrchestrationHow do we sequence/coordinate multiple LLM calls, tools, and steps reliably?
RAGHow do we ground LLM answers in real, current, private data instead of relying on parametric memory?
MCPHow does a model connect to external tools and data sources in a standardized way?
Agentic WorkflowsWhen should the model itself decide what happens next, instead of a fixed sequence?
RAG
grounding pattern, not a framework
MCP
open protocol for tool/data connections
Orchestration
the control layer coordinating steps
Agentic
dynamic, model-driven control flow

Retrieval-Augmented Generation (RAG)

RAG grounds an LLM's response in retrieved external data rather than relying solely on what the model memorized during training. At query time: embed the query, retrieve the most relevant chunks from a vector store (or hybrid search), insert them into the prompt as context, then generate an answer constrained to that context.

User query
Embed query
Retrieve top-K chunks
Build prompt + context
LLM generates
Answer (+ citations)

What you can actually build

Advantages
  • Reduces hallucination by grounding answers in retrieved evidence
  • Updates instantly by re-indexing data — no fine-tuning or retraining needed
  • Supports citation/attribution back to source documents
  • Keeps proprietary data out of model weights — relevant for HIPAA/PII contexts
Disadvantages
  • Retrieval quality is a hard ceiling — bad retrieval guarantees a bad answer regardless of model quality
  • Chunking strategy is non-trivial; poor chunking splits relevant context across boundaries
  • Adds latency (embedding + search) compared to a direct LLM call
  • Still doesn't eliminate hallucination entirely — the model can ignore or misread retrieved context

Beyond naive RAG

Model Context Protocol (MCP)

MCP is an open protocol (introduced by Anthropic) standardizing how LLM applications connect to external tools, data sources, and systems. Instead of every application writing custom, one-off integration code for each tool, MCP defines a common interface: servers expose tools/resources, and any MCP-compatible client (Claude, an IDE, a custom agent) can discover and call them the same way.

What you can actually build

// minimal MCP server tool definition (conceptual)
server.tool("lookup_claim_status", {
  description: "Look up the status of an insurance claim by ID",
  inputSchema: { claimId: "string" },
  handler: async ({ claimId }) => {
    const result = await db.query(
      "SELECT status FROM claims WHERE id = $1", [claimId]
    );
    return result.rows[0];
  }
});
Advantages
  • Standardizes tool/data integration — write once, usable by any MCP-compatible client
  • Decouples tool implementation from the orchestration layer calling it
  • Growing ecosystem means more pre-built connectors instead of custom integration work
  • Clear separation of concerns: the server owns the business logic, the client owns the reasoning
Disadvantages
  • Still an emerging standard — tooling, security patterns, and best practices are actively evolving
  • Adds an architectural layer/process to run and maintain (the MCP server itself)
  • Security surface: a tool server with broad permissions is a real risk if the model is tricked into misusing it (prompt injection via tool results)
  • Not every integration needs the overhead of a full protocol — simple one-off API calls may not justify it

MCP is moving quickly; verify current spec details, security guidance, and ecosystem maturity against docs.claude.com before treating specifics as settled.

LLM Orchestration

Orchestration is the control layer that coordinates everything else: sequencing LLM calls, routing between models, managing memory/state across turns, calling tools, handling retries and fallbacks, and deciding what happens next. LangChain/LangGraph from the prior guide are orchestration frameworks; this section is the underlying concept independent of any specific tool.

What you can actually build

Common orchestration patterns

PatternWhen to use it
Sequential chainFixed, predictable steps with no branching needed
RouterDifferent query types need different handling (e.g. FAQ vs. complex support case)
Parallel fan-out / fan-inMultiple independent retrievals or sub-tasks that can run concurrently, then merge
Evaluator-optimizer loopGenerate, grade the output, regenerate if it fails quality checks
Orchestrator-workerOne model plans/delegates, specialized sub-agents execute each piece
Advantages
  • Makes complex multi-step behavior reliable and observable instead of one giant unmanaged prompt
  • Enables cost control through model routing (cheap model first, escalate selectively)
  • Centralizes error handling, retries, and logging in one layer
Disadvantages
  • Added architectural complexity — more moving parts, more failure points to monitor
  • Over-orchestrating a simple task adds latency and cost without benefit
  • State management across steps is genuinely hard to get right and test

Agentic Workflows

An agentic workflow is one where the model itself decides the next action — which tool to call, whether to retrieve more information, when the task is complete — rather than following a developer-defined fixed sequence. This sits at the dynamic end of a spectrum that starts with a single LLM call and ends with a fully autonomous multi-step agent.

Single call
Fixed chain
Router
Tool-using agent
Multi-agent system

What you can actually build

Advantages
  • Handles open-ended tasks that can't be fully specified as a fixed sequence in advance
  • Adapts to unexpected situations mid-task (a failed tool call, an ambiguous result) without a human rewriting the pipeline
  • Can reduce the number of distinct fixed pipelines you need to maintain for varied task types
Disadvantages
  • Unpredictable cost and latency — the model may take more steps, more tool calls, than expected
  • Harder to test exhaustively; agent paths are not enumerable the way a fixed chain's paths are
  • Higher risk surface — an agent with real tool access can take unintended or harmful actions if it misreads a situation
  • Requires explicit guardrails: max iteration limits, human-in-the-loop checkpoints for high-stakes actions, scoped tool permissions

Production guardrails for agents

AI Pipeline Design

Pipeline design is the architecture-level discipline of deciding how data moves through an AI system end to end: ingestion, processing, storage, retrieval, generation, validation, and monitoring — and where each failure mode is caught. This is the layer where EDI/ETL background transfers most directly.

A typical production RAG pipeline, stage by stage

StageWhat happensCommon failure mode
IngestionPull data from source systems (docs, DBs, APIs)Schema drift, missing/stale source data
ChunkingSplit documents into retrievable unitsSplitting context mid-meaning, inconsistent chunk size
EmbeddingConvert chunks to vectorsModel version mismatch between index and query time
Indexing/storageStore vectors + metadata (pgvector/Pinecone)Stale index after source data updates
RetrievalFetch relevant chunks for a queryLow recall, irrelevant matches, missing filters
OrchestrationCoordinate steps, tools, routingUnhandled errors, runaway agent loops
GenerationLLM produces the answerHallucination, ignoring provided context
ValidationCheck output before returning to userNo validation at all — output ships unchecked
MonitoringTrack quality, cost, latency over timeSilent quality drift with no alerting
Why this discipline matters
  • Most production AI failures are pipeline/data problems, not model problems
  • Treating each stage as testable and observable (an ETL mindset) catches issues before they reach users
  • Clear stage boundaries make it possible to swap components (e.g. pgvector → Pinecone) without rebuilding the whole system
Common design mistakes
  • No evaluation set — shipping changes with no way to measure if quality improved or regressed
  • Treating the LLM call as the whole system instead of one stage among many
  • No monitoring for data staleness, embedding drift, or cost spikes
  • Over-engineering with agents/orchestration where a simple fixed pipeline would do

Chunking Strategies

Chunking is how you split source documents into retrievable units before embedding. It is the single highest-leverage decision in most RAG systems — the right chunk size and strategy can double retrieval quality; the wrong one silently cripples it. Most RAG failures trace back here, not to the model or the prompt.

Chunking strategies compared

StrategyHow it worksBest forRisk
Fixed-size (characters)Split every N characters with M overlapSimple documents, quick prototypingCuts mid-sentence, destroys semantic units
Recursive text splitterSplit on paragraph → sentence → word boundaries in orderGeneral prose — the LangChain defaultStill ignores document structure
Sentence-windowIndex individual sentences; retrieve surrounding window for contextDense factual documents where precision mattersWindow may still miss cross-paragraph context
Semantic chunkingEmbed sentences; split when cosine similarity drops below thresholdDocuments with clear topic shiftsSlow at ingestion; inconsistent chunk sizes
Document-structure awareSplit on headings, sections, HTML/Markdown elementsStructured docs: policies, manuals, API docsRequires clean, consistently structured source
Hierarchical / parent-childIndex small child chunks; retrieve parent for LLM contextBest of precision + context — production standardMore complex indexing pipeline

The parent-child (hierarchical) pattern

Index small chunks (128–256 tokens) for high-precision retrieval. When a small chunk matches, return its parent chunk (512–1024 tokens) to the LLM for richer context. This separates the precision of retrieval from the context richness of generation.

from llama_index.core.node_parser import HierarchicalNodeParser
from llama_index.core.retrievers import AutoMergingRetriever

# Build hierarchy: 2048 → 512 → 128 token chunks
parser = HierarchicalNodeParser.from_defaults(
    chunk_sizes=[2048, 512, 128]
)
nodes = parser.get_nodes_from_documents(documents)

# Retriever: match on small chunks, return parent for context
base_retriever = index.as_retriever(similarity_top_k=12)
retriever = AutoMergingRetriever(base_retriever, storage_context)

Chunk size guidelines

128–256
tokens — high precision retrieval chunk
512–1024
tokens — context window chunk for LLM
10–20%
overlap recommended between adjacent chunks
~1/4
of context window — max chunk to LLM ratio
What Makes a Good Chunk
  • Contains one complete semantic unit — a concept, a procedure, a policy rule
  • Does not cut across a sentence or paragraph boundary
  • Has enough context that it is interpretable without surrounding chunks
  • Includes structural metadata: document title, section heading, page number
Chunking Failure Modes
  • Splitting a table across chunk boundaries — the model gets half a table with no headers
  • Chunks too small — each chunk lacks enough context to be useful even if retrieved
  • Chunks too large — retrieval precision drops; relevant sentence buried in noise
  • No overlap — the answer sits exactly at a chunk boundary and gets split

Multi-Agent Systems

A multi-agent system uses multiple LLM-powered agents working together — one orchestrating, others specialising — to complete tasks too complex or broad for a single agent. Each sub-agent has a focused role, its own tools, and communicates results back to the orchestrator. The architecture trades simplicity for capability.

Core multi-agent patterns

PatternStructureBest for
Orchestrator-WorkerOne planning agent delegates tasks to specialised worker agentsComplex workflows with distinct sub-tasks (research, write, review)
SupervisorA supervisor agent routes each query to the most appropriate sub-agentCustomer support with different agents per topic domain
Sequential PipelineAgents pass output to the next agent in a chainDocument processing: extract → analyse → summarise → format
Parallel Fan-outMultiple agents run simultaneously on sub-tasks; results mergedResearch: different agents search different sources concurrently
Debate / ReflectionMultiple agents critique each other's outputs before finalisingHigh-stakes content requiring self-correction and accuracy

Supervisor agent in LangGraph

from langgraph.graph import StateGraph, END
from typing import Literal

AGENTS = ["claims_agent", "policy_agent", "billing_agent"]

def supervisor(state):
    """Route to the right specialist agent based on query."""
    prompt = f"Route this query to one of {AGENTS}: {state['query']}"
    route = llm.invoke(prompt).content.strip()
    return {"next_agent": route}

def should_continue(state) -> Literal["claims_agent","policy_agent","billing_agent","END"]:
    return state.get("next_agent", "END")

graph = StateGraph(dict)
graph.add_node("supervisor", supervisor)
graph.add_node("claims_agent", claims_agent_fn)
graph.add_node("policy_agent", policy_agent_fn)
graph.add_node("billing_agent", billing_agent_fn)

graph.add_conditional_edges("supervisor", should_continue)
[graph.add_edge(a, "supervisor") for a in AGENTS]  # loop back
graph.set_entry_point("supervisor")
app = graph.compile()

Communication patterns between agents

Shared state (LangGraph)

All agents read and write to a common typed state object. Simple, consistent, easy to debug — the LangGraph default.

  • Entire conversation history visible to all agents
  • State changes are auditable in the graph trace
  • Risk: large state objects bloat the context window
Message passing

Agents communicate via structured messages. Keeps each agent's context lean — only sees messages relevant to it.

  • Scales better to many agents
  • Explicit contracts between agents
  • Risk: more complex routing and serialisation logic

Production guardrails for multi-agent systems

  • Hard step limits per agent — each agent should have a max iteration budget; the orchestrator should timeout an agent that exceeds it
  • Least-privilege tools — the billing agent should not have write access to patient records; scope tools to each agent's role
  • Human-in-the-loop gates — for irreversible or high-value actions, pause and require human approval before the agent proceeds
  • Full trace logging — every agent decision, tool call, and message must be logged with agent identity and timestamp for auditability
  • Failure propagation handling — define what happens when a worker agent fails: retry, fallback, escalate to human, or graceful degradation

AI System Deployment Patterns

Deploying an AI system is not the same as deploying a standard API. The system has non-deterministic outputs, external model dependencies, retrieval pipelines that can go stale, and quality metrics that degrade silently over time. Each of these requires specific production patterns beyond what a standard deployment checklist covers.

Deployment architecture options

ArchitectureDescriptionBest for
Synchronous APIRequest → process → respond in one call. Standard REST or gRPC endpoint.Simple Q&A, classification, extraction with <10s latency budget
Streaming APIToken-by-token streaming response using SSE or WebSocketChat interfaces where perceived latency matters more than completion time
Async / Queue-basedJob submitted to queue; result polled or pushed via webhookLong-running agents, document processing pipelines, batch jobs
Batch processingBulk inputs processed off-peak; results stored for retrievalNightly document ingestion, re-indexing, bulk embedding jobs

CI/CD for AI systems

# Example GitHub Actions gate for a RAG pipeline change
# Runs on every PR that touches prompts, retrieval, or chain logic

name: RAG Quality Gate
on: [pull_request]
jobs:
  eval:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Run retrieval eval
        run: python eval/run_ragas.py --min-faithfulness 0.80
                                      --min-context-recall 0.75
      - name: Run DeepEval suite
        run: deepeval test run tests/test_chain.py
      - name: Check for prompt regressions
        run: promptfoo eval --config promptfoo.yaml --ci

Canary and shadow deployment

Canary rollout

Route a small percentage (5–10%) of production traffic to the new model or prompt version. Compare quality metrics between canary and baseline before full rollout.

  • Catches regressions on real traffic before full exposure
  • Requires metric collection and comparison infrastructure
  • A/B test framework or feature flag system needed
Shadow index for RAG

When upgrading an embedding model or re-chunking, build the new index in parallel. Run evaluation against the shadow index. Swap only after quality is confirmed.

  • Zero-downtime index upgrades
  • Evaluation-gated cutover — no guessing
  • Requires 2x storage during transition window

Production monitoring checklist

What to monitorMetricAlert threshold
Answer qualitySampled faithfulness + relevancy (Ragas)Drop >5% from baseline
Retrieval qualityContext recall@5 on eval setDrop below 0.75
Latency p95End-to-end response timeExceeds SLA (e.g. >5s)
Token costInput + output tokens per requestSpike >20% week-over-week
Error rateRate of failed or timed-out requests>1% of requests
Embedding driftQuery distribution vs index distribution (Evidently AI)Significant distribution shift detected
The most common production mistake: treating AI system deployment as identical to a standard API deployment. The difference is that quality degrades gradually and silently — you need continuous quality monitoring, not just uptime monitoring.

Production-Level Interview Q&A

Click a question to expand the answer.

How do RAG, MCP, and agentic workflows relate to each other in one system?
RAG is a grounding pattern — it answers 'how does the model get accurate, current data.' MCP is a connection standard — it answers 'how does the model reach that data and other tools in a uniform way.' Agentic workflow is a control-flow style — it answers 'who decides what happens next.' A system can use RAG without being agentic (a fixed retrieve-then-generate chain), and can be agentic without RAG (a pure tool-calling agent with no document retrieval). They're independent dimensions that often combine: an agent that dynamically decides when to retrieve, using MCP-exposed tools to do so.
When would a fixed pipeline be the better choice over an agentic workflow, even though agents are more flexible?
When the task is well-defined, predictable, and doesn't benefit from dynamic decision-making — most production RAG Q&A, classification, and extraction tasks fall here. A fixed pipeline is cheaper, faster, fully testable (every path is enumerable), and has a much smaller risk surface than an agent with tool access. The decision should be driven by whether the task genuinely requires the model to decide its own next steps, not by which approach is more interesting to build.
Walk through how you'd debug a RAG system that's hallucinating despite having relevant documents in the index.
First isolate which stage is at fault: confirm the retrieval step is actually surfacing the relevant chunks for that query (log and inspect retrieved context directly, don't assume). If retrieval is correct but the answer still hallucinates, the issue is in generation — check whether the prompt clearly instructs the model to answer only from provided context, whether the context window is being truncated, or whether the chunk is too fragmented to be useful even though it's topically relevant. This mirrors root-cause isolation in ETL debugging: check each transform stage independently rather than assuming the failure is where the symptom appears.
What guardrails would you put on an agentic workflow before letting it run against production systems?
Hard limits on iteration count to prevent runaway loops, least-privilege scoped tool permissions so the agent can't take actions beyond what the task requires, human-in-the-loop approval gates before irreversible or high-stakes actions (sending external communications, executing financial transactions, modifying records), full audit logging of every tool call and decision, and cost/latency monitoring with alerting since agent runs have unpredictable resource use compared to fixed pipelines.
How does MCP change the integration story compared to writing custom API wrappers for each tool?
Without MCP, each new tool or data source typically means custom integration code specific to that LLM framework and that tool's API. MCP standardizes the interface: a tool exposed once as an MCP server can be used by any MCP-compatible client without rewriting integration logic per consumer. This reduces duplicated integration work across applications, though it does add the overhead of running and securing the MCP server itself, and the ecosystem is still maturing — worth verifying current adoption and tooling against docs.claude.com rather than treating it as fully settled.
How would you design an evaluation strategy for a multi-stage AI pipeline, not just the final output?
Evaluate each stage independently rather than only judging the final answer: retrieval quality via precision@K/recall@K against a labeled set, generation quality via answer relevance and faithfulness to retrieved context (tools like Ragas or DeepEval), and orchestration/agent behavior via scenario tests checking the right path was taken and termination conditions fired correctly. Stage-level evaluation lets you pinpoint exactly where a regression originated instead of only knowing the final output got worse — the same logic as validating each transform in an ETL pipeline rather than only checking the final load.
What's the difference between orchestration and agentic behavior, and why do interviewers conflate them?
Orchestration is the coordination layer itself — it can run a purely fixed sequence with zero dynamic decision-making. Agentic behavior is a property of how that orchestration layer is used — letting the model decide the next step rather than hardcoding it. They get conflated because the same frameworks (LangGraph, for instance) are used for both fixed and agentic flows; the distinguishing factor is whether control-flow decisions are hardcoded by the developer or made dynamically by the model at runtime.
How would you control cost and latency in a system that combines RAG with an agentic loop?
Cap retrieval and tool-call iterations explicitly rather than letting the agent loop indefinitely; use a cheaper/faster model for intermediate reasoning steps and reserve the strongest model for final generation; cache embeddings and frequent queries; and add a router that short-circuits to a fixed, cheap path for simple queries instead of always invoking the full agentic loop. Monitoring actual cost and latency per request in production, not just at design time, is necessary because agent behavior is inherently variable run to run.
From a pipeline-design view, what's the single highest-leverage thing to get right early in a RAG project?
Chunking and data quality at ingestion — far more production RAG failures trace back to bad chunking, stale data, or poor source document structure than to model choice or prompt engineering. Getting the ingestion and chunking strategy right (and building an evaluation set early to measure retrieval quality objectively) pays off more than tuning the generation prompt, which is usually where teams over-invest first.