โ† Back to Blog
RAGAgentsAI Engineering

Agentic Search vs Embedding RAG for Code: Why Coding Agents Grep Instead of Embed

Claude Code-style agents explore repositories with grep, glob and file reads instead of vector indexes. Here is when agentic search beats embedding RAG, when it loses, and how to build and evaluate both.

By Joinloopยท22 November 2026ยท8 min read
ShareLinkedInXReddit
๐Ÿ”Ž

You wire up a code assistant the standard way: chunk the repo, embed every chunk, store vectors, retrieve top-k for each question. It works on demos. On your real monorepo it returns three near-identical test files, misses the function that actually defines the behaviour, and has no idea that the index is two days stale.

Meanwhile, the popular coding agents mostly skip the vector index. They run grep, glob, and file reads in a loop, and decide what to look at next based on what they just saw. Recent surveys of repository-level retrieval describe exactly this shift: from passive similarity matching to active exploration with tools. This post explains why that works for code, where it breaks, and how to choose.

Why embeddings struggle on code

Embedding retrieval assumes the answer is a chunk of text that is semantically similar to the question. Code questions often are not like that.

  • Identifiers beat semantics. "Where is retry_budget used?" is an exact-match problem. A dense model may return conceptually related retry code that never mentions the symbol.
  • Answers span files. To understand a bug you follow call chains: handler โ†’ service โ†’ repository โ†’ query. Top-k similarity returns neighbours, not a path.
  • Chunking destroys structure. A 512-token window cuts through a class, separates a decorator from its function, and drops imports.
  • Freshness. Code changes every commit. Every stale vector is a confident wrong answer. Grep reads the working tree, so it is never stale.
  • Operational weight. An index needs build jobs, storage, access control, and re-embedding on model upgrades.

None of this means embeddings are useless for code. It means similarity is the wrong primary tool when the query contains exact symbols and the answer requires multi-hop navigation.

What agentic search actually is

Agentic search replaces the fixed pipeline (query โ†’ retrieve โ†’ generate) with a loop:

  1. The model proposes a search (a regex, a glob, a file to open).
  2. A tool executes it and returns a bounded result.
  3. The model reads the result, decides if it has enough, and either answers or searches again.

The "retriever" is the model's own judgement plus cheap, exact tools. Cost moves from index building to extra LLM turns at query time.

A minimal agentic code searcher

This is a runnable sketch using the Anthropic Python SDK with two tools. Set ANTHROPIC_API_KEY and check the official docs for current model IDs and parameters before using it in production.

import subprocess, pathlib, anthropic

ROOT = pathlib.Path(".").resolve()
client = anthropic.Anthropic()
MODEL = "claude-sonnet-5-5"  # verify the current model ID in the docs
MAX_OUT = 4000  # hard cap on tool output so context stays small

def grep(pattern: str, glob: str = "*") -> str:
    out = subprocess.run(
        ["rg", "-n", "--max-count", "5", "-g", glob, pattern, str(ROOT)],
        capture_output=True, text=True, timeout=15,
    ).stdout
    return out[:MAX_OUT] or "no matches"

def read_file(path: str, start: int = 1, end: int = 120) -> str:
    p = (ROOT / path).resolve()
    if ROOT not in p.parents:          # block path traversal
        return "path outside repo"
    lines = p.read_text(errors="ignore").splitlines()[start - 1:end]
    return "\n".join(f"{start + i}: {l}" for i, l in enumerate(lines))[:MAX_OUT]

TOOLS = [
    {"name": "grep", "description": "Regex search (ripgrep) over the repo. Returns file:line matches.",
     "input_schema": {"type": "object", "properties": {
         "pattern": {"type": "string"}, "glob": {"type": "string"}},
         "required": ["pattern"]}},
    {"name": "read_file", "description": "Read a line range of a file.",
     "input_schema": {"type": "object", "properties": {
         "path": {"type": "string"}, "start": {"type": "integer"}, "end": {"type": "integer"}},
         "required": ["path"]}},
]
IMPL = {"grep": grep, "read_file": read_file}

def ask(question: str, max_turns: int = 8) -> str:
    messages = [{"role": "user", "content": question}]
    for _ in range(max_turns):                       # budget: never loop forever
        resp = client.messages.create(
            model=MODEL, max_tokens=1024, tools=TOOLS, messages=messages,
            system="Answer questions about this repo. Search before answering. Cite file:line.",
        )
        messages.append({"role": "assistant", "content": resp.content})
        if resp.stop_reason != "tool_use":
            return "".join(b.text for b in resp.content if b.type == "text")
        results = []
        for b in resp.content:
            if b.type == "tool_use":
                results.append({"type": "tool_result", "tool_use_id": b.id,
                                "content": IMPL[b.name](**b.input)})
        messages.append({"role": "user", "content": results})
    return "Stopped: turn budget exhausted."

