Search modes

Embedding adapters

Write or install an embedding adapter in TypeScript, Python, Go, or Rust, let the engine embed your text on every write and every search, store the rest of a batch when one document has no text, and wrap the adapter in a cache.

An embedding adapter converts text into the numbers that a vector field stores. Once you give the engine an adapter and map a vector field to its source text fields, the engine embeds each document as you write it and each question as you search. Your code then passes only text, while the engine produces every vector. Every example on this page is part of one program for a small catalogue of kitchen appliances. Each code block below shows the whole file, with green lines marking the lines that you add at each step and struck lines marking the lines that you remove.

Install a model that works inside your process

The TypeScript package @delali/narsil-embeddings-transformers provides a ready-made adapter that loads all-MiniLM-L6-v2 into your process. The Python, Go, and Rust packages provide no ready-made adapter, so in those languages, the adapter is a short class or type that you write around a library. That library is fastembed in Python and Rust, or hugot in Go, each of which loads the same model locally. In each language, the library downloads the model the first time that your program uses it, and after that download your program loads the model with no API key.

pnpm add @delali/narsil @delali/narsil-embeddings-transformers @huggingface/transformers

The latest release of hugot requires Go 1.27.0 or later, although the Narsil module itself works on Go 1.26.

Embed an index as you write it

An adapter has dimensions, the width of every vector that it returns, and an embed method that turns one text into one vector. An adapter can also embed a whole batch in one call through embedBatch in TypeScript, embed_batch in Python and Rust, or EmbedBatch in Go. The adapters in this step pass each batch to the model in one call. The engine registers the adapter under the name kitchen-model, while the embedding setting of the index refers to that name and lists the text fields from which the engine builds the vector field. The last document in the batch contains only a supplier, with no name or summary.

import { createNarsil } from '@delali/narsil'
import { createTransformersEmbedding } from '@delali/narsil-embeddings-transformers'
 
const embedding = createTransformersEmbedding({ dimensions: 384 })
 
const narsil = await createNarsil({ embeddingAdapters: { 'kitchen-model': embedding } })
 
await narsil.createIndex('appliances', {
  schema: { name: 'string', summary: 'string', supplier: 'string', embedding: 'vector[384]' },
  embedding: { adapter: 'kitchen-model', fields: { embedding: ['name', 'summary'] } },
})
 
const loaded = await narsil.insertBatch('appliances', [
  { id: 'kt-2100', name: 'Stovetop kettle', summary: 'A two-litre enamel kettle that whistles when the water reaches the boil.', supplier: 'kettle-supplier, Kraków' },
  { id: 'gr-4400', name: 'Burr grinder', summary: 'Forty grind settings from espresso to cafetiere, with a stainless steel burr set.', supplier: 'grinder-supplier, Osaka' },
  { id: 'bl-1200', name: 'Counter blender', summary: 'A 1200 watt motor that crushes ice and frozen fruit without stalling.', supplier: 'blender-supplier, Gothenburg' },
  { id: 'tp-0800', name: 'Four-slot toaster', summary: 'Four wide slots with a reheat setting and a removable crumb tray.', supplier: 'toaster-supplier, Enugu' },
  { id: 'sc-3000', name: 'Pressure cooker', summary: 'A six-litre pot that cuts a bean stew from three hours to forty minutes.', supplier: 'cooker-supplier, Medellín' },
  { id: 'mw-5500', name: 'Combination oven', summary: 'A microwave and convection oven in one cabinet, with a browning element.', supplier: 'oven-supplier, Lyon' },
  { id: 'xx-0000', supplier: 'kitchenware-supplier, Surabaya' },
])
 
console.log(
  JSON.stringify(
    {
      succeeded: loaded.succeeded,
      failed: loaded.failed.map(({ docId, error }) => ({ docId, code: error.code, message: error.message })),
    },
    null,
    2
  )
)
 
