Skip to main content

08. Programming & Technologies

Embeddings, RAG and Semantic Search Basics

Embeddings turn text into vectors so similar meanings sit nearby; semantic search finds nearest chunks by meaning; RAG (Retrieval-Augmented Generation) retrieves those chunks and feeds them to an LLM so agents answer from your data β€” with chunking, hybrid search, citations, and retrieval evals deciding quality.

What you will learn

  • Define embeddings, semantic search, and RAG in plain language
  • Sketch the offline ingest and online retrieve-generate paths
  • Choose chunking and hybrid-search tactics that help agents
  • List failure modes and how to eval retrieval separately
  • Answer interview questions with short, solid answers
Embeddings semantic search and RAG pillars
Interview staple: embed β†’ retrieve by meaning β†’ generate with evidence.

Definition

An embedding is a numeric vector that represents text (or other media) so items with similar meaning have high similarity (cosine, dot product, etc.). Semantic search queries that space instead of only matching keywords. RAG uses retrieval (often semantic, often hybrid) to pull evidence into the prompt before generation β€” cutting hallucinations when the answer lives in your corpus.

For agents, RAG is usually a tool or a fixed first step: search_docs β†’ reason β†’ maybe more tools β†’ answer with citations.

Introduction

This lesson (#7 in Programming & Technologies) follows Vector Databases. You know where vectors live; now master the ideas: embeddings, search, chunking, and the RAG loop agents depend on.

Next: Cloud Platforms for Agentic AI (AWS, Azure, GCP).

Why this matters for agents

  • Agents cannot memorize your private docs in weights
  • Tool-using agents need a reliable knowledge lookup
  • Bad retrieval makes β€œsmart” agents confidently wrong
  • Chunking and metadata decide what the model ever sees
  • Evals on retrieval catch issues before UX blame hits the LLM

Embeddings

  • Model maps text β†’ fixed-size vector
  • Same model (and version) for index and query time
  • Similarity metrics: cosine / dot product (know which your store uses)
  • Multilingual and domain models exist β€” match your corpus
  • Re-embed the corpus when you change embedding models
  • Do not embed secrets you would not put in a prompt

Semantic search

  • Embed the query; find top-k nearest stored vectors
  • Returns similar meaning even when wording differs
  • Weak on exact IDs, SKUs, error codes β€” pair with keywords
  • Always apply metadata filters (tenant, ACL, doc type)
  • Approximate nearest neighbor (ANN) trades tiny recall for speed

RAG pipeline

Split offline preparation from the online agent path.

Docs chunk embed index then online retrieve generate
Agent frameworks wrap this; you still own chunk quality and filters.
  • Offline: ingest β†’ clean β†’ chunk β†’ embed β†’ upsert to vector store
  • Online: embed query β†’ retrieve β†’ optional re-rank β†’ prompt β†’ generate
  • Return citations (doc id, section) with the answer
  • Cap tokens of retrieved text injected into context
  • Refuse or ask clarifying questions when retrieval is weak

Chunking and hybrid search

Retrieval quality is usually a data problem before it is a model problem.

Overlapping chunks and hybrid vector plus keyword search
Overlap preserves boundary sentences; hybrid catches exact tokens vectors miss.
  • Chunk by structure (headings) when possible, not only fixed chars
  • Use overlap so ideas split across boundaries still retrieve
  • Store metadata: source, title, tenant, updated_at
  • Hybrid: vector + BM25/keyword, then merge or re-rank
  • Parent-document / small-to-big patterns help when chunks are tiny

RAG for agents (patterns)

  • Fixed RAG: always retrieve before answer
  • Tool RAG: model calls search_docs when needed
  • Multi-hop: retrieve β†’ read β†’ new query β†’ retrieve again
  • Agentic RAG: plan queries, critique evidence, loop with budgets
  • Memory RAG: embed past summaries for personalization

Evaluation

  • Retrieval: was the gold doc in top-k? (hit rate / recall@k)
  • Generation: faithfulness to retrieved evidence (groundedness)
  • End-to-end: answer correctness on a labeled question set
  • Change one variable at a time (chunk size vs model vs top-k)
  • Log query, retrieved ids, and user feedback for offline review

Map to earlier modules

  • Vector DB lesson = where embeddings are stored/searched
  • SQL lesson = source of truth and ACL ids in metadata
  • HTTP tools often fetch the full doc after a chunk hit
  • Providers supply embedding + chat models β€” pin both
  • Module 09 will go deeper on advanced RAG / multimodal

Failure modes

  • Mismatched embedding models between index and query
  • Chunks too big (noise) or too small (no context)
  • No hybrid search β†’ miss exact ticket/SKU queries
  • Stuffing irrelevant top-k into the prompt
  • Blind trust in generation without citations or refusal

Program / implementation notes

Build a tiny corpus: chunk with overlap, embed, index, and a search_docs tool that returns cited snippets under a character budget. Measure recall@5 before tuning the LLM prompt.

  • Pin embedding model id next to index name in config
  • Next: Cloud Platforms for Agentic AI (AWS, Azure, GCP)

Advantages and limitations

  • Advantage: grounds agents in private, fresh knowledge
  • Advantage: cheaper/safer than fine-tuning for many doc Q&A cases
  • Advantage: semantic search handles paraphrase-heavy user questions
  • Limitation: garbage corpus or chunks β†’ garbage answers
  • Limitation: pure vectors miss exact identifiers without hybrid
  • Limitation: retrieval latency and cost add to every agent turn

Key points

  • Embeddings map text to vectors for meaning similarity.
  • Semantic search = nearest neighbors in embedding space.
  • RAG retrieves evidence then generates grounded answers.
  • Chunking, metadata, and hybrid search drive quality.
  • Same embedding model at index and query time.
  • Eval retrieval separately from generation.

FAQs

RAG vs fine-tuning?

RAG pulls fresh documents into context without retraining. Fine-tuning changes model behavior/style. Use RAG for knowledge; fine-tune for skills or tone when needed.

Semantic vs keyword search?

Semantic matches meaning; keyword matches exact tokens. Production agents often use both (hybrid) then re-rank.

How big should chunks be?

Start with structure-aware chunks (e.g. 200–800 tokens) with overlap, then tune using retrieval hit rate on your eval set β€” not vibes.

Is RAG only for Q&A bots?

No. Agents use it for policies, code search, ticket history, and long-term memory β€” any grounded lookup before acting.

Interview questions

  1. What is an embedding?

    Answer A numeric vector representation of text (or other data) such that similar meanings are close under a similarity metric like cosine.

  2. What is RAG?

    Answer Retrieval-Augmented Generation: retrieve relevant evidence (often via embeddings), insert it into the prompt, then generate an answer grounded in that evidence.

  3. Why hybrid search?

    Answer Vectors miss exact IDs and rare tokens; keywords miss paraphrases. Combining both improves recall for real user questions.

  4. What is chunking and why overlap?

    Answer Splitting documents into retrievable pieces; overlap keeps sentences that straddle boundaries from being lost between chunks.

  5. How do you evaluate RAG?

    Answer Measure retrieval hit rate/recall@k on labeled questions, then groundedness/correctness of answers β€” change one pipeline knob at a time.

  6. How does this connect to agents?

    Answer Agents call retrieval as a tool or first step, then reason and act; budgets and citations keep RAG from becoming unbounded context stuffing.

Related topics

Practice task

Complete each numbered practice step in a notebook or doc before opening the next lesson.

  1. Define embeddings, semantic search, and RAG in one sentence each.
  2. Design chunking rules for a 50-page policy PDF (size, overlap, metadata).
  3. List when you would use hybrid search for a support agent (3 examples).
  4. Write 5 eval questions and the gold doc section each must retrieve.
  5. Answer interview questions 1, 2, and 5 in two sentences each.