print(ask("Where is the retry budget enforced, and what happens when it runs out?"))

Three details matter more than the model choice: the output cap on every tool, the path check, and the turn budget. Without them an agent can flood its own context or loop.

The hybrid: give the agent a semantic tool too

You do not have to choose. Expose a semantic_search tool next to grep and let the agent pick. Exact symbol? Grep. "Where do we handle rate limiting for uploads?" with unknown vocabulary? Semantic search to find the neighbourhood, then grep and read to confirm.

def semantic_search(query: str, k: int = 5) -> str:
    # your vector store of function-level chunks (AST-aware), returns path:line + signature only
    hits = index.search(query, k=k)
    return "\n".join(f"{h.path}:{h.start_line} {h.signature}" for h in hits)

Return short pointers (path, line, signature), not full chunks. The agent then reads only what it needs.

Comparison

Dimension Embedding RAG Agentic search (grep/read) Hybrid
Exact symbol lookup Weak Strong Strong
Vague conceptual query Strong Moderate (depends on guessing keywords) Strong
Multi-hop (call chains) Weak Strong Strong
Freshness Needs reindexing Always current Mixed
Latency per query Low (one retrieval) Higher (several LLM turns) Medium
Cost per query Low Higher tokens Medium
Setup and ops Index pipeline, storage Almost none Index pipeline
Predictability / debugging Deterministic retrieval Path varies run to run Mixed
Access control Must replicate in index Inherits filesystem permissions Mixed

General comparisons of agentic and classic RAG agree on the shape of this tradeoff: agentic approaches handle multi-hop questions better but cost more and are harder to debug, while classic RAG stays practical for simple lookups. A 2026 arXiv paper, Is Agentic RAG worth it?, compares the approaches experimentally; read it before generalising from any single benchmark, including ours.

When to pick which

  • Code, docs with stable vocabulary, logs, config: start agentic. Exact tools plus a loop is the cheapest thing that can work.
  • Large unstructured corpora (support tickets, contracts, wikis) with fuzzy wording: embeddings still win. There is no grep for "customers upset about billing".
  • Latency-critical, single-hop Q&A at scale: classic RAG. Five LLM turns per question will hurt your p95 and your bill.
  • Mixed repos (code plus design docs plus tickets): hybrid, with the semantic tool restricted to the prose parts.

How to evaluate it

Do not eyeball. Build 30 to 50 real questions from your team's Slack and PR comments, each with the file and line range that contains the answer. Then measure:

Metric How
Hit rate Did the final answer cite the correct file/line?
Turns and tokens per question From your trace logs
p50 / p95 latency End to end
Stale-answer rate Re-run after a commit that moves the answer

Run both systems on the same set. The decision usually becomes obvious: agentic wins hit rate on symbol and multi-hop questions, embeddings win cost on vague single-hop ones.

Common pitfalls

  1. Unbounded tool output. One grep for import returns 40k tokens and ruins the run. Cap results and cap matches per file.
  2. No turn budget. Agents can circle. Set a max turns and a max tokens, and return a clear failure.
  3. Reading whole files. Prefer line ranges; let the agent ask for more.
  4. Over-trusting the first match. Tell the agent in the system prompt to confirm by reading the surrounding code before answering.
  5. Ignoring generated and vendored directories. Exclude node_modules, dist, lockfiles and minified bundles, or grep drowns in noise.
  6. Skipping security. Constrain paths to the repo, make tools read-only, and remember that file contents are untrusted input that can contain prompt injection.
  7. Judging by vibes. Agentic runs vary. Evaluate over many questions, and consider repeated runs per question.

Next steps

Take your current retrieval setup and the 30 hardest questions your users asked last month. Run them through the minimal loop above with only grep and read_file, and compare hit rate and cost against what you have. If grep-only already beats your index on the symbol-heavy questions, delete a pipeline. If it loses on the fuzzy ones, add a thin semantic_search tool rather than rebuilding everything.

Choosing the right retrieval architecture, instrumenting it, and proving it with evals is core material in the Joinloop AI Engineering cohort, where we build and measure these systems hands-on.

ShareLinkedInXReddit

Want to build this yourself?

Join a live cohort and go from reading about AI to shipping it, with practitioners who do it daily.