# AI Search (AutoRAG) — semantic retrieval for the library

Cloudflare **AI Search** (managed AutoRAG) indexes the R2 bucket and answers by
*meaning*, not just keywords — the real fix for "LLMs can't find our material".
It surfaces in the Worker as the `ai_search` MCP tool and `GET /api/ai-search`.

The wiring is **gated + inert until provisioned**: with no `AI_SEARCH` binding,
`ai_search` returns a "not provisioned" notice and nothing else changes. This is
safe to deploy before the instance exists (no deploy break).

## 1. Provision the instance (once) — verified command

```bash
npx wrangler ai-search create trustfortress-library \
  --type r2 --source trustfortress-resource-library
```
This creates an AI Search instance that indexes the existing
`trustfortress-resource-library` R2 bucket. Indexing runs asynchronously — new
R2 objects are picked up on AutoRAG's next scan (not instantly). Check status /
trigger a re-index:
```bash
npx wrangler ai-search get trustfortress-library     # status + config
npx wrangler ai-search stats trustfortress-library   # usage / index stats
npx wrangler ai-search search trustfortress-library "your query"   # test retrieval
```
There is no `wrangler ai-search jobs` subcommand. To force an immediate re-index
after uploading new docs, use the Cloudflare dashboard: **AI → AI Search →
trustfortress-library → Sync index**.

## 2. Bind it into the Worker

Add to `apps/resource-library/wrangler.jsonc` (JSONC form of the `[[ai_search]]`
binding), then redeploy:
```jsonc
"ai_search": [
  { "binding": "AI_SEARCH", "instance_name": "trustfortress-library" }
]
```
> Confirm the exact binding key against the current AI Search Workers-binding docs
> before deploying — it is **open beta** and the config/response shape may have
> changed. The Worker's `aiSearchQuery()` normalizes the response defensively.

## 3. Verify it's actually serving (paste-the-output)

```bash
# HTTP:
curl -sS 'https://lib.trustfortress.ai/api/ai-search?q=how%20is%20FAR%3D0%20a%20calibration%20identity' | jq '.configured,.results[0]'
# MCP:
curl -sS https://lib.trustfortress.ai/mcp -H 'content-type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"ai_search","arguments":{"query":"agentic waste blast radius"}}}'
```
`configured: true` with real `results` chunks = live. Only then should the site
copy call AI Search "live" rather than "planned".

## Generation model

The answer/generation model for `/api/ask` is **`@cf/google/gemma-4-26b-a4b-it`**
(Gemma 4, 26B / ~4B active MoE — high quality, fast), routed through
[AI Gateway](./AI_GATEWAY.md) when configured. When AI Search generation is wired,
pass the same Gemma model to keep answers consistent.