await narsil.shutdown()
{
  "succeeded": [
    "kt-2100",
    "gr-4400",
    "bl-1200",
    "tp-0800",
    "sc-3000",
    "mw-5500"
  ],
  "failed": [
    {
      "docId": "xx-0000",
      "code": "EMBEDDING_NO_SOURCE",
      "message": "All source fields for embedding target \"embedding\" are missing or empty"
    }
  ]
}

The engine embeds the six appliances in one call to the batch method of the adapter, joining each name and summary with a newline, before it stores the vectors in embedding. The last document has no text in either source field, so the engine rejects it with EMBEDDING_NO_SOURCE and stores the other six. In TypeScript and Go, details.documentIndex on that error gives the position of the document in the batch. When the adapter fails on any text of a batch, however, the engine rejects every document in that batch with EMBEDDING_FAILED. The engine makes no retry after a failure, so put any retry in the adapter.

Search by the meaning of a question

For a vector query that passes text in place of value, the engine embeds the question with the same adapter before it compares the vectors. In this step, the program prints the three nearest appliances in place of the batch report.

import { createNarsil } from '@delali/narsil'
import { createTransformersEmbedding } from '@delali/narsil-embeddings-transformers'
 
const embedding = createTransformersEmbedding({ dimensions: 384 })
 
const narsil = await createNarsil({ embeddingAdapters: { 'kitchen-model': embedding } })
 
await narsil.createIndex('appliances', {
  schema: { name: 'string', summary: 'string', supplier: 'string', embedding: 'vector[384]' },
  embedding: { adapter: 'kitchen-model', fields: { embedding: ['name', 'summary'] } },
})
 
const loaded = await narsil.insertBatch('appliances', [ 
await narsil.insertBatch('appliances', [ 
  { id: 'kt-2100', name: 'Stovetop kettle', summary: 'A two-litre enamel kettle that whistles when the water reaches the boil.', supplier: 'kettle-supplier, Kraków' },
  { id: 'gr-4400', name: 'Burr grinder', summary: 'Forty grind settings from espresso to cafetiere, with a stainless steel burr set.', supplier: 'grinder-supplier, Osaka' },
  { id: 'bl-1200', name: 'Counter blender', summary: 'A 1200 watt motor that crushes ice and frozen fruit without stalling.', supplier: 'blender-supplier, Gothenburg' },
  { id: 'tp-0800', name: 'Four-slot toaster', summary: 'Four wide slots with a reheat setting and a removable crumb tray.', supplier: 'toaster-supplier, Enugu' },
  { id: 'sc-3000', name: 'Pressure cooker', summary: 'A six-litre pot that cuts a bean stew from three hours to forty minutes.', supplier: 'cooker-supplier, Medellín' },
  { id: 'mw-5500', name: 'Combination oven', summary: 'A microwave and convection oven in one cabinet, with a browning element.', supplier: 'oven-supplier, Lyon' },
  { id: 'xx-0000', supplier: 'kitchenware-supplier, Surabaya' },
])
 
console.log( 
  JSON.stringify(
    {
      succeeded: loaded.succeeded,
      failed: loaded.failed.map(({ docId, error }) => ({ docId, code: error.code, message: error.message })),
    },
    null,
    2
  )
)
const results = await narsil.query('appliances', { 
  mode: 'vector',
  vector: { field: 'embedding', text: 'something that makes coffee taste better' },
  limit: 3,
  document: { include: ['name', 'supplier'] },
})
 
console.log(JSON.stringify(results.hits, (key, value) => (typeof value === 'number' ? Number(value.toFixed(2)) : value), 2))
 
await narsil.shutdown()
[
  {
    "id": "gr-4400",
    "score": 0.39,
    "document": {
      "name": "Burr grinder",
      "supplier": "grinder-supplier, Osaka"
    }
  },
  {
    "id": "bl-1200",
    "score": 0.25,
    "document": {
      "name": "Counter blender",
      "supplier": "blender-supplier, Gothenburg"
    }
  },
  {
    "id": "sc-3000",
    "score": 0.24,
    "document": {
      "name": "Pressure cooker",
      "supplier": "cooker-supplier, Medellín"
    }
  }
]

None of the three contains the word coffee, yet the burr grinder comes first at 0.39, since its summary contains espresso and cafetiere. The blender and the pressure cooker follow at 0.25 and 0.24, which are weak matches for a question about coffee. To make the engine drop such hits, set a similarity floor, as on the Vector search page. Without a projection, each hit contains the whole stored document, including all 384 numbers of its vector, so the program lists the fields to return.

Give the engine its adapters again after a restart

The engine stores only the name of the adapter with the index, because an adapter is code. Give the engine the same adapters under the same names each time the process starts. When an engine opens an index without its adapter, it raises EMBEDDING_CONFIG_INVALID for a write or a text query on that index. The error message contains the name of the missing adapter. However, the same engine accepts a document that contains its vector, along with a query that passes value.

registerEmbeddingAdapter in TypeScript, register_embedding_adapter in Python and Rust, and RegisterEmbeddingAdapter in Go register an adapter under a name on an open engine. With that call, you can repair such an index in place or swap a model without recreating the index. When the dimensions of an adapter differ from the width of a field that it fills, the engine refuses the registration with EMBEDDING_DIMENSION_MISMATCH before it changes anything. In TypeScript and Go, the engine configuration can also set one default adapter, under embedding in TypeScript and Embedding in Go, which the engine uses for every index whose setting gives no adapter name. The Python package refuses an embedding key in the configuration with CONFIG_INVALID.

Wrap an adapter in a cache

Any object or type that has dimensions and an embed method is a valid adapter. The engine passes each text with a purpose that is either the document purpose or the query purpose, so that an adapter for an asymmetric model can add a different prefix to each. The wrapper in this step stores each vector under its purpose and text, so that the model embeds each distinct text once. In Python, Go, and Rust, the engine can call the adapter from two threads at once, so the wrappers in those languages guard the cache with a lock.

import { createNarsil } from '@delali/narsil'
import { createNarsil, type EmbeddingAdapter } from '@delali/narsil'
import { createTransformersEmbedding } from '@delali/narsil-embeddings-transformers'
 
const embedding = createTransformersEmbedding({ dimensions: 384 })
 
const narsil = await createNarsil({ embeddingAdapters: { 'kitchen-model': embedding } }) 
const cache = new Map<string, Float32Array>() 
let modelCalls = 0
 
const cachedEmbedding: EmbeddingAdapter = {
  dimensions: embedding.dimensions,
  async embed(input, purpose, signal) {
    const key = `${purpose}:${input}`
    const cached = cache.get(key)
    if (cached !== undefined) return cached
    modelCalls += 1
    const vector = await embedding.embed(input, purpose, signal)
    cache.set(key, vector)
    return vector
  },
  shutdown: () => embedding.shutdown(),
}
 
const narsil = await createNarsil({ embeddingAdapters: { 'kitchen-model': cachedEmbedding } })
 
await narsil.createIndex('appliances', {
  schema: { name: 'string', summary: 'string', supplier: 'string', embedding: 'vector[384]' },
  embedding: { adapter: 'kitchen-model', fields: { embedding: ['name', 'summary'] } },
})
 
await narsil.insertBatch('appliances', [
  { id: 'kt-2100', name: 'Stovetop kettle', summary: 'A two-litre enamel kettle that whistles when the water reaches the boil.', supplier: 'kettle-supplier, Kraków' },
  { id: 'gr-4400', name: 'Burr grinder', summary: 'Forty grind settings from espresso to cafetiere, with a stainless steel burr set.', supplier: 'grinder-supplier, Osaka' },
  { id: 'bl-1200', name: 'Counter blender', summary: 'A 1200 watt motor that crushes ice and frozen fruit without stalling.', supplier: 'blender-supplier, Gothenburg' },
  { id: 'tp-0800', name: 'Four-slot toaster', summary: 'Four wide slots with a reheat setting and a removable crumb tray.', supplier: 'toaster-supplier, Enugu' },
  { id: 'sc-3000', name: 'Pressure cooker', summary: 'A six-litre pot that cuts a bean stew from three hours to forty minutes.', supplier: 'cooker-supplier, Medellín' },
  { id: 'mw-5500', name: 'Combination oven', summary: 'A microwave and convection oven in one cabinet, with a browning element.', supplier: 'oven-supplier, Lyon' },
  { id: 'xx-0000', supplier: 'kitchenware-supplier, Surabaya' },
])
 
const results = await narsil.query('appliances', { 
  mode: 'vector',
  vector: { field: 'embedding', text: 'something that makes coffee taste better' },
  limit: 3,
  document: { include: ['name', 'supplier'] },
})
const question = 'something that makes coffee taste better'
const first = await narsil.query('appliances', { mode: 'vector', vector: { field: 'embedding', text: question }, limit: 3 })
const again = await narsil.query('appliances', { mode: 'vector', vector: { field: 'embedding', text: question }, limit: 3 })
const ids = (hits: Array<{ id: string }>): string[] => hits.map((hit) => hit.id)
 
console.log(JSON.stringify(results.hits, (key, value) => (typeof value === 'number' ? Number(value.toFixed(2)) : value), 2)) 
console.log(JSON.stringify({ first: ids(first.hits), again: ids(again.hits), modelCalls, cachedTexts: cache.size }, null, 2)) 
 
await narsil.shutdown()
{
  "first": [
    "gr-4400",
    "bl-1200",
    "sc-3000"
  ],
  "again": [
    "gr-4400",
    "bl-1200",
    "sc-3000"
  ],
  "modelCalls": 7,
  "cachedTexts": 7
}

The model embeds seven texts, one for each of the six appliances and one for the question. For the second query, the wrapper returns the vector from the cache, and the engine returns the same three appliances. The wrapper has no batch method, so the engine calls its embed method once for each document in a batch. When your model embeds a batch faster than the same texts one at a time, give the adapter a batch method as well.

Choose an adapter in TypeScript

The TypeScript packages provide two ready-made adapters. createTransformersEmbedding from @delali/narsil-embeddings-transformers loads a model into your process on its first call, with no API key. The model is Xenova/all-MiniLM-L6-v2 unless you choose another. The adapter loads the model at full precision, fp32, unless you set dtype. Under a quantised dtype such as q8, the adapter downloads a smaller model. Because that model computes one scale for the numbers of a whole batch, the adapter then embeds each text of a batch separately, so that the vector of each text matches the vector that a single call returns. Embedding a batch therefore takes as long as embedding the same texts one at a time. With documentPrefix and queryPrefix, the adapter prepends text for an asymmetric model such as E5 or BGE. With pooling and normalize, you set how the adapter reduces the model's output to one vector.

createOpenAIEmbedding from @delali/narsil/embeddings/openai returns an adapter that calls any endpoint that serves the OpenAI embeddings API. It takes a baseUrl, a model, the dimensions, and an apiKey, which can be a function that the adapter calls before each request. The adapter sends up to 2,048 texts in one request. By default, it retries a 429, 500, 502, 503, or 504 response up to three times, with a delay that roughly doubles each time, and it honours a retry-after header. The adapter ignores purpose, so the model embeds a question and a document in the same way.

Where to go next

  • Read Vector search for the vector field, the similarity floor, and the graph that the engine builds as a field grows.
  • Read Hybrid search for a query in which the engine searches the same index for keywords and for meaning at once.
  • Read Reranking for a second model whose scores the engine uses to reorder the top hits of a search.