Knowledge
Documents chunked and embedded per organization, agent, project, chat or user, with hybrid search that ranks full text and vector matches together.
The knowledge block stores what an assistant can look things up in:
documents, split into chunks that each carry an embedding and a
tsvector. Search runs full text and vector similarity and fuses the two
rankings with reciprocal rank fusion, so a query finds both the exact term
and a paraphrase. Row level security decides which documents a caller
sees.
better-supabase add knowledge # adds tenant, access and vector-search as well| Table | Holds |
|---|---|
knowledge_documents | One row per document: tenant, owner, scope and scope_id, title, source, metadata, status |
knowledge_chunks | The chunks of a document in order: content, token_count, embedding, embedding_model, the tsv |
A document belongs to one scope:
| Scope | scope_id | Who reads it |
|---|---|---|
organization | none | every member with the read permission |
agent | the agent | every member with the read permission |
project | the project | the owner |
chat | an AI chat | the owner, and whoever can read the chat |
user | the owner (the caller by default) | the owner |
subject | none; subject_type, subject_id | whoever can read the record |
Members with the manage permission read every document in the tenant
except subject ones, which follow the record (see
Record knowledge).
A new document is user scoped unless you pass scope.
| Permission | Lets a member | Default roles |
|---|---|---|
knowledge.read | read organization and agent documents | owner, admin, member |
knowledge.write | add user, project and chat documents | owner, admin, member |
knowledge.manage | add organization and agent documents, read every one | owner, admin |
Rename the keys with blocks.knowledge.permissions.read, .write
and .manage.
| Option | Default | Sets |
|---|---|---|
dimensions | 1536 | The embedding size; 384 for gte-small in Edge Functions |
type | vector | vector or halfvec, as in vector search |
textSearch | simple | The text search configuration of the tsv column, such as english |
embedQueue | knowledge_embed | The jobs queue a new document is enqueued on |
autoEmbed | false | A pg_cron job posts pending chunks to an embedding worker |
Server
Server code calls the knowledge instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useKnowledge } = defineDataHooks(
"knowledge",
(db: AppDb) => db.knowledge,
);const rows = await db.knowledge.list({ limit: 50 }).orThrow();"use client";
import { useKnowledge } from "@/lib/supabase/hooks";
const rows = useKnowledge({ limit: 50 });transport acts as the user. service writes embeddings, which only the
server does. The embedder is anything with a model name and an
embed(values) method; better-supabase/ai-sdk/embeddings
builds one from an AI SDK model, and files (an AI files
client) lets ingest.file read uploads.
| Group | Methods |
|---|---|
collections | create, update, remove, list, grant, revoke, grants |
documents | create, get, list, write, remove |
ingest | text, file, queue |
| (top level) | process, embedJob, drain, search, reembed |
Paging documents and collections
documents.page and collections.page page by keyset (ADR 1077), each with facets and count, and documents.get and collections.get return a not_found error for an unknown id. Documents sort by createdAt and title, filter by scope, status, collectionId, scopeId, subjectType and subjectId, and q searches the title. Collections sort by priority (the default), name and createdAt, filter by visibility, and q searches the name and the description. documents.list and collections.list keep working and are deprecated. A cursor belongs to the sort it came from, so start again from the first page when sort changes. A sort, filter, facet or text the entity does not declare returns an invalid_input error. Block lists describes the options every block list shares.
Ingest and embed
const doc = await knowledge.ingest
.text(organizationId, { title: "Refund policy", text, source: "handbook" })
.orThrow();ingest.text creates the document and writes its chunks with
chunk(text): about 2,000 characters each, cut at a paragraph, line,
sentence or word break, with a short overlap. The document starts
pending. Embedding happens on the server:
- With the
jobsmodule installed, a new document is enqueued onknowledge_embed; registerknowledge.embedJob()as its handler. The last failed attempt marks the documentfailedwith the error. - Without a queue, call
knowledge.process(doc.id)(inafter(), for example) orknowledge.drain()from a cron job.draintries each documentattemptstimes (3 by default) and marks itfailedonly after the last attempt.
Each pending chunk comes with a hash of its text, and an embedding is
written only while the chunk still has that text: a chunk rewritten during
the embedding call stays pending for the next round. The embedder must
return one finite vector per chunk, all of one length; anything else fails
with invalid_input and the hint EMBEDDING_INVALID.
documents.write(id, chunks) replaces the chunks; a chunk whose text and
model didn't change keeps its embedding, so editing one paragraph re-embeds
one chunk. reembed({ model }) marks documents embedded by another model
pending again after you change models.
ingest.file(organizationId, fileId) reads a ready AI files upload. It
extracts text, JSON, XML and YAML; pass extract to createKnowledge for
PDFs and other formats.
With the jobs block installed, ingest.queue(organizationId, fileId) moves
that work off the request: it creates a pending document for the file and
enqueues it on knowledge_ingest (the ingestQueue option). Register
knowledge.ingestJob() as that queue's handler on the server; it reads the
file, extracts its text and writes the chunks, which enqueues their
embedding. The handler runs as the service role, so give createKnowledge
an AI files client with a service transport. The last failed attempt marks
the document failed.
const handlers = {
knowledge_ingest: knowledge.ingestJob(),
knowledge_embed: knowledge.embedJob(),
};PDF and Word files
createKnowledge({ extract }) takes the text extractor. extractors picks one
by media type and falls back to the default text decoder, and pdfExtractor
and docxExtractor read PDF and Word files with the optional peers unpdf and
mammoth. Install the one you use (pnpm add unpdf mammoth) and the first
file of that type imports it. Without the library, the extractor throws an
error that names it.
import {
DOCX_TYPE,
PDF_TYPE,
createKnowledge,
docxExtractor,
extractors,
pdfExtractor,
} from "better-supabase/blocks/knowledge";
export const knowledge = createKnowledge({
transport,
extract: extractors({
[PDF_TYPE]: pdfExtractor(),
[DOCX_TYPE]: docxExtractor(),
}),
});To bundle the library yourself or use another one, pass
load: () => import("unpdf"). load has to return a module with extractText(data, { mergePages: false })
(unpdf) or extractRawText({ arrayBuffer }) (mammoth). The PDF extractor
puts a form feed between pages, which gives chunks a position.page. A failed
load is retried on the next file.
Pages from a URL
createUrlSource fetches a web page and ingests it with the URL as the
document's source. resync fetches it again and replaces the chunks, so a
page that did not change costs no embedding calls, and resyncAll does that for
every URL document of a tenant (call it from a cron route).
import { createUrlSource } from "better-supabase/blocks/knowledge";
export const urls = createUrlSource({
knowledge,
allowedHosts: ["docs.example.com"],
maxBytes: 2_000_000,
timeoutMs: 10_000,
});
const doc = await urls
.ingest({ organizationId, url: "https://docs.example.com/refunds" })
.orThrow();
await urls.resyncAll({ organizationId }).orThrow();The source allows only http and https URLs without credentials, checks every
redirect hop, reads at most maxBytes (5 MiB by default) and stops after
timeoutMs (15 seconds). Without allowedHosts it refuses localhost, names
without a dot, .local and .internal names, and private, loopback, link-local
and multicast addresses. It cannot see what a name resolves to, so set
allowedHosts when a user supplies the URL. HTML becomes text with #
headings; other types go through extract.
Chunk positions
Every chunk written by chunk() records where it sits in the document text:
position: { start, end, page?, heading? }, stored under the chunk's
metadata.position. start and end are offsets into the text after line
endings are normalized and the text is trimmed, page counts form feeds (the
PDF extractor adds them) and heading is the nearest Markdown heading above the
chunk. Search hits return it as hit.position, so a citation can say
"Refund policy, page 3".
Search
const hits = await knowledge
.search(organizationId, "how fast are refunds paid", {
scopes: [{ scope: "organization" }, { scope: "chat", id: chatId }],
k: 8,
})
.orThrow();Each hit has the documentId, the chunk index, its content, the
document title, a fused score, the chunkId and the organizationId
(undefined for a system document). Without an embedder the search is
full text only; pass { text, embedding } to reuse an embedding you
already have. filter matches documents whose metadata contains an
object.
Set dimensions on createKnowledge to fail with the hint
KNOWLEDGE_DIMENSION_MISMATCH when an embedder returns vectors of another
length. priorityOrder: false (on the block or one search) ranks the hits by
score alone in knowledge_search, ignoring collection priority. The
function takes it as priority_order (default true) and returns chunk_id
and organization_id in each hit.
Collections
A collection groups documents with a visibility and a priority. An
automatic collection shows up in every search of its organization, a
restricted one only for the users and teams it is granted to (and for
members with the manage permission), and a disabled one in no search. A
search ranks the chunks of a higher priority collection first; pass
collections to search only some of them.
const policies = await knowledge.collections
.create(organizationId, { name: "HR policies", visibility: "restricted" })
.orThrow();
await knowledge.collections
.grant(policies.id, { teamId: peopleTeamId })
.orThrow();
await knowledge.ingest
.text(organizationId, { title: "Leave", text, collectionId: policies.id })
.orThrow();
const hits = await knowledge
.search(organizationId, "parental leave", { collections: [policies.id] })
.orThrow();Team grants need the teams block, and their
team_id column takes the teams id type (uuid or bigint). Each grant
keeps its collection's organization_id, so data lifecycle exports and
deletes it with the tenant. Removing a collection keeps its documents,
without a collection.
An adopted knowledge_collections table may declare visibility as an
enum: the module writes and compares it through the column's type, and
blocks.knowledge.values.collections.visibility maps its labels.
Record knowledge
With the subjects block installed, a document can
belong to one record, such as a drive folder, a case or a ticket. Pass
scope: "subject" and the record's subject type and id:
const doc = await knowledge.ingest
.text(organizationId, {
title: "Lease",
text,
scope: "subject",
subject: { type: "drive_node", id: folderId },
})
.orThrow();
const notes = await knowledge.documents
.list(organizationId, { subject: { type: "drive_node", id: folderId } })
.orThrow();
const hits = await knowledge
.search(organizationId, "when does the lease renew", {
scopes: [{ scope: "subject", type: "drive_node", id: folderId }],
})
.orThrow();A member reads, lists and searches the document only while
can_subject(subject_type, subject_id, 'read') is true: the record is
visible to them, they hold the subject type's read permission, and its
check function (a drive node's grants, for example) lets them read. Share
the folder and its knowledge follows; revoke the grant and it goes. The
owner and members with the manage permission get no exception, and the
collection the document is in must still be readable. Creating one needs
read access to the record too, or it fails with the hint
KNOWLEDGE_DOCUMENT_SUBJECT_NOT_FOUND. Scope subject without both a type
and an id, or a type or id with another scope, fails with
KNOWLEDGE_DOCUMENT_INVALID.
Without the subjects block the subject scope is not accepted. The
subject_type and subject_id columns are optional: map them to your own
columns on an adopted knowledge_documents table, or leave them out.
System documents
The service role creates a system collection with collections.create(null, ...)
and a system document with documents.create(null, ...) or
ingest.text(null, ...). A system document has no organization and no owner,
and every organization reads and searches it, so product help or a shared
handbook is written once. A system document can join a system collection
only; an organization's documents join its own collections or a system one.
AI SDK
better-supabase/ai-sdk/embeddings gives you
the embedder, a reranker, a search tool for the model and source parts
for the answer.
Hooks
createKnowledge takes hooks, keyed by method name, that run your code
before and after a call: refuse it with a DbError, rewrite its arguments
or observe the result (see extending blocks). Methods in a group take their hooks under the group's name,
such as hooks: { documents: { create: { before } } }.
Without the client
db.knowledge is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { embedWith } from "better-supabase/ai-sdk/embeddings";
import {
createKnowledge,
rpcTransport,
} from "better-supabase/blocks/knowledge";
export const knowledgeFor = (supabase: SupabaseClient, admin: SupabaseClient) =>
createKnowledge({
transport: rpcTransport(supabase),
service: rpcTransport(admin),
embedder: embedWith("openai/text-embedding-3-small"),
});Last updated on
AI files
Attachments and generated files for AI chats in a private bucket, provider file references with expiry, and versioned documents with suggested edits.
Memory
Core memory files the model edits with Anthropic's memory tool commands, archival facts found by similarity, and recall over a user's earlier messages.