{"slug": "how-we-built-search-for-agents-on-dejan-ai-without-cloudflare", "title": "How we built Search for Agents on dejan.ai without Cloudflare", "summary": "Dejan.ai built a self-hosted /.well-known/search API without Cloudflare AI Search, using gemini-decision-1 boundary classification, gemini-embedding-2 contextual vectors and PostgreSQL pgvector hybrid search across 5,718 chunks. Backfilling all 2,111 live units produced 5,718 chunks with zero failures in 3 minutes 20 seconds, and reframing chunk boundaries as end-of-unit/start-of-new transitions cut orphan headings from 5 to 0 and chunk count from 20 to 12 on a 3,150-word test post. The pipeline frames semantic chunking as binary classification in a single gemini-decision-1 call (209 to 329 ms per document, 0 output tokens, 100% verbatim text) and embeds each chunk with Title > Section context at 768 Matryoshka dimensions.", "body_md": "# How we built Search for Agents on dejan.ai without Cloudflare\n\nHow 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.\n\nWe 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.\n\nFigure 1: End-to-end indexing and retrieval pipeline on `dejan.ai`.\n\n## Why we framed semantic chunking as binary classification\n\nFixed-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.\n\n`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.\n\nBecause 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).\n\n## The boundary-framing detail that eliminated orphan headings\n\nIn 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.\n\nReframing the question on the transition between adjacent blocks fixed the behaviour with no extra latency:\n\n```\nDoes block [B{i-1}] mark the end of a complete, self-contained semantic unit\nsuch that block [B{i}] begins a new semantic unit? Answer no if [B{i-1}] is an\nincomplete opener (such as a heading or lead-in) or if [B{i}] continues the same\nsection, argument, table, code example, or list.\n```\n\nFigure 2: Measured boundary calibration on post #339 comparing block-start framing against end-of-unit / start-of-new transition framing.\n\nBecause 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.\n\n## Contextual embeddings and the PostgreSQL schema\n\nA 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.\n\nAll keyword and vector data live in one PostgreSQL table:\n\n```\nCREATE TABLE IF NOT EXISTS search_chunks (\n    unit_type  text NOT NULL,\n    unit_id    text NOT NULL,\n    chunk_idx  integer NOT NULL,\n    slug       text NOT NULL,\n    title      text NOT NULL,\n    section    text NOT NULL DEFAULT '',\n    url        text NOT NULL,\n    markdown   text NOT NULL,\n    search_tsv tsvector GENERATED ALWAYS AS (\n        setweight(to_tsvector('english', coalesce(title, '')), 'A') ||\n        setweight(to_tsvector('english', coalesce(section, '')), 'B') ||\n        setweight(to_tsvector('english', coalesce(markdown, '')), 'C')\n    ) STORED,\n    embedding  vector(768) NOT NULL,\n    doc_hash   text NOT NULL,\n    tokens     integer NOT NULL DEFAULT 0,\n    model      text NOT NULL DEFAULT 'gemini-embedding-2',\n    updated_at timestamptz NOT NULL DEFAULT now(),\n    PRIMARY KEY (unit_type, unit_id, chunk_idx)\n);\n```\n\nTwo 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`).\n\n## Backfill numbers and automatic indexing on publish\n\nWe ran the initial backfill in two batches with concurrent workers:\n\n| Batch | Live units | Decision 1 calls | Chunks created | Wall time | Failures | \n|---|---|---|---|---|---|\n| Posts, concepts, pages | 564 | 1 per eligible doc | 4,171 | 2m 37s | 0 | \n| Codebase Explorer elements | 1,547 | 0 (atomic single-chunk units) | 1,547 | 43s | 0 | \n| **Total** | **2,111** | **~564** | **5,718** | **3m 20s** | **0** | \n\nFor 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.\n\n## One index serving human search and /.well-known/search\n\nBoth retrieval surfaces read from the same `search_chunks` hybrid query, formatting the output for their respective client:\n\nFigure 3: Shared hybrid PostgreSQL index serving rendered HTML chunks to human visitors and raw Markdown chunks to AI agents.\n\n- **Agent API (****/.well-known/search**\n**):** 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.\n- **Human search (****/search**\n**):** 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** ).\n\n## Discovery advertisement across HTML and Markdown\n\nTo 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):\n\n```\n<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.\">\n<meta name=\"agent:endpoint\" content=\"https://dejan.ai/.well-known/search?q={query}\">\n<meta name=\"agent:method\" content=\"GET\">\n<meta name=\"agent:documentation\" content=\"https://dejan.ai/blog/cloudflare-search-for-agents/\">\n```\n\nEvery [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()`.", "url": "https://wpnews.pro/news/how-we-built-search-for-agents-on-dejan-ai-without-cloudflare", "canonical_source": "https://dejan.ai/blog/agent-search-diy/", "published_at": "2026-11-27 03:17:34+00:00", "updated_at": "2026-11-27 03:43:54.355586+00:00", "lang": "en", "topics": ["ai-search", "ai-agents", "ai-tools", "structured-data"], "entities": ["dejan.ai", "Cloudflare", "gemini-decision-1", "gemini-embedding-2", "PostgreSQL", "pgvector", "PoolDPP"], "also_reported_by": [], "takeaway": "Framing semantic chunking as an end-of-unit/start-of-new transition question to gemini-decision-1, rather than asking whether each block starts a chunk, dropped the highest post-heading cut probability to 0.251 and eliminated orphan headings (5 to 0) at 209-329 ms per document with zero output token", "recommendation": {"advice": "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.", "playbook": "rag-retrieval", "playbook_url": "https://wpnews.pro/playbooks/rag-retrieval"}, "alternates": {"html": "https://wpnews.pro/news/how-we-built-search-for-agents-on-dejan-ai-without-cloudflare", "markdown": "https://wpnews.pro/news/how-we-built-search-for-agents-on-dejan-ai-without-cloudflare.md", "text": "https://wpnews.pro/news/how-we-built-search-for-agents-on-dejan-ai-without-cloudflare.txt", "jsonld": "https://wpnews.pro/news/how-we-built-search-for-agents-on-dejan-ai-without-cloudflare.jsonld"}}