Search and RAG

Retrieval-augmented generation (RAG) means searching your own content for the passages that answer a question, and sending them to the model with the prompt, so the answer is grounded in your content instead of the model's memory. PocketOne does the whole pipeline: you put content in a bucket (a knowledge base), it's chunked and embedded in the background, and one option on any $llm call does the retrieval:

const answer = await $llm.text.completeAsync({
  model: "vultr/glm-5.3",
  system: "Answer from the passages given. Say so when they don't cover it.",
  prompt: "How do I export my notes?",
  enrich: ["help"], // RAG: search the "help" bucket and send the best passages with the prompt
})
// answer.text is the answer; answer.passages are the passages it was grounded in

It uses the provider you added in Settings → LLM (AI in your app), which needs embedding models (Vultr's, for one). The embedding model is picked for you and kept; you never name one.

Why not just put everything in the prompt?

You can, for a little content: that's context stuffing, and long context windows make it tempting. It gets slow and expensive as content grows (every call pays for all of it), and models pay less attention to the middle of a long prompt. RAG sends only the few passages that match the question, so a question costs the same whether the knowledge base is one page or ten thousand.

How it works

  1. Ingestion. Each source you add (a file, a folder, a zip, a web page, a Git repository, a collection) becomes documents, and each document is split into chunks of about 500 tokens: Markdown at its headings (each chunk keeps its heading path, like "Install › macOS"), code and text at blank lines.
  2. Embeddings. Each chunk is turned into a vector by your embedding model, in the background. A chunk whose text didn't change is never embedded again, and identical text anywhere in the app is embedded once.
  3. Retrieval. A question is embedded too, and ranked against the chunks by meaning (semantic search, vector similarity) and by words (keyword search, BM25 over a local index) at once: hybrid search. Keywords catch exact names like onRecordCreate that embeddings blur; meaning catches a reworded question.
  4. Generation. enrich sends the best chunks after the prompt, numbered so the model can cite them, and the answer lists them in passages.

1. Make a bucket

A bucket is a knowledge base: content that's searched together. Your app makes the bucket it needs, once at startup. The description is what your admins see on the dashboard's Search screen, so say what belongs there:

// pb_hooks/search.pb.js
onBootstrap((e) => {
  e.next()
  $llm.search.ensure({
    name: "help",
    title: "Help center",
    owner: "Help desk",
    description: "Our help articles, as Markdown. The help desk answers from these.",
  })
})

Calling it again changes nothing, so your admins' changes stick. You can also make a bucket on the Search screen.

2. Add your content

Open the dashboard and choose Search in the header. A sidebar lists Chat, Search, Settings and every bucket. Open yours and add sources. Each one is a single row you can refresh, replace or remove, however many documents it brings:

  • Drop files, folders or zips on it (Markdown, text or code inside), or choose files.
  • Paste text.
  • Add a URL or Git repo: paste any URL. Its server is asked whether it's a Git repository (with or without .git, on any host), and the form shows how it will be read, with a switch if you want the other. Pick how often to read it again: every hour, day or week. A repository brings its default branch's text files and its recent commits.
  • Follow a collection: pick the collection, check the fields to search (its text fields start checked; the first is each record's title) and, if you like, which records (published = true). It reads the records there now and keeps up as they're saved and deleted.

Adding something with the same name as a source replaces it: files that didn't change cost nothing, and files it no longer has are removed. For a new version under another name (guide-v2.zip), use Upload a new version on the old one's row. Each source goes from reading to ready, and its documents from in line to embedding to ready; open a row to see its documents.

To try a bucket out, use Chat in the sidebar: pick buckets and a model, ask questions in words, and read the answers with the passages they're grounded in (follow-ups keep the conversation). Search shows the raw hybrid search results instead: exactly what $llm.search and enrich get.

From code

Everything the screen does, your code can do with $llm.search. Adding returns at once; ingestion happens in the background.

// a file's text, or text you put together (a source of one document; the same name again replaces it)
$llm.search.add({ bucket: "help", name: "export.md", text: "# Exporting\n\nChoose File → Export…" })

// a web page or a Git repository, read again every day
$llm.search.addURL({ bucket: "help", url: "https://github.com/acme/help-articles", every: "day" })

// a collection: a document per published article, kept in sync as records are saved and deleted
$llm.search.follow({ bucket: "help", collection: "articles", fields: ["title", "body"], filter: "published = true" })

// a folder of the app's own files (your docs pages), read again every five minutes; each result links to its page
$llm.search.addFolder({ bucket: "help", path: "pb_pages/docs", include: ["*.md"], url: "/docs/{path}" })

Then look at what's there, and tidy up:

const sources = $llm.search.sources("help")          // [{ name, kind, status, documents, pending, error, ... }]
const docs = $llm.search.documents({ bucket: "help", source: "export.md" })
$llm.search.refresh("help", "https://github.com/acme/help-articles") // read it again now
$llm.search.remove("help", ["export.md"])            // take sources out, with their documents
const { model, chunks, embedded } = $llm.search.status() // embedded < chunks: still embedding

A source's name is how it's found again: the file name you gave, the URL, or the collection.

3. RAG with enrich

enrich works on $llm.text.completeAsync, $llm.text.streamAsync and LLM Chat (on a chat's options or a send):

const chat = $llm.chat.open(id, { model: "vultr/glm-5.3", system: preamble, enrich: ["help"] })
const answer = await chat.sendAsync("And as PDF?")

Name several buckets to search them together (enrich: ["help", "changelog"]), or pass { buckets, limit, query }: limit is how many passages go in (5 by default, at most 20) and query searches for something other than the prompt. LLM Chat saves the passages with each question, so later turns send the same thing.

Search directly

To show results yourself (a search box, related articles), run the hybrid search without a model call:

const found = await $llm.search.searchAsync({ buckets: ["help"], query: "export notes", limit: 5 })
// found.results: [{ bucket, source, document, heading, text, record, score }, ...], best first

Leave buckets out to search every bucket. It's the only async $llm.search call: it embeds the query (a few tokens; a repeated query is cached).

Who sees what

A collection source holds a copy of its records' text, so retrieval skips the collection's API rules unless you say who's asking. Pass the signed-in user as viewer and passages from records they can't view are left out (null is a signed-out visitor):

const found = await $llm.search.searchAsync({ buckets: ["notes"], query, viewer: ctx.auth })
const answer = await $llm.text.completeAsync({ model, prompt: question, enrich: { buckets: ["notes"], viewer: ctx.auth } })

Without viewer, a search sees everything, as your own server code does. Always pass it when the answer is for a user.

The embedding model

One embedding model embeds every bucket, so any of them can be searched together. Settings on the Search screen shows it and lets you change it; every bucket is then embedded again in the background, with its progress shown. Search keeps working meanwhile: chunks not yet re-embedded are still found by keyword search.

What it costs

Embedding is billed to your provider account like any $llm call: qwen3-embedding-4b on Vultr is $0.05 per million tokens, about 4 MB of text, embedded once. Each document shows what it cost. Each search embeds only the query, a few tokens; the model call that uses the passages pays for them as input tokens.

$llm.search at a glance

Every call is local and returns at once, except searchAsync.

Call What it does
buckets() Every bucket, with its counts.
bucket(name) One bucket.
ensure({ name, title?, description?, owner? }) Makes the bucket if it's missing and returns it; an existing one keeps its settings.
update({ name, title?, description?, maxDocuments?, maxBytes? }) Changes a bucket.
deleteBucket(name) Deletes a bucket and everything in it.
sources(bucket) Its sources: { name, kind, status, documents, chunks, embedded, pending, error, refreshed, next, ... }.
add({ bucket, name, text, replace? }) A file or text as a source; replace names an older source a renamed version replaces.
addURL({ bucket, url, every?, kind?, commits?, exclude? }) A web page or Git repository (kind is decided by asking the server); every is hour, day or week.
follow({ bucket, collection, fields, filter? }) A collection; the first field is each record's title.
addFolder({ bucket, path, include?, exclude?, url? }) A folder of the app's own files (path relative to the app's folder, never pb_data), read again every five minutes; url ("/docs/{path}") links each result to its page and section.
refresh(bucket, source) Reads a source again now.
remove(bucket, sources) Takes sources out, with their documents.
documents(bucket | { bucket, source?, prefix? }) Documents, with their status and how many chunks are embedded.
status() The app's embedding model, and how many chunks are embedded of how many.
await searchAsync({ query, buckets?, limit?, prefix?, viewer? }) Hybrid search across the buckets (all when none are named): { results: [{ bucket, source, document, heading, text, record, url, score }], model, usage }.

The same operations are the llm.search/v1 contract: over HTTP at /api/_c/llm.search/v1/… (a superuser, or an API token with the search scope), from Go with searchv1.Contract.Must(app), and as MCP tools. The LLM Search extension has the details: what's skipped in folders, zips and repositories, the limits, and how ranking works.