# How we built Search for Agents on dejan.ai without Cloudflare

> Source: <https://dejan.ai/blog/agent-search-diy/>
> Published: 2026-11-27 03:17:34+00:00

**Recommendation:** Ask the classifier whether the previous block completes a semantic unit rather than whether the next block starts one, then merge sub-30-word non-heading chunks and split chunks over 900 words on block boundaries.
More in the playbook "Retrieval and RAG": <https://wpnews.pro/playbooks/rag-retrieval>

# How we built Search for Agents on dejan.ai without Cloudflare

How dejan.ai built a self-hosted /.well-known/search API without Cloudflare: gemini-decision-1 boundary classification, gemini-embedding-2 contextual vectors, and PostgreSQL pgvector hybrid search across 5,718 chunks.

We built a self-hosted [/.well-known/search](https://dejan.ai/.well-known/search?q=how+does+PoolDPP+avoid+near-duplicate+prompts)[/search](https://dejan.ai/search?q=PoolDPP)`dejan.ai` without using Cloudflare AI Search. The pipeline converts each published post, concept, page, and Codebase Explorer element to Markdown, frames semantic chunking as a binary boundary classification task in a single `gemini-decision-1` call (209 to 329 ms per document, 0 output tokens, 100% verbatim text), embeds every chunk with `Title > Section` context using `gemini-embedding-2` (768 Matryoshka dimensions), and stores both a generated PostgreSQL `tsvector` (GIN) and a `pgvector` HNSW index in one table (`search_chunks`). Backfilling all 2,111 live units produced 5,718 chunks with zero failures in 3 minutes 20 seconds.

Figure 1: End-to-end indexing and retrieval pipeline on `dejan.ai`.

## Why we framed semantic chunking as binary classification

Fixed-size chunking (such as Cloudflare's 1,024-token default with 10% overlap) cuts across ideas and tables at arbitrary token counts. Generative LLM chunking (asking a model to echo the document back with `<chunk_start>` tags) solves boundary placement, while paying output-token latency for every word and risking silent text drops or rewrites.

`gemini-decision-1` accepts up to 262,000 input tokens and evaluates up to 1,000 independent yes/no (`noul`) questions over that shared input in one pass, returning calibrated probabilities and zero output tokens. We split each Markdown document into atomic blocks `[B0]` through `[Bn-1]` (headings, paragraphs, lists, tables, fenced code blocks, blockquotes) and ask one calibrated question per adjacent pair.

Because the model never regenerates text, verbatim fidelity is guaranteed by construction. On our 3,150-word [PoolDPP-MAP post](https://dejan.ai/blog/pooldpp-map-diverse-sampling-gemini-embeddings-decision-1/) (75 atomic blocks), one API call scored all 74 candidate transitions in 329 ms (15,657 input tokens, 0 output tokens). On a 759-word prose post with zero HTML headings, it scored all 34 transitions in 209 ms (5,635 input tokens, 0 output tokens).

## The boundary-framing detail that eliminated orphan headings

In our first test, we asked per block whether `[Bi]` started a new semantic chunk rather than continuing `[Bi-1]`. Because both a heading and the opening paragraph beneath it look like the start of new content, Decision 1 scored both above `0.50` on five sections of the 3,150-word test post, producing 5-word orphan heading chunks.

Reframing the question on the transition between adjacent blocks fixed the behaviour with no extra latency:

```
Does block [B{i-1}] mark the end of a complete, self-contained semantic unit
such that block [B{i}] begins a new semantic unit? Answer no if [B{i-1}] is an
incomplete opener (such as a heading or lead-in) or if [B{i}] continues the same
section, argument, table, code example, or list.
```

Figure 2: Measured boundary calibration on post #339 comparing block-start framing against end-of-unit / start-of-new transition framing.

Because a bare heading opens a unit rather than completing one, the highest post-heading cut probability dropped to `0.251`, orphan headings fell from 5 to 0, and chunk count dropped from 20 to 12 (median 190 words). On the heading-free prose post, the same prompt identified every bold Q&A transition and produced 10 clean chunks (27 to 222 words). Two lightweight guardrails sit after classification: chunks under 30 words that do not start with a heading merge into the preceding chunk, and rare chunks over 900 words split on block boundaries.

## Contextual embeddings and the PostgreSQL schema

A passage extracted from the middle of a long post often loses its subject when embedded in isolation. Before calling `gemini-embedding-2` (768 Matryoshka dimensions), we prepend the document title and active section heading (`Title > Section`) to the chunk text, while storing the clean Markdown in `search_chunks` for display and agent retrieval.

All keyword and vector data live in one PostgreSQL table:

```
CREATE TABLE IF NOT EXISTS search_chunks (
    unit_type  text NOT NULL,
    unit_id    text NOT NULL,
    chunk_idx  integer NOT NULL,
    slug       text NOT NULL,
    title      text NOT NULL,
    section    text NOT NULL DEFAULT '',
    url        text NOT NULL,
    markdown   text NOT NULL,
    search_tsv tsvector GENERATED ALWAYS AS (
        setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
        setweight(to_tsvector('english', coalesce(section, '')), 'B') ||
        setweight(to_tsvector('english', coalesce(markdown, '')), 'C')
    ) STORED,
    embedding  vector(768) NOT NULL,
    doc_hash   text NOT NULL,
    tokens     integer NOT NULL DEFAULT 0,
    model      text NOT NULL DEFAULT 'gemini-embedding-2',
    updated_at timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (unit_type, unit_id, chunk_idx)
);
```

Two indexes back the table: a GIN index on `search_tsv` for exact keyword matches and a `pgvector` HNSW index (`vector_cosine_ops`, `m = 16`, `ef_construction = 64`) on `embedding`. At query time, we pull the top 80 keyword hits (` websearch_to_tsquery`) and the top 80 cosine-distance neighbours, then fuse their ranks with Reciprocal Rank Fusion (`RRF_K = 60`).

## Backfill numbers and automatic indexing on publish

We ran the initial backfill in two batches with concurrent workers:

| Batch | Live units | Decision 1 calls | Chunks created | Wall time | Failures | 
|---|---|---|---|---|---|
| Posts, concepts, pages | 564 | 1 per eligible doc | 4,171 | 2m 37s | 0 | 
| Codebase Explorer elements | 1,547 | 0 (atomic single-chunk units) | 1,547 | 43s | 0 | 
| **Total** | **2,111** | **~564** | **5,718** | **3m 20s** | **0** | 

For new and updated content, chunking and embedding run inside the existing background daemon thread in `semantic_index.refresh(unit_type, slug)`, triggered on every publish, edit, hide, show, or delete in the web CMS and over MCP. Each unit stores a `doc_hash` fingerprint of its title, summary, and Markdown; unchanged saves skip both Decision 1 and embedding calls. HTML comments (`<!-- ... -->`) are stripped inside `html_to_markdown()` before block splitting so template comments never leak into chunks or OKF files.

## One index serving human search and /.well-known/search

Both retrieval surfaces read from the same `search_chunks` hybrid query, formatting the output for their respective client:

Figure 3: Shared hybrid PostgreSQL index serving rendered HTML chunks to human visitors and raw Markdown chunks to AI agents.

- **Agent API (****/.well-known/search**
**):** Accepts`GET ?q=...` and the IETF Proposed Standard HTTP`QUERY` method (RFC 10008, plain-text or JSON`{"q": "..."}` body). Returns up to 10 ranked Markdown passages with canonical URL, title, section, and normalized score (`text/markdown; charset=utf-8` ). Guarded by a 30-minute in-memory TTL cache (500 queries), per-IP rate limits (60/min, 600/hr), control-character stripping on`q` , and`X-Robots-Tag: noindex, nofollow` so dynamic query URLs stay out of search engine indexes.
- **Human search (****/search**
**):** Groups matching passages by parent document, keeps the highest-scoring chunk per URL, ranks purely by fused relevance, renders the full semantic chunk as safe HTML with query terms highlighted in`<mark>` , and offers live client-side filter tabs (**All** ,**Articles** ,**Concepts** ,**Pages** ,**Tools** ,**Elements** ).

## Discovery advertisement across HTML and Markdown

To match the discovery convention described in our [Cloudflare Search for Agents breakdown](https://dejan.ai/blog/cloudflare-search-for-agents/), we added the four `agent:*` tags to our HTML `<head>` templates (homepage and base layout):

```
<meta name="agent:instructions" content="Use this search API to find relevant content across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown.">
<meta name="agent:endpoint" content="https://dejan.ai/.well-known/search?q={query}">
<meta name="agent:method" content="GET">
<meta name="agent:documentation" content="https://dejan.ai/blog/cloudflare-search-for-agents/">
```

Every [Open Knowledge Format (](https://dejan.ai/okf/index.md)[/okf/*.md](https://dejan.ai/okf/index.md)[)](https://dejan.ai/okf/index.md) response injects the same four fields into its YAML front matter automatically inside `_md_response()`.
