Embeddings
Embed knowledge with an AI SDK model or Supabase's built-in model, rerank hits, and give the model a search tool that cites its sources.
better-supabase/ai-sdk/embeddings connects the knowledge
and memory blocks to the AI SDK. The blocks take
any Embedder; this subpath builds one from an AI SDK model and adds the
tool the model searches with.
pnpm add aiEmbedders
import { embedWith, supabaseEmbed } from "better-supabase/ai-sdk/embeddings";
const embedder = embedWith("openai/text-embedding-3-small");embedWith(model, options) calls the SDK's embedMany with
maxParallelCalls (4 by default) and providerOptions. A model string
goes through the AI Gateway. The
embedder's model name (openai/text-embedding-3-small, or name when
you pass one) is stored with each chunk, so knowledge.reembed can find
what another model embedded. The embedder has apiVersion: 2: embed
returns { embeddings, usage: { tokens } }, so the token count is available
to callers that meter embeddings.
supabaseEmbed() runs Supabase's built-in gte-small model in an Edge
Function, through Supabase.ai.Session, with no API key. It returns 384
numbers, so install the modules with options: { dimensions: 384 }.
Search tool
import { searchTool, toSourceParts } from "better-supabase/ai-sdk/embeddings";
const result = streamText({
model,
messages,
tools: {
searchKnowledge: searchTool(knowledge, organizationId, {
scopes: [{ scope: "organization" }, { scope: "chat", id: chatId }],
onHits: (hits) => sources.push(...toSourceParts(hits)),
}),
},
});searchTool is strict, and the reranker receives the tenant so the rerank
call is metered. modelOutput: { maxCharacters } sends the model only each
result's id and its trimmed content, while onHits still gets the full hits.
searchTool gives the model a query input and returns up to k (8)
chunks as { results: [{ id, title, content }] }, with ids in the form
documentId#index the model can cite. The search runs as the caller, so
row level security decides what the model sees. toSourceParts(hits)
returns one source-document part per document, for the assistant
message.
Reranking
import { rerankWith } from "better-supabase/ai-sdk/embeddings";
searchTool(knowledge, organizationId, {
k: 20,
rerank: rerankWith("cohere/rerank-v3.5", { topN: 5 }),
});rerankWith reorders the hits with the SDK's rerank and keeps the
topN best, with the reranker's score.
Cache embeddings
embeddingCacheMiddleware wraps an embedding model so the same text is embedded once per model and
dimensions. rerankHits reorders any list of hits with a reranker, and embedWith takes
dimensions for models that shorten their output.
Embed table rows automatically
renderAutoEmbedding from better-supabase/sql renders the SQL that keeps an embedding column
current for one table: a halfvec column with an HNSW cosine index, a trigger that clears the vector
and queues the row on pgmq when the content changes, and a pg_cron job that posts queued rows to
your worker through pg_net. The worker URL and bearer token come from Vault (embedding_worker_url
and embedding_worker_token).
import { renderAutoEmbedding } from "better-supabase/sql";
const sql = renderAutoEmbedding({
table: "articles",
content: ["title", "body"],
dimensions: 1536,
});Serve the worker with embeddingWorker. apply calls the generated <table>_apply_embedding
function, which stores the vector only while the row still hashes to the text that was embedded.
import { embeddingWorker, embedWith } from "better-supabase/ai-sdk/embeddings";
export const POST = embeddingWorker({
embedder: embedWith("openai/text-embedding-3-small", { dimensions: 1536 }),
token: process.env.EMBEDDING_WORKER_TOKEN!,
apply: async (batch, job, embedding) => {
const { data } = await admin.rpc(`${batch.table}_apply_embedding`, {
row_id: job.id,
embedding_json: embedding,
content_hash: job.hash,
msg_id: job.msgId,
});
return data === true;
},
});drainEmbeddings(batch, options) runs the same steps without HTTP, for a job or a script. The
appTables.<name>.embedding (or the @bsb embedding tag, see tables) renders the SQL for you, and doctor reports jobs read five times or more (BS241) and failed pg_net requests (BS242). blocks.knowledge.options.autoEmbed sends the pending chunks of knowledge documents to the same worker, one job per chunk with the id <document id>:<chunk index>; apply each with set_knowledge_embeddings.
Last updated on