> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Embeddings and reranking

> Embed facts for vector ranking, cache vectors by content digest, run bulk jobs and rerank results.

## Embed and rank

`ai.embed(ctx, key, texts, { once, then, role })` submits one embedding
request: 1 to the entry's `maxInputs` texts, at most 256, as `document`
(the default) or `query`. The continuation decodes the vectors with
`ai.vectors(key, result)` and writes them to a `t.vector` field, which
`.near` ranks.

```ts bijection/notes.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { mutation, t, table } from "@bijectionhq/bijection";
import { digest } from "@bijectionhq/library-codecs";
import { ai } from "./ai";
import { workspace } from "./labels";

export const notes = table(
  { text: t.string, embedding: t.maybe(t.vector(1536, { model: "text-embedding-3-small" })) },
  { label: workspace },
);

export const embed = mutation(
  { under: workspace, args: { id: t.key(notes) } },
  async (ctx, { id }) => {
    const note = await ctx.get(notes(id));
    if (note === null) return null;
    await ai.embed(ctx, "embed", [note.text], { once: ["embed", id, digest(note.text)], then: embedded.with({ id }) });
    return null;
  },
);

export const embedded = mutation(
  { under: workspace, args: { id: t.key(notes), result: ai.result } },
  async (ctx, { id, result }) => {
    const vectors = ai.vectors("embed", result, 1);
    if (vectors.ok) await ctx.patch(notes(id), { embedding: [...vectors.value[0]!] });
    return null;
  },
);

// In a query: the ten nearest notes to a query vector.
// await ctx.list(notes.near("embedding", vector).first(10));
```

`t.vector(n, { model })` names the embedding model, so a vector of another
model does not type-check where this one is declared, and the host refuses
a deploy that changes a field's model. `ai.generation(key)` answers the
exact model and shape that produced a vector: a new model or dimension is a
new generation. Add `recall` to opt a field's ranking into the host's
approximate route. A `.where(…)` before `.near` filters the ranking by an
index entry that ends in the vector field, and `.search(…).near(…)` fuses a
text ranking with it. See [indexes](https://docs.bijection.com/database/indexes.md).

Sending text to a model is egress: the pack's clearance must admit the
frame's label. See [provider packs](https://docs.bijection.com/models/gateway.md#egress-follows-labels).

## Cache vectors by content

`embeddingCache({ label })` is a subtree of two tables at the source's
label: entries keyed by `contentKey(generation, text)`, and the
contributions of the sources whose text digests to them. A cache hit
reuses the vector without a provider call.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { digest } from "@bijectionhq/library-codecs";
import { embeddingCache } from "@bijectionhq/library-models";

export const vectors = embeddingCache({ label: workspace });   // app({ vectors, ... })

// In a mutation under `workspace`:
const generation = ai.generation("embed");
const items = facts.map((fact) => ({ text: fact.text, source: `notes/${fact.id}`, revision: digest(fact.text) }));
const cached = await vectors.use(ctx, generation, items);
// embed the misses, then in the continuation:
await vectors.store(ctx, generation, missing, decoded);
// when a note is deleted, edited or erased:
await vectors.retract(ctx, `notes/${id}`);
```

`retract` removes a source's contributions and deletes every entry left
without one, in the same transaction, so erasable sources may use the
cache. One cache holds one label. The retrieval library creates its own
cache by default and accepts a shared one through `cache`.

## Bulk embedding

`bulkEmbeddings({ label, ai, cache, openai, azure, vertex, bedrock, poll,
within, retention })` is a subtree that runs a provider's batch API (OpenAI
and Azure OpenAI Batch, Vertex AI batch prediction, Bedrock batch
inference) as tasks that land in the cache. `split(model, items)` bounds
the jobs, and `start(ctx, { job, model, items })` uploads the input in
pieces, creates the job, polls it with `due` tasks and lands its output a
window at a time. Set `meter: { reserve }` on the OpenAI, Azure OpenAI
or Bedrock batch receiver, or `batchMeter: { reserve }` on
`vertexReceiver`, to charge a fixed allowance at batch creation. Choose
the reserve for the largest job you submit. The job attempts to delete
known provider-side copies when it ends. Bedrock needs at least 100
records.

## Rerank

`ai.rerank(ctx, key, query, documents, { once, then, topN })` scores 1 to
the entry's `maxDocuments` documents against a query. The continuation
reads `ai.ranking(key, result)`: `{ index, score }` per document, best
first.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.