---
title: "RAG"
canonical: https://docs.qvac.tether.io/sdk/v0.23/ai-capabilities/rag/
collection: "SDK"
package: "@qvac/sdk"
line: v0.23
current_line: false
---

# RAG (/sdk/v0.23/ai-capabilities/rag)



## Overview

RAG (retrieval-augmented generation) uses [text embeddings](/sdk/v0.23/ai-capabilities/text-embeddings): you embed (vectorize) documents, persist them in a vector store, and later retrieve the most relevant chunks for a query using similarity search.

Compared to generating text embeddings only, the key differences are:

* You must **persist embeddings** (vectors) alongside the original text (and optional metadata) in a vector store.
* At query time, you **embed the query** and run **top‑K** vector search to fetch the most relevant documents/chunks.
* You *typically* pass the retrieved text to [`completion()`](/sdk/v0.23/reference/api#completion) as context to ground the model's answer (this retrieval step is what makes it RAG).

## Functions

1. [`loadModel()`](/sdk/v0.23/reference/api#loadmodel) (with `modelType: "embeddings"`)
2. [`embed()`](/sdk/v0.23/reference/api#embed) — generate vectors
3. Use any combination of the RAG functions below as needed:
   * [`ragChunk()`](/sdk/v0.23/reference/api#ragchunk) — chunk documents
   * [`ragIngest()`](/sdk/v0.23/reference/api#ragingest) — embed and store (requires model)
   * [`ragSaveEmbeddings()`](/sdk/v0.23/reference/api#ragsaveembeddings) — save pre-computed vectors
   * [`ragSearch()`](/sdk/v0.23/reference/api#ragsearch) — query similar documents (requires model)
   * [`ragReindex()`](/sdk/v0.23/reference/api#ragreindex) — optimize search index
   * [`ragDeleteEmbeddings()`](/sdk/v0.23/reference/api#ragdeleteembeddings) — remove documents
   * [`ragListWorkspaces()`](/sdk/v0.23/reference/api#raglistworkspaces) — list workspaces
   * [`ragCloseWorkspace()`](/sdk/v0.23/reference/api#ragcloseworkspace) — release resources
   * [`ragDeleteWorkspace()`](/sdk/v0.23/reference/api#ragdeleteworkspace) — delete workspace and data
   * [`createVectorIndex()`](/sdk/v0.23/reference/api#createvectorindex) — build a TurboVec index over your own documents
   * [`loadVectorIndex()`](/sdk/v0.23/reference/api#loadvectorindex) — reopen a saved TurboVec index
4. [`unloadModel()`](/sdk/v0.23/reference/api#unloadmodel)

For how to use each function, see [SDK — API reference](/sdk/v0.23/reference/api/).

## Pipeline

Create your RAG pipeline using [text embeddings](/sdk/v0.23/ai-capabilities/text-embeddings), the functions above, and [completion](/sdk/v0.23/ai-capabilities/text-generation).

Regarding vector storage, you may use:

* **External vector DB:** use [`embed()`](/sdk/v0.23/reference/api#embed) to generate vectors and store them wherever you want (e.g., MongoDB, LanceDB, ChromaDB, SQLite-Vector). Choose this when you need custom persistence, filtering, or integration with an existing database.
* **Built-in TurboVec index with your own document store:** use [`embed()`](/sdk/v0.23/reference/api#embed) for vectors and [`createVectorIndex()`](/sdk/v0.23/reference/api#createvectorindex) for on-device nearest-neighbour search. QVAC indexes the vectors; your documents stay in whatever store you already have, and results come back as the ids you assigned. Snapshots can be saved and reopened with [`loadVectorIndex()`](/sdk/v0.23/reference/api#loadvectorindex).
* **Built-in vector store:** use the RAG workspace functions ([`ragIngest()`](/sdk/v0.23/reference/api#ragingest), [`ragSearch()`](/sdk/v0.23/reference/api#ragsearch), etc.). QVAC persists the vectors for you, so this is the simplest path.

<Callout type="warn">
  **Built-in vector store is not production grade** and is intended for prototypes only. For production workloads, use one of the external vector DB paths shown below (MongoDB, SQLite, LanceDB, Chroma, etc.).
</Callout>

<Callout type="info">
  **Important:** when using an external vector DB, make sure its schema matches the embedding dimensionality produced by your model (e.g., GTE Large embeddings used in the example are 1024‑dimensional).
</Callout>

## Examples

### Built-in vector store

<Callout type="warn">
  **Prototype only** — for production, prefer an external vector DB (below).
</Callout>

The following script shows how to ingest documents into a built-in RAG workspace with `ragIngest()` and query them with `ragSearch()`, without setting up an external vector DB:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/rag/rag-hyperdb/ingest.js title="rag-managed.js" lineNumbers
      import { loadModel, unloadModel, GTE_LARGE_FP16, ragIngest, ragSearch, ragCloseWorkspace } from '@qvac/sdk';
      try {
          // Get query from command line or use default
          const query = process.argv[2] || 'machine learning algorithms';
          const workspace = 'ingest-example';
          console.log(`▸ Query: "${query}"`);
          const modelId = await loadModel({
              modelSrc: GTE_LARGE_FP16,
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          const samples = [
              'Machine learning is a subset of artificial intelligence that focuses on algorithms that can learn and make predictions from data without being explicitly programmed for every task.',
              'Deep learning uses neural networks with multiple layers to process and learn from complex data patterns, enabling breakthroughs in image recognition and natural language processing.',
              'Natural language processing combines computational linguistics with machine learning to help computers understand, interpret, and generate human language in a meaningful way.',
              'Computer vision enables machines to interpret and understand visual information from the world, using techniques like image classification, object detection, and facial recognition.',
              'Quantum computing leverages quantum mechanical phenomena to process information in fundamentally different ways than classical computers, potentially solving certain problems exponentially faster.',
              'Blockchain technology creates decentralized, immutable ledgers that enable secure peer-to-peer transactions without requiring a central authority or intermediary.',
              'Cloud computing delivers computing services over the internet, allowing users to access resources like storage, processing power, and applications on-demand from anywhere.',
              'Cybersecurity protects digital systems, networks, and data from malicious attacks, unauthorized access, and various forms of cyber threats through multiple layers of defense.'
          ];
          console.log('▸ Ingesting documents...');
          const result = await ragIngest({
              modelId,
              workspace,
              documents: samples,
              chunk: false
          });
          console.log(`▸ Ingested ${result.processed.length} documents`);
          console.log('▸ Searching for similar documents...');
          const results = await ragSearch({
              modelId,
              workspace,
              query,
              topK: 3
          });
          console.log('▸ Top 3 most similar documents:');
          results.forEach((result, index) => {
              console.log(`${index + 1}. (Score: ${result.score})`);
              console.log(`   ${result.content}`);
              console.log();
          });
          // Cleanup: close and delete workspace
          await ragCloseWorkspace({ workspace, deleteOnClose: true });
          console.log(`▸ Deleted '${workspace}' workspace`);
          await unloadModel({ modelId });
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/rag/rag-hyperdb/ingest.ts title="rag-managed.ts" lineNumbers
      import {
        loadModel,
        unloadModel,
        GTE_LARGE_FP16,
        ragIngest,
        ragSearch,
        ragCloseWorkspace
      } from '@qvac/sdk'

      try {
        // Get query from command line or use default
        const query = process.argv[2] || 'machine learning algorithms'
        const workspace = 'ingest-example'

        console.log(`▸ Query: "${query}"`)
        const modelId = await loadModel({
          modelSrc: GTE_LARGE_FP16,
          onProgress: (p) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        const samples = [
          'Machine learning is a subset of artificial intelligence that focuses on algorithms that can learn and make predictions from data without being explicitly programmed for every task.',
          'Deep learning uses neural networks with multiple layers to process and learn from complex data patterns, enabling breakthroughs in image recognition and natural language processing.',
          'Natural language processing combines computational linguistics with machine learning to help computers understand, interpret, and generate human language in a meaningful way.',
          'Computer vision enables machines to interpret and understand visual information from the world, using techniques like image classification, object detection, and facial recognition.',
          'Quantum computing leverages quantum mechanical phenomena to process information in fundamentally different ways than classical computers, potentially solving certain problems exponentially faster.',
          'Blockchain technology creates decentralized, immutable ledgers that enable secure peer-to-peer transactions without requiring a central authority or intermediary.',
          'Cloud computing delivers computing services over the internet, allowing users to access resources like storage, processing power, and applications on-demand from anywhere.',
          'Cybersecurity protects digital systems, networks, and data from malicious attacks, unauthorized access, and various forms of cyber threats through multiple layers of defense.'
        ]

        console.log('▸ Ingesting documents...')
        const result = await ragIngest({
          modelId,
          workspace,
          documents: samples,
          chunk: false
        })
        console.log(`▸ Ingested ${result.processed.length} documents`)

        console.log('▸ Searching for similar documents...')
        const results = await ragSearch({
          modelId,
          workspace,
          query,
          topK: 3
        })

        console.log('▸ Top 3 most similar documents:')
        results.forEach((result, index) => {
          console.log(`${index + 1}. (Score: ${result.score})`)
          console.log(`   ${result.content}`)
          console.log()
        })

        // Cleanup: close and delete workspace
        await ragCloseWorkspace({ workspace, deleteOnClose: true })
        console.log(`▸ Deleted '${workspace}' workspace`)

        await unloadModel({ modelId })
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/rag_managed.py title="rag_managed.py" lineNumbers
      """Python port of packages/sdk/examples/rag/rag-hyperdb/ingest.ts.

      Ingest documents into a built-in RAG workspace and query them with similarity
      search, without setting up an external vector DB.

      `rag` is a generated request-reply method covering every RAG operation: it
      takes a `RagRequest` discriminated by `operation` and returns a `RagResponse`
      (there are no flat `rag_ingest()` / `rag_search()` wrappers like the JS SDK's).
      Both models are re-exported from the flat surface, and each is a union, so the
      operation's own payload sits on the response's `.root`.

      RUN: python examples/rag_managed.py [query]
      """

      from __future__ import annotations

      import asyncio
      import sys

      from tetherto.qvac_sdk import Client, RagRequest, load_model, rag, unload_model
      from tetherto.qvac_sdk.models import GTE_LARGE_FP16


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def main() -> int:
          async with Client() as client:
              t = client.transport
              try:
                  # Get query from command line or use default
                  query = sys.argv[1] if len(sys.argv) > 1 else "machine learning algorithms"
                  workspace = "ingest-example"

                  print(f'▸ Query: "{query}"')
                  model_id = await load_model(
                      t, model_src=GTE_LARGE_FP16, on_progress=print_progress
                  )

                  samples = [
                      "Machine learning is a subset of artificial intelligence that focuses on algorithms that can learn and make predictions from data without being explicitly programmed for every task.",
                      "Deep learning uses neural networks with multiple layers to process and learn from complex data patterns, enabling breakthroughs in image recognition and natural language processing.",
                      "Natural language processing combines computational linguistics with machine learning to help computers understand, interpret, and generate human language in a meaningful way.",
                      "Computer vision enables machines to interpret and understand visual information from the world, using techniques like image classification, object detection, and facial recognition.",
                      "Quantum computing leverages quantum mechanical phenomena to process information in fundamentally different ways than classical computers, potentially solving certain problems exponentially faster.",
                      "Blockchain technology creates decentralized, immutable ledgers that enable secure peer-to-peer transactions without requiring a central authority or intermediary.",
                      "Cloud computing delivers computing services over the internet, allowing users to access resources like storage, processing power, and applications on-demand from anywhere.",
                      "Cybersecurity protects digital systems, networks, and data from malicious attacks, unauthorized access, and various forms of cyber threats through multiple layers of defense.",
                  ]

                  print("▸ Ingesting documents...")
                  ingest = await rag(
                      t,
                      RagRequest.model_validate(
                          {
                              "type": "rag",
                              "operation": "ingest",
                              "modelId": model_id,
                              "workspace": workspace,
                              "documents": samples,
                              "chunk": False,
                          }
                      ),
                  )
                  if not ingest.root.success:
                      raise RuntimeError(ingest.root.error)
                  print(f"▸ Ingested {len(ingest.root.processed)} documents")

                  print("▸ Searching for similar documents...")
                  search = await rag(
                      t,
                      RagRequest.model_validate(
                          {
                              "type": "rag",
                              "operation": "search",
                              "modelId": model_id,
                              "workspace": workspace,
                              "query": query,
                              "topK": 3,
                          }
                      ),
                  )
                  if not search.root.success:
                      raise RuntimeError(search.root.error)

                  print("▸ Top 3 most similar documents:")
                  for index, result in enumerate(search.root.results, start=1):
                      print(f"{index}. (Score: {result.score})")
                      print(f"   {result.content}")
                      print()

                  # Cleanup: close and delete workspace
                  close = await rag(
                      t,
                      RagRequest.model_validate(
                          {
                              "type": "rag",
                              "operation": "closeWorkspace",
                              "workspace": workspace,
                              "deleteOnClose": True,
                          }
                      ),
                  )
                  if not close.root.success:
                      raise RuntimeError(close.root.error)
                  print(f"▸ Deleted '{workspace}' workspace")

                  await unload_model(t, model_id)
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/RagManaged.kt title="RagManaged.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/rag/rag-hyperdb/ingest.ts.
      //
      // Ingest documents into a built-in RAG workspace and query them with similarity
      // search, without setting up an external vector DB.
      //
      // `client.retrieval.execute()` covers every RAG operation. `RagRequest` and
      // `RagResponse` are sealed classes with one variant per operation, so each
      // request names its operation in the type (`RagRequest.Ingest(...)`) and each
      // response is read off the matching variant (`as RagResponse.Ingest`), where
      // the JS SDK has flat `ragIngest()` / `ragSearch()` wrappers.
      //
      // RUN: ./gradlew -p examples run -Pexample=RagManaged --args="[query]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.generated.ModelConstant
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.RagRequest
      import io.tether.qvac.sdk.generated.schema.RagRequestCloseWorkspace
      import io.tether.qvac.sdk.generated.schema.RagRequestIngest
      import io.tether.qvac.sdk.generated.schema.RagRequestIngestDocuments
      import io.tether.qvac.sdk.generated.schema.RagRequestSearch
      import io.tether.qvac.sdk.generated.schema.RagResponse
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.retrieval
      import kotlinx.coroutines.runBlocking

      private val SAMPLES = listOf(
          "Machine learning is a subset of artificial intelligence that focuses on algorithms that can learn and " +
              "make predictions from data without being explicitly programmed for every task.",
          "Deep learning uses neural networks with multiple layers to process and learn from complex data patterns, " +
              "enabling breakthroughs in image recognition and natural language processing.",
          "Natural language processing combines computational linguistics with machine learning to help computers " +
              "understand, interpret, and generate human language in a meaningful way.",
          "Computer vision enables machines to interpret and understand visual information from the world, using " +
              "techniques like image classification, object detection, and facial recognition.",
          "Quantum computing leverages quantum mechanical phenomena to process information in fundamentally different " +
              "ways than classical computers, potentially solving certain problems exponentially faster.",
          "Blockchain technology creates decentralized, immutable ledgers that enable secure peer-to-peer transactions " +
              "without requiring a central authority or intermediary.",
          "Cloud computing delivers computing services over the internet, allowing users to access resources like " +
              "storage, processing power, and applications on-demand from anywhere.",
          "Cybersecurity protects digital systems, networks, and data from malicious attacks, unauthorized access, and " +
              "various forms of cyber threats through multiple layers of defense.",
      )

      fun main(args: Array<String>): Unit = runBlocking {
          // Get query from command line or use default
          val query = args.getOrNull(0) ?: "machine learning algorithms"
          val workspace = "ingest-example"

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              println("▸ Query: \"$query\"")
              val modelId = client.loadWithProgress(Models.GTE_LARGE_FP16)

              println("▸ Ingesting documents...")
              val ingest = client.retrieval.execute(
                  RagRequest.Ingest(
                      RagRequestIngest(
                          modelId = modelId,
                          workspace = workspace,
                          documents = RagRequestIngestDocuments.Variant2(SAMPLES),
                          chunk = false,
                      ),
                  ),
              ) as RagResponse.Ingest
              if (!ingest.value.success) error(ingest.value.error ?: "RAG ingest failed")
              println("▸ Ingested ${ingest.value.processed.size} documents")

              println("▸ Searching for similar documents...")
              val search = client.retrieval.execute(
                  RagRequest.Search(
                      RagRequestSearch(
                          modelId = modelId,
                          workspace = workspace,
                          query = query,
                          topK = 3.0,
                      ),
                  ),
              ) as RagResponse.Search
              if (!search.value.success) error(search.value.error ?: "RAG search failed")

              println("▸ Top 3 most similar documents:")
              search.value.results.forEachIndexed { index, result ->
                  println("${index + 1}. (Score: ${result.score})")
                  println("   ${result.content}")
                  println()
              }

              // Cleanup: close and delete workspace
              val close = client.retrieval.execute(
                  RagRequest.CloseWorkspace(RagRequestCloseWorkspace(workspace = workspace, deleteOnClose = true)),
              ) as RagResponse.CloseWorkspace
              if (!close.value.success) error(close.value.error ?: "RAG closeWorkspace failed")
              println("▸ Deleted '$workspace' workspace")

              client.models.unload(modelId)
          } finally {
              client.close()
          }
      }

      /** Load [model], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(model: ModelConstant): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(model.src, model.engine, model.name).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

<Callout type="info">
  **Swap the backend:** to store the vectors in a TurboVec index instead of the default HyperDB, set `"ragTurbovec": true` in `qvac.config.json`. The RAG API is the same. See [Configuration › `ragTurbovec`](/sdk/v0.23/configuration#options) for details.
</Callout>

### TurboVec index with your own document store

The following script keeps the documents in a plain `Map`, embeds them with `embed()`, and indexes the vectors in a TurboVec index created with `createVectorIndex()`. Search returns the ids you assigned, so the documents can live in any database. The index is saved with `write()` and reopened with `loadVectorIndex()`; only the vectors are stored, never the documents.

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/rag/rag-turbovec.js title="rag-turbovec.js" lineNumbers
      import { createVectorIndex, embed, embedBatch, loadModel, loadVectorIndex, unloadModel, GTE_LARGE_FP16, VectorIndexStorage } from '@qvac/sdk';
      // Retrieval over documents kept in your own store. The SDK holds only the
      // vectors, in a TurboVec index inside the worker; the documents stay in this
      // Map (or any database you choose) and result ids map back to them.
      try {
          const query = process.argv[2] || 'Which moon has methane rain and lakes?';
          console.log(`▸ Query: "${query}"`);
          const documents = new Map([
              ['1', 'Saturn moon Titan has lakes, clouds, and rain made of liquid methane.'],
              ['2', 'Solar panels convert sunlight into electricity using photovoltaic cells.'],
              ['3', 'Honeybees communicate the location of flowers through a waggle dance.'],
              ['4', 'The Pacific Ocean is the largest and deepest ocean on Earth.']
          ]);
          const modelId = await loadModel({
              modelSrc: GTE_LARGE_FP16,
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log('▸ Embedding documents...');
          const { embedding: vectors } = await embedBatch({ modelId, inputs: [...documents.values()] });
          console.log('▸ Building the vector index...');
          const index = await createVectorIndex({
              dim: vectors[0].length,
              storage: VectorIndexStorage.TURBOVEC_Q4
          });
          await index.add({ ids: [...documents.keys()], vectors });
          console.log(`▸ Indexed ${index.length} vectors of dimension ${index.dim}`);
          console.log('▸ Searching...');
          const { embedding: queryVector } = await embed({ modelId, text: query });
          const hits = await index.search({ query: queryVector, k: 2 });
          console.log('▸ Top matches:');
          for (const hit of hits) {
              console.log(`  score=${hit.score.toFixed(4)} id=${hit.id}: ${documents.get(hit.id)}`);
          }
          // Snapshots persist the vectors only. A relative path resolves under the
          // QVAC data directory; pass an absolute path to store it elsewhere.
          const snapshotPath = 'examples/rag-turbovec.qvi';
          const { path: writtenPath } = await index.write({ path: snapshotPath });
          await index.dispose();
          console.log(`▸ Snapshot written to ${writtenPath}`);
          const reloaded = await loadVectorIndex({ path: snapshotPath });
          const [reloadedBest] = await reloaded.search({ query: queryVector, k: 1 });
          await reloaded.dispose();
          if (!reloadedBest || reloadedBest.id !== hits[0]?.id) {
              throw new Error(`Reloaded index returned id=${reloadedBest?.id} but the original returned id=${hits[0]?.id}`);
          }
          console.log(`▸ Reloaded index agrees: best match id=${reloadedBest.id}`);
          await unloadModel({ modelId });
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/rag/rag-turbovec.ts title="rag-turbovec.ts" lineNumbers
      import {
        createVectorIndex,
        embed,
        embedBatch,
        loadModel,
        loadVectorIndex,
        unloadModel,
        GTE_LARGE_FP16,
        VectorIndexStorage
      } from '@qvac/sdk'

      // Retrieval over documents kept in your own store. The SDK holds only the
      // vectors, in a TurboVec index inside the worker; the documents stay in this
      // Map (or any database you choose) and result ids map back to them.
      try {
        const query = process.argv[2] || 'Which moon has methane rain and lakes?'
        console.log(`▸ Query: "${query}"`)

        const documents = new Map<string, string>([
          ['1', 'Saturn moon Titan has lakes, clouds, and rain made of liquid methane.'],
          ['2', 'Solar panels convert sunlight into electricity using photovoltaic cells.'],
          ['3', 'Honeybees communicate the location of flowers through a waggle dance.'],
          ['4', 'The Pacific Ocean is the largest and deepest ocean on Earth.']
        ])

        const modelId = await loadModel({
          modelSrc: GTE_LARGE_FP16,
          onProgress: (p) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        console.log('▸ Embedding documents...')
        const { embedding: vectors } = await embedBatch({ modelId, inputs: [...documents.values()] })

        console.log('▸ Building the vector index...')
        const index = await createVectorIndex({
          dim: vectors[0]!.length,
          storage: VectorIndexStorage.TURBOVEC_Q4
        })
        await index.add({ ids: [...documents.keys()], vectors })
        console.log(`▸ Indexed ${index.length} vectors of dimension ${index.dim}`)

        console.log('▸ Searching...')
        const { embedding: queryVector } = await embed({ modelId, text: query })
        const hits = await index.search({ query: queryVector, k: 2 })
        console.log('▸ Top matches:')
        for (const hit of hits) {
          console.log(`  score=${hit.score.toFixed(4)} id=${hit.id}: ${documents.get(hit.id)}`)
        }

        // Snapshots persist the vectors only. A relative path resolves under the
        // QVAC data directory; pass an absolute path to store it elsewhere.
        const snapshotPath = 'examples/rag-turbovec.qvi'
        const { path: writtenPath } = await index.write({ path: snapshotPath })
        await index.dispose()
        console.log(`▸ Snapshot written to ${writtenPath}`)

        const reloaded = await loadVectorIndex({ path: snapshotPath })
        const [reloadedBest] = await reloaded.search({ query: queryVector, k: 1 })
        await reloaded.dispose()
        if (!reloadedBest || reloadedBest.id !== hits[0]?.id) {
          throw new Error(
            `Reloaded index returned id=${reloadedBest?.id} but the original returned id=${hits[0]?.id}`
          )
        }
        console.log(`▸ Reloaded index agrees: best match id=${reloadedBest.id}`)

        await unloadModel({ modelId })
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/rag_turbovec.py title="rag_turbovec.py" lineNumbers
      """Python port of packages/sdk/examples/rag/rag-turbovec.ts.

      Retrieval over documents kept in your own store. The SDK holds only the
      vectors, in a TurboVec index inside the worker; the documents stay in this dict
      (or any database you choose) and result ids map back to them.

      `vector_index` is a generated request-reply method covering every index
      operation. Where the JS SDK hands back an index object with `add`/`search`/
      `write`/`dispose` methods, `create` here returns an `indexId` that every later
      operation carries. `search` is batched: it takes `queries` and returns one
      result list per query. `VectorIndexStorage` is a plain enum, so pass its
      `.value` — the wire contract takes the string.

      RUN: python examples/rag_turbovec.py [query]
      """

      from __future__ import annotations

      import asyncio
      import sys

      from tetherto.qvac_sdk import (
          Client,
          EmbedRequest,
          VectorIndexRequest,
          VectorIndexStorage,
          embed,
          load_model,
          unload_model,
          vector_index,
      )
      from tetherto.qvac_sdk.models import GTE_LARGE_FP16


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def embed_text(t, model_id, text):
          """Embed one string or a list of strings; returns the vector(s)."""
          response = await embed(
              t,
              EmbedRequest.model_validate(
                  {"type": "embed", "modelId": model_id, "text": text}
              ),
          )
          if not response.success:
              raise RuntimeError(response.error)
          return response.embedding


      async def main() -> int:
          async with Client() as client:
              t = client.transport
              try:
                  query = (
                      sys.argv[1]
                      if len(sys.argv) > 1
                      else "Which moon has methane rain and lakes?"
                  )
                  print(f'▸ Query: "{query}"')

                  # Ids are numeric by contract, so keep your own id as the key and
                  # let the index hold only the numeric handle plus the vector.
                  documents = {
                      "1": "Saturn moon Titan has lakes, clouds, and rain made of liquid methane.",
                      "2": "Solar panels convert sunlight into electricity using photovoltaic cells.",
                      "3": "Honeybees communicate the location of flowers through a waggle dance.",
                      "4": "The Pacific Ocean is the largest and deepest ocean on Earth.",
                  }

                  model_id = await load_model(
                      t, model_src=GTE_LARGE_FP16, on_progress=print_progress
                  )

                  print("▸ Embedding documents...")
                  vectors = await embed_text(t, model_id, list(documents.values()))

                  print("▸ Building the vector index...")
                  created = await vector_index(
                      t,
                      VectorIndexRequest.model_validate(
                          {
                              "type": "vectorIndex",
                              "operation": "create",
                              "dim": len(vectors[0]),
                              "storage": VectorIndexStorage.turbovec_q4.value,
                          }
                      ),
                  )
                  index_id = created.root.index_id
                  added = await vector_index(
                      t,
                      VectorIndexRequest.model_validate(
                          {
                              "type": "vectorIndex",
                              "operation": "add",
                              "indexId": index_id,
                              "ids": list(documents.keys()),
                              "vectors": vectors,
                          }
                      ),
                  )
                  print(
                      f"▸ Indexed {added.root.length} vectors of dimension {created.root.dim}"
                  )

                  print("▸ Searching...")
                  query_vector = await embed_text(t, model_id, query)
                  found = await vector_index(
                      t,
                      VectorIndexRequest.model_validate(
                          {
                              "type": "vectorIndex",
                              "operation": "search",
                              "indexId": index_id,
                              "queries": [query_vector],
                              "k": 2,
                          }
                      ),
                  )
                  hits = found.root.results[0]
                  print("▸ Top matches:")
                  for hit in hits:
                      print(f"  score={hit.score:.4f} id={hit.id}: {documents[hit.id]}")

                  # Snapshots persist the vectors only. A relative path resolves under
                  # the QVAC data directory; pass an absolute path to store it elsewhere.
                  snapshot_path = "examples/rag_turbovec.qvi"
                  written = await vector_index(
                      t,
                      VectorIndexRequest.model_validate(
                          {
                              "type": "vectorIndex",
                              "operation": "write",
                              "indexId": index_id,
                              "path": snapshot_path,
                          }
                      ),
                  )
                  await vector_index(
                      t,
                      VectorIndexRequest.model_validate(
                          {
                              "type": "vectorIndex",
                              "operation": "dispose",
                              "indexId": index_id,
                          }
                      ),
                  )
                  print(f"▸ Snapshot written to {written.root.path}")

                  reloaded = await vector_index(
                      t,
                      VectorIndexRequest.model_validate(
                          {
                              "type": "vectorIndex",
                              "operation": "load",
                              "path": snapshot_path,
                          }
                      ),
                  )
                  reloaded_id = reloaded.root.index_id
                  reloaded_found = await vector_index(
                      t,
                      VectorIndexRequest.model_validate(
                          {
                              "type": "vectorIndex",
                              "operation": "search",
                              "indexId": reloaded_id,
                              "queries": [query_vector],
                              "k": 1,
                          }
                      ),
                  )
                  reloaded_hits = reloaded_found.root.results[0]
                  reloaded_best = reloaded_hits[0] if reloaded_hits else None
                  await vector_index(
                      t,
                      VectorIndexRequest.model_validate(
                          {
                              "type": "vectorIndex",
                              "operation": "dispose",
                              "indexId": reloaded_id,
                          }
                      ),
                  )
                  best = hits[0] if hits else None
                  if reloaded_best is None or best is None or reloaded_best.id != best.id:
                      raise RuntimeError(
                          f"Reloaded index returned id="
                          f"{reloaded_best.id if reloaded_best else None} but the "
                          f"original returned id={best.id if best else None}"
                      )
                  print(f"▸ Reloaded index agrees: best match id={reloaded_best.id}")

                  await unload_model(t, model_id)
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/RagTurbovec.kt title="RagTurbovec.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/rag/rag-turbovec.ts.
      //
      // Retrieval over documents kept in your own store. The SDK holds only the
      // vectors, in a TurboVec index inside the worker; the documents stay in this
      // map (or any database you choose) and result ids map back to them.
      //
      // `client.vectorIndex()` is the generated method covering every index
      // operation. Where the JS SDK hands back an index object with `add`/`search`/
      // `write`/`dispose` methods, `create` here returns an `indexId` that every later
      // operation carries. `VectorIndexRequest` and `VectorIndexResponse` are sealed
      // classes with one variant per operation, so each response is read off the
      // matching variant. `search` is batched: it takes `queries` and returns one
      // result list per query. `client.embeddings.embed()` has a single-text overload
      // returning one vector and a list overload returning one vector per text.
      //
      // RUN: ./gradlew -p examples run -Pexample=RagTurbovec --args="[query]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.embeddings
      import io.tether.qvac.sdk.generated.ModelConstant
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.generated.schema.VectorId
      import io.tether.qvac.sdk.generated.schema.VectorIndexRequest
      import io.tether.qvac.sdk.generated.schema.VectorIndexRequestAdd
      import io.tether.qvac.sdk.generated.schema.VectorIndexRequestCreate
      import io.tether.qvac.sdk.generated.schema.VectorIndexRequestCreateStorage
      import io.tether.qvac.sdk.generated.schema.VectorIndexRequestDispose
      import io.tether.qvac.sdk.generated.schema.VectorIndexRequestLoad
      import io.tether.qvac.sdk.generated.schema.VectorIndexRequestSearch
      import io.tether.qvac.sdk.generated.schema.VectorIndexRequestWrite
      import io.tether.qvac.sdk.generated.schema.VectorIndexResponse
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.vectorIndex
      import kotlinx.coroutines.runBlocking

      fun main(args: Array<String>): Unit = runBlocking {
          val query = args.getOrNull(0) ?: "Which moon has methane rain and lakes?"
          println("▸ Query: \"$query\"")

          // Ids are numeric by contract, so keep your own id as the key and let the
          // index hold only the numeric handle plus the vector.
          val documents = mapOf(
              "1" to "Saturn moon Titan has lakes, clouds, and rain made of liquid methane.",
              "2" to "Solar panels convert sunlight into electricity using photovoltaic cells.",
              "3" to "Honeybees communicate the location of flowers through a waggle dance.",
              "4" to "The Pacific Ocean is the largest and deepest ocean on Earth.",
          )

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              val modelId = client.loadWithProgress(Models.GTE_LARGE_FP16)

              println("▸ Embedding documents...")
              val vectors = client.embeddings.embed(modelId, documents.values.toList())

              println("▸ Building the vector index...")
              val created = client.vectorIndex(
                  VectorIndexRequest.Create(
                      VectorIndexRequestCreate(
                          dim = vectors[0].size.toLong(),
                          storage = VectorIndexRequestCreateStorage.TURBOVECQ4,
                      ),
                  ),
              ) as VectorIndexResponse.Create
              val indexId = created.value.indexId
              val added = client.vectorIndex(
                  VectorIndexRequest.Add(
                      VectorIndexRequestAdd(
                          indexId = indexId,
                          ids = documents.keys.map { VectorId.Variant1(it) },
                          vectors = vectors,
                      ),
                  ),
              ) as VectorIndexResponse.Add
              println("▸ Indexed ${added.value.length} vectors of dimension ${created.value.dim}")

              println("▸ Searching...")
              val queryVector = client.embeddings.embed(modelId, query)
              val found = client.vectorIndex(
                  VectorIndexRequest.Search(
                      VectorIndexRequestSearch(indexId = indexId, queries = listOf(queryVector), k = 2),
                  ),
              ) as VectorIndexResponse.Search
              val hits = found.value.results[0]
              println("▸ Top matches:")
              for (hit in hits) {
                  println("  score=%.4f id=%s: %s".format(hit.score, hit.id, documents[hit.id]))
              }

              // Snapshots persist the vectors only. A relative path resolves under the
              // QVAC data directory; pass an absolute path to store it elsewhere.
              val snapshotPath = "examples/RagTurbovec.qvi"
              val written = client.vectorIndex(
                  VectorIndexRequest.Write(VectorIndexRequestWrite(indexId = indexId, path = snapshotPath)),
              ) as VectorIndexResponse.Write
              client.vectorIndex(VectorIndexRequest.Dispose(VectorIndexRequestDispose(indexId = indexId)))
              println("▸ Snapshot written to ${written.value.path}")

              val reloaded = client.vectorIndex(
                  VectorIndexRequest.Load(VectorIndexRequestLoad(path = snapshotPath)),
              ) as VectorIndexResponse.Load
              val reloadedId = reloaded.value.indexId
              val reloadedFound = client.vectorIndex(
                  VectorIndexRequest.Search(
                      VectorIndexRequestSearch(indexId = reloadedId, queries = listOf(queryVector), k = 1),
                  ),
              ) as VectorIndexResponse.Search
              val reloadedBest = reloadedFound.value.results[0].firstOrNull()
              client.vectorIndex(VectorIndexRequest.Dispose(VectorIndexRequestDispose(indexId = reloadedId)))
              val best = hits.firstOrNull()
              if (reloadedBest == null || best == null || reloadedBest.id != best.id) {
                  error("Reloaded index returned id=${reloadedBest?.id} but the original returned id=${best?.id}")
              }
              println("▸ Reloaded index agrees: best match id=${reloadedBest.id}")

              client.models.unload(modelId)
          } finally {
              client.close()
          }
      }

      /** Load [model], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(model: ModelConstant): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(model.src, model.engine, model.name).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

<Callout type="info">
  TurboVec quantises vectors (`VectorIndexStorage.TURBOVEC_Q4` by default, `TURBOVEC_Q2` for half the memory) and needs a dimension divisible by 8 and no greater than 1024. `GTE_LARGE_FP16` produces 1024-dimensional vectors and fits. Search uses dot products, so L2-normalise vectors when you need cosine similarity. The index lives in the SDK worker; after a worker restart, reopen it from the snapshot.
</Callout>

### External vector DB

#### MongoDB

This example needs two things the SDK does not provide: a MongoDB driver, and a deployment with Atlas Vector Search. Install the driver for the language you are using — `npm i "mongodb@^7.5.0"` for JavaScript and TypeScript, or `pip install "pymongo>=4.13"` for Python. Those are the versions these docs are tested against.

One way to get a deployment is the Atlas local container:

```bash
docker run -p 27017:27017 --name atlas-local mongodb/mongodb-atlas-local
```

The script connects to `mongodb://localhost:27017/?directConnection=true`; edit that connection string if your deployment lives elsewhere.

The following script stores each document in MongoDB alongside its vector, builds a vector search index over it, and retrieves matches with a `$vectorSearch` aggregation that [pre-filters](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage/#pre-filter-search-data) by category:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/rag/rag-mongodb.js title="rag-mongodb.js" lineNumbers
      import { embed, loadModel, unloadModel, GTE_LARGE_FP16 } from '@qvac/sdk';
      import { MongoClient } from 'mongodb';
      const INDEX_NAME = 'documents_vector_index';
      const MONGODB_SETUP_INSTRUCTIONS = `
      ▸ This example needs a MongoDB deployment with Atlas Vector Search.

      One way to get one is to run it in Docker:

         docker run -p 27017:27017 --name atlas-local mongodb/mongodb-atlas-local

      For more details, visit: https://www.mongodb.com/docs/atlas/cli/current/atlas-cli-deploy-docker/
      `;
      async function initializeMongoClient() {
          // Replace with your own deployment's connection string if it is not the Docker one
          // https://www.mongodb.com/docs/manual/reference/connection-string/
          const client = new MongoClient('mongodb://localhost:27017/?directConnection=true');
          try {
              await client.connect();
              await client.db('admin').command({ ping: 1 });
              console.log('▸ Connected to MongoDB server');
              return client;
          }
          catch {
              console.error('✖ Failed to connect to MongoDB server');
              console.error('▸ Please ensure the server is running on localhost:27017');
              console.error(MONGODB_SETUP_INSTRUCTIONS);
              process.exit(1);
          }
      }
      function wait(ms) {
          return new Promise((resolve) => setTimeout(resolve, ms));
      }
      try {
          // Get query and category from command line or use defaults
          const query = process.argv[2] || 'machine learning algorithms';
          const category = process.argv[3] || 'ai';
          console.log(`▸ Query: "${query}" (category: "${category}")`);
          const client = await initializeMongoClient();
          const collection = client.db('qvac').collection('documents');
          const modelId = await loadModel({
              modelSrc: GTE_LARGE_FP16,
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          // Sample corpus, each document tagged with a category to filter on
          const samples = [
              {
                  id: 1,
                  category: 'ai',
                  text: 'Machine learning is a subset of artificial intelligence that focuses on algorithms that can learn and make predictions from data without being explicitly programmed for every task.'
              },
              {
                  id: 2,
                  category: 'ai',
                  text: 'Deep learning uses neural networks with multiple layers to process and learn from complex data patterns, enabling breakthroughs in image recognition and natural language processing.'
              },
              {
                  id: 3,
                  category: 'ai',
                  text: 'Natural language processing combines computational linguistics with machine learning to help computers understand, interpret, and generate human language in a meaningful way.'
              },
              {
                  id: 4,
                  category: 'ai',
                  text: 'Computer vision enables machines to interpret and understand visual information from the world, using techniques like image classification, object detection, and facial recognition.'
              },
              {
                  id: 5,
                  category: 'computing',
                  text: 'Quantum computing leverages quantum mechanical phenomena to process information in fundamentally different ways than classical computers, potentially solving certain problems exponentially faster.'
              },
              {
                  id: 6,
                  category: 'security',
                  text: 'Blockchain technology creates decentralized, immutable ledgers that enable secure peer-to-peer transactions without requiring a central authority or intermediary.'
              },
              {
                  id: 7,
                  category: 'computing',
                  text: 'Cloud computing delivers computing services over the internet, allowing users to access resources like storage, processing power, and applications on-demand from anywhere.'
              },
              {
                  id: 8,
                  category: 'security',
                  text: 'Cybersecurity protects digital systems, networks, and data from malicious attacks, unauthorized access, and various forms of cyber threats through multiple layers of defense.'
              }
          ];
          // (Re)create the collection
          try {
              await collection.drop();
          }
          catch (e) {
              console.warn(`▸ Collection didn't exist, no need to drop: ${String(e)}`);
          }
          // Embed and store documents
          console.log('▸ Embedding documents...');
          const documents = [];
          for (const sample of samples) {
              const { embedding } = await embed({ modelId, text: sample.text });
              documents.push({
                  id: sample.id,
                  category: sample.category,
                  text: sample.text,
                  embedding
              });
          }
          await collection.insertMany(documents);
          // numDimensions is fixed at index creation and must match the model: GTE Large is 1024
          console.log('▸ Creating vector search index...');
          await collection.createSearchIndex({
              name: INDEX_NAME,
              type: 'vectorSearch',
              definition: {
                  fields: [
                      {
                          type: 'vector',
                          path: 'embedding',
                          numDimensions: 1024,
                          similarity: 'cosine'
                      },
                      // A field must be indexed as a filter to be usable in a $vectorSearch filter
                      {
                          type: 'filter',
                          path: 'category'
                      }
                  ]
              }
          });
          // Index builds are asynchronous; querying too early returns no matches
          for (let attempt = 0; attempt < 60; attempt++) {
              const [index] = (await collection.listSearchIndexes(INDEX_NAME).toArray());
              if (index?.queryable)
                  break;
              if (attempt === 59)
                  throw new Error(`Index ${INDEX_NAME} did not become queryable`);
              await wait(1000);
          }
          console.log('▸ Searching for similar documents...');
          const { embedding: queryEmbedding } = await embed({ modelId, text: query });
          const results = await collection
              .aggregate([
              {
                  $vectorSearch: {
                      index: INDEX_NAME,
                      path: 'embedding',
                      queryVector: queryEmbedding,
                      filter: { category: { $eq: category } },
                      numCandidates: 100,
                      limit: 3
                  }
              },
              {
                  $project: {
                      _id: 0,
                      id: 1,
                      category: 1,
                      text: 1,
                      score: { $meta: 'vectorSearchScore' }
                  }
              }
          ])
              .toArray();
          console.log('▸ Top 3 most similar documents:');
          results.forEach((result, index) => {
              console.log(`${index + 1}. (Score: ${result.score.toFixed(4)}, Category: ${result.category})`);
              console.log(`   ${result.text}`);
              console.log();
          });
          await unloadModel({ modelId });
          await client.close();
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/rag/rag-mongodb.ts title="rag-mongodb.ts" lineNumbers
      import { embed, loadModel, unloadModel, GTE_LARGE_FP16 } from '@qvac/sdk'
      import { MongoClient } from 'mongodb'

      const INDEX_NAME = 'documents_vector_index'

      const MONGODB_SETUP_INSTRUCTIONS = `
      ▸ This example needs a MongoDB deployment with Atlas Vector Search.

      One way to get one is to run it in Docker:

         docker run -p 27017:27017 --name atlas-local mongodb/mongodb-atlas-local

      For more details, visit: https://www.mongodb.com/docs/atlas/cli/current/atlas-cli-deploy-docker/
      `

      async function initializeMongoClient() {
        // Replace with your own deployment's connection string if it is not the Docker one
        // https://www.mongodb.com/docs/manual/reference/connection-string/
        const client = new MongoClient('mongodb://localhost:27017/?directConnection=true')

        try {
          await client.connect()
          await client.db('admin').command({ ping: 1 })
          console.log('▸ Connected to MongoDB server')
          return client
        } catch {
          console.error('✖ Failed to connect to MongoDB server')
          console.error('▸ Please ensure the server is running on localhost:27017')
          console.error(MONGODB_SETUP_INSTRUCTIONS)
          process.exit(1)
        }
      }

      function wait(ms: number) {
        return new Promise((resolve) => setTimeout(resolve, ms))
      }

      try {
        // Get query and category from command line or use defaults
        const query = process.argv[2] || 'machine learning algorithms'
        const category = process.argv[3] || 'ai'
        console.log(`▸ Query: "${query}" (category: "${category}")`)

        const client = await initializeMongoClient()
        const collection = client.db('qvac').collection('documents')

        const modelId = await loadModel({
          modelSrc: GTE_LARGE_FP16,
          onProgress: (p) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        // Sample corpus, each document tagged with a category to filter on
        const samples = [
          {
            id: 1,
            category: 'ai',
            text: 'Machine learning is a subset of artificial intelligence that focuses on algorithms that can learn and make predictions from data without being explicitly programmed for every task.'
          },
          {
            id: 2,
            category: 'ai',
            text: 'Deep learning uses neural networks with multiple layers to process and learn from complex data patterns, enabling breakthroughs in image recognition and natural language processing.'
          },
          {
            id: 3,
            category: 'ai',
            text: 'Natural language processing combines computational linguistics with machine learning to help computers understand, interpret, and generate human language in a meaningful way.'
          },
          {
            id: 4,
            category: 'ai',
            text: 'Computer vision enables machines to interpret and understand visual information from the world, using techniques like image classification, object detection, and facial recognition.'
          },
          {
            id: 5,
            category: 'computing',
            text: 'Quantum computing leverages quantum mechanical phenomena to process information in fundamentally different ways than classical computers, potentially solving certain problems exponentially faster.'
          },
          {
            id: 6,
            category: 'security',
            text: 'Blockchain technology creates decentralized, immutable ledgers that enable secure peer-to-peer transactions without requiring a central authority or intermediary.'
          },
          {
            id: 7,
            category: 'computing',
            text: 'Cloud computing delivers computing services over the internet, allowing users to access resources like storage, processing power, and applications on-demand from anywhere.'
          },
          {
            id: 8,
            category: 'security',
            text: 'Cybersecurity protects digital systems, networks, and data from malicious attacks, unauthorized access, and various forms of cyber threats through multiple layers of defense.'
          }
        ]

        // (Re)create the collection
        try {
          await collection.drop()
        } catch (e) {
          console.warn(`▸ Collection didn't exist, no need to drop: ${String(e)}`)
        }

        // Embed and store documents
        console.log('▸ Embedding documents...')
        const documents = []
        for (const sample of samples) {
          const { embedding } = await embed({ modelId, text: sample.text })
          documents.push({
            id: sample.id,
            category: sample.category,
            text: sample.text,
            embedding
          })
        }

        await collection.insertMany(documents)

        // numDimensions is fixed at index creation and must match the model: GTE Large is 1024
        console.log('▸ Creating vector search index...')
        await collection.createSearchIndex({
          name: INDEX_NAME,
          type: 'vectorSearch',
          definition: {
            fields: [
              {
                type: 'vector',
                path: 'embedding',
                numDimensions: 1024,
                similarity: 'cosine'
              },
              // A field must be indexed as a filter to be usable in a $vectorSearch filter
              {
                type: 'filter',
                path: 'category'
              }
            ]
          }
        })

        // Index builds are asynchronous; querying too early returns no matches
        for (let attempt = 0; attempt < 60; attempt++) {
          const [index] = (await collection.listSearchIndexes(INDEX_NAME).toArray()) as {
            queryable?: boolean
          }[]
          if (index?.queryable) break
          if (attempt === 59) throw new Error(`Index ${INDEX_NAME} did not become queryable`)
          await wait(1000)
        }

        console.log('▸ Searching for similar documents...')
        const { embedding: queryEmbedding } = await embed({ modelId, text: query })

        const results = await collection
          .aggregate<{ id: number; category: string; text: string; score: number }>([
            {
              $vectorSearch: {
                index: INDEX_NAME,
                path: 'embedding',
                queryVector: queryEmbedding,
                filter: { category: { $eq: category } },
                numCandidates: 100,
                limit: 3
              }
            },
            {
              $project: {
                _id: 0,
                id: 1,
                category: 1,
                text: 1,
                score: { $meta: 'vectorSearchScore' }
              }
            }
          ])
          .toArray()

        console.log('▸ Top 3 most similar documents:')
        results.forEach((result, index) => {
          console.log(`${index + 1}. (Score: ${result.score.toFixed(4)}, Category: ${result.category})`)
          console.log(`   ${result.text}`)
          console.log()
        })

        await unloadModel({ modelId })
        await client.close()
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/rag_mongodb.py title="rag_mongodb.py" lineNumbers
      """Python port of packages/sdk/examples/rag/rag-mongodb.ts.

      Store each document in MongoDB alongside its vector, build a vector search
      index over it, and retrieve matches with a `$vectorSearch` aggregation that
      pre-filters by category.

      Needs the MongoDB driver (`pip install pymongo`) and a deployment with Atlas
      Vector Search. QVAC only produces the vectors through `embed`; the storage,
      indexing and search all belong to MongoDB.

      The driver's asyncio API mirrors the JS one closely: `AsyncMongoClient`, and
      every collection call awaited. Two differences worth knowing: `drop()` is
      idempotent (the driver allows "ns not found"), so dropping a collection that
      was never created needs no guard, and the index-build poll sleeps with
      `asyncio.sleep` instead of a hand-rolled promise timer.

      RUN: python examples/rag_mongodb.py [query] [category]
      """

      from __future__ import annotations

      import asyncio
      import sys

      from tetherto.qvac_sdk import Client, EmbedRequest, embed, load_model, unload_model
      from tetherto.qvac_sdk.models import GTE_LARGE_FP16

      INDEX_NAME = "documents_vector_index"

      MONGODB_SETUP_INSTRUCTIONS = """
      ▸ This example needs a MongoDB deployment with Atlas Vector Search.

      One way to get one is to run it in Docker:

         docker run -p 27017:27017 --name atlas-local mongodb/mongodb-atlas-local

      For more details, visit: https://www.mongodb.com/docs/atlas/cli/current/atlas-cli-deploy-docker/
      """


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def embed_text(t, model_id, text):
          """Embed one string or a list of strings; returns the vector(s)."""
          response = await embed(
              t,
              EmbedRequest.model_validate(
                  {"type": "embed", "modelId": model_id, "text": text}
              ),
          )
          if not response.success:
              raise RuntimeError(response.error)
          return response.embedding


      async def main() -> int:
          try:
              from pymongo import AsyncMongoClient
              from pymongo.errors import PyMongoError
              from pymongo.operations import SearchIndexModel
          except ImportError:
              print("✖ This example needs pymongo: pip install pymongo", file=sys.stderr)
              return 1

          # Get query and category from command line or use defaults
          query = sys.argv[1] if len(sys.argv) > 1 else "machine learning algorithms"
          category = sys.argv[2] if len(sys.argv) > 2 else "ai"
          print(f'▸ Query: "{query}" (category: "{category}")')

          # Replace with your own deployment's connection string if it is not the Docker one
          # https://www.mongodb.com/docs/manual/reference/connection-string/
          mongo = AsyncMongoClient("mongodb://localhost:27017/?directConnection=true")
          try:
              await mongo.admin.command("ping")
              print("▸ Connected to MongoDB server")
          except PyMongoError:
              print("✖ Failed to connect to MongoDB server", file=sys.stderr)
              print(
                  "▸ Please ensure the server is running on localhost:27017", file=sys.stderr
              )
              print(MONGODB_SETUP_INSTRUCTIONS, file=sys.stderr)
              await mongo.close()
              return 1

          collection = mongo["qvac"]["documents"]

          try:
              async with Client() as client:
                  t = client.transport
                  model_id = await load_model(
                      t, model_src=GTE_LARGE_FP16, on_progress=print_progress
                  )

                  # Sample corpus, each document tagged with a category to filter on
                  samples = [
                      {
                          "id": 1,
                          "category": "ai",
                          "text": "Machine learning is a subset of artificial intelligence that focuses on algorithms that can learn and make predictions from data without being explicitly programmed for every task.",
                      },
                      {
                          "id": 2,
                          "category": "ai",
                          "text": "Deep learning uses neural networks with multiple layers to process and learn from complex data patterns, enabling breakthroughs in image recognition and natural language processing.",
                      },
                      {
                          "id": 3,
                          "category": "ai",
                          "text": "Natural language processing combines computational linguistics with machine learning to help computers understand, interpret, and generate human language in a meaningful way.",
                      },
                      {
                          "id": 4,
                          "category": "ai",
                          "text": "Computer vision enables machines to interpret and understand visual information from the world, using techniques like image classification, object detection, and facial recognition.",
                      },
                      {
                          "id": 5,
                          "category": "computing",
                          "text": "Quantum computing leverages quantum mechanical phenomena to process information in fundamentally different ways than classical computers, potentially solving certain problems exponentially faster.",
                      },
                      {
                          "id": 6,
                          "category": "security",
                          "text": "Blockchain technology creates decentralized, immutable ledgers that enable secure peer-to-peer transactions without requiring a central authority or intermediary.",
                      },
                      {
                          "id": 7,
                          "category": "computing",
                          "text": "Cloud computing delivers computing services over the internet, allowing users to access resources like storage, processing power, and applications on-demand from anywhere.",
                      },
                      {
                          "id": 8,
                          "category": "security",
                          "text": "Cybersecurity protects digital systems, networks, and data from malicious attacks, unauthorized access, and various forms of cyber threats through multiple layers of defense.",
                      },
                  ]

                  # (Re)create the collection. The driver allows "ns not found", so
                  # this is a no-op the first time round.
                  await collection.drop()

                  # Embed and store documents
                  print("▸ Embedding documents...")
                  documents = []
                  for sample in samples:
                      embedding = await embed_text(t, model_id, sample["text"])
                      documents.append(
                          {
                              "id": sample["id"],
                              "category": sample["category"],
                              "text": sample["text"],
                              "embedding": embedding,
                          }
                      )

                  await collection.insert_many(documents)

                  # numDimensions is fixed at index creation and must match the model:
                  # GTE Large is 1024
                  print("▸ Creating vector search index...")
                  await collection.create_search_index(
                      SearchIndexModel(
                          name=INDEX_NAME,
                          type="vectorSearch",
                          definition={
                              "fields": [
                                  {
                                      "type": "vector",
                                      "path": "embedding",
                                      "numDimensions": 1024,
                                      "similarity": "cosine",
                                  },
                                  # A field must be indexed as a filter to be usable
                                  # in a $vectorSearch filter
                                  {"type": "filter", "path": "category"},
                              ]
                          },
                      )
                  )

                  # Index builds are asynchronous; querying too early returns no matches
                  for attempt in range(60):
                      cursor = await collection.list_search_indexes(INDEX_NAME)
                      indexes = await cursor.to_list()
                      if indexes and indexes[0].get("queryable"):
                          break
                      if attempt == 59:
                          raise RuntimeError(f"Index {INDEX_NAME} did not become queryable")
                      await asyncio.sleep(1)

                  print("▸ Searching for similar documents...")
                  query_vector = await embed_text(t, model_id, query)

                  cursor = await collection.aggregate(
                      [
                          {
                              "$vectorSearch": {
                                  "index": INDEX_NAME,
                                  "path": "embedding",
                                  "queryVector": query_vector,
                                  "filter": {"category": {"$eq": category}},
                                  "numCandidates": 100,
                                  "limit": 3,
                              }
                          },
                          {
                              "$project": {
                                  "_id": 0,
                                  "id": 1,
                                  "category": 1,
                                  "text": 1,
                                  "score": {"$meta": "vectorSearchScore"},
                              }
                          },
                      ]
                  )
                  results = await cursor.to_list()

                  print("▸ Top 3 most similar documents:")
                  for index, result in enumerate(results, start=1):
                      print(
                          f"{index}. (Score: {result['score']:.4f}, "
                          f"Category: {result['category']})"
                      )
                      print(f"   {result['text']}")
                      print()

                  await unload_model(t, model_id)
          except Exception as error:
              print(f"✖ {error}", file=sys.stderr)
              return 1
          finally:
              await mongo.close()
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/RagMongodb.kt title="RagMongodb.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/rag/rag-mongodb.ts.
      //
      // Store each document in MongoDB alongside its vector, build a vector search
      // index over it, and retrieve matches with a `$vectorSearch` aggregation that
      // pre-filters by category.
      //
      // Needs the MongoDB Kotlin coroutine driver
      // (`org.mongodb:mongodb-driver-kotlin-coroutine`, scoped to this example in
      // build.gradle.kts) and a deployment with Atlas Vector Search. QVAC only
      // produces the vectors through `client.embeddings.embed()`; the storage,
      // indexing and search all belong to MongoDB.
      //
      // The coroutine driver mirrors the JS one closely: every collection call
      // suspends, and cursors are `Flow`s collected with `toList()`. `drop()` is
      // idempotent (the driver allows "ns not found"), so dropping a collection that
      // was never created needs no guard, and the index-build poll waits with
      // `delay` instead of a hand-rolled timer.
      //
      // RUN: ./gradlew -p examples run -Pexample=RagMongodb --args="[query] [category]"

      import com.mongodb.MongoException
      import com.mongodb.client.model.SearchIndexModel
      import com.mongodb.client.model.SearchIndexType
      import com.mongodb.kotlin.client.coroutine.MongoClient
      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.embeddings
      import io.tether.qvac.sdk.generated.ModelConstant
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import kotlin.system.exitProcess
      import kotlinx.coroutines.delay
      import kotlinx.coroutines.flow.toList
      import kotlinx.coroutines.runBlocking
      import org.bson.Document

      private const val INDEX_NAME = "documents_vector_index"

      private val MONGODB_SETUP_INSTRUCTIONS = """
          |
          |▸ This example needs a MongoDB deployment with Atlas Vector Search.
          |
          |One way to get one is to run it in Docker:
          |
          |   docker run -p 27017:27017 --name atlas-local mongodb/mongodb-atlas-local
          |
          |For more details, visit: https://www.mongodb.com/docs/atlas/cli/current/atlas-cli-deploy-docker/
          |
      """.trimMargin()

      private data class Sample(val id: Int, val category: String, val text: String)

      // Sample corpus, each document tagged with a category to filter on
      private val SAMPLES = listOf(
          Sample(
              1, "ai",
              "Machine learning is a subset of artificial intelligence that focuses on algorithms that can learn and " +
                  "make predictions from data without being explicitly programmed for every task.",
          ),
          Sample(
              2, "ai",
              "Deep learning uses neural networks with multiple layers to process and learn from complex data patterns, " +
                  "enabling breakthroughs in image recognition and natural language processing.",
          ),
          Sample(
              3, "ai",
              "Natural language processing combines computational linguistics with machine learning to help computers " +
                  "understand, interpret, and generate human language in a meaningful way.",
          ),
          Sample(
              4, "ai",
              "Computer vision enables machines to interpret and understand visual information from the world, using " +
                  "techniques like image classification, object detection, and facial recognition.",
          ),
          Sample(
              5, "computing",
              "Quantum computing leverages quantum mechanical phenomena to process information in fundamentally " +
                  "different ways than classical computers, potentially solving certain problems exponentially faster.",
          ),
          Sample(
              6, "security",
              "Blockchain technology creates decentralized, immutable ledgers that enable secure peer-to-peer " +
                  "transactions without requiring a central authority or intermediary.",
          ),
          Sample(
              7, "computing",
              "Cloud computing delivers computing services over the internet, allowing users to access resources like " +
                  "storage, processing power, and applications on-demand from anywhere.",
          ),
          Sample(
              8, "security",
              "Cybersecurity protects digital systems, networks, and data from malicious attacks, unauthorized access, " +
                  "and various forms of cyber threats through multiple layers of defense.",
          ),
      )

      fun main(args: Array<String>): Unit = runBlocking {
          // Get query and category from command line or use defaults
          val query = args.getOrNull(0) ?: "machine learning algorithms"
          val category = args.getOrNull(1) ?: "ai"
          println("▸ Query: \"$query\" (category: \"$category\")")

          // Replace with your own deployment's connection string if it is not the Docker one
          // https://www.mongodb.com/docs/manual/reference/connection-string/
          val mongo = MongoClient.create("mongodb://localhost:27017/?directConnection=true")
          val connected = try {
              mongo.getDatabase("admin").runCommand(Document("ping", 1))
              true
          } catch (_: MongoException) {
              false
          }
          if (!connected) {
              System.err.println("✖ Failed to connect to MongoDB server")
              System.err.println("▸ Please ensure the server is running on localhost:27017")
              System.err.println(MONGODB_SETUP_INSTRUCTIONS)
              mongo.close()
              exitProcess(1)
          }
          println("▸ Connected to MongoDB server")

          val collection = mongo.getDatabase("qvac").getCollection<Document>("documents")

          try {
              val client = QvacClient(JvmBareKitTransport.connect())
              try {
                  val modelId = client.loadWithProgress(Models.GTE_LARGE_FP16)

                  // (Re)create the collection. The driver allows "ns not found", so this
                  // is a no-op the first time round.
                  collection.drop()

                  // Embed and store documents
                  println("▸ Embedding documents...")
                  val documents = SAMPLES.map { sample ->
                      Document("id", sample.id)
                          .append("category", sample.category)
                          .append("text", sample.text)
                          .append("embedding", client.embeddings.embed(modelId, sample.text))
                  }
                  collection.insertMany(documents)

                  // numDimensions is fixed at index creation and must match the model:
                  // GTE Large is 1024
                  println("▸ Creating vector search index...")
                  collection.createSearchIndexes(
                      listOf(
                          SearchIndexModel(
                              INDEX_NAME,
                              Document(
                                  "fields",
                                  listOf(
                                      Document("type", "vector")
                                          .append("path", "embedding")
                                          .append("numDimensions", 1024)
                                          .append("similarity", "cosine"),
                                      // A field must be indexed as a filter to be usable in a $vectorSearch filter
                                      Document("type", "filter").append("path", "category"),
                                  ),
                              ),
                              SearchIndexType.vectorSearch(),
                          ),
                      ),
                  ).toList() // a cold Flow: nothing is sent until it is collected

                  // Index builds are asynchronous; querying too early returns no matches
                  for (attempt in 0 until 60) {
                      val indexes = collection.listSearchIndexes<Document>().name(INDEX_NAME).toList()
                      if (indexes.firstOrNull()?.getBoolean("queryable") == true) break
                      if (attempt == 59) error("Index $INDEX_NAME did not become queryable")
                      delay(1000)
                  }

                  println("▸ Searching for similar documents...")
                  val queryVector = client.embeddings.embed(modelId, query)

                  val results = collection.aggregate<Document>(
                      listOf(
                          Document(
                              "\$vectorSearch",
                              Document("index", INDEX_NAME)
                                  .append("path", "embedding")
                                  .append("queryVector", queryVector)
                                  .append("filter", Document("category", Document("\$eq", category)))
                                  .append("numCandidates", 100)
                                  .append("limit", 3),
                          ),
                          Document(
                              "\$project",
                              Document("_id", 0)
                                  .append("id", 1)
                                  .append("category", 1)
                                  .append("text", 1)
                                  .append("score", Document("\$meta", "vectorSearchScore")),
                          ),
                      ),
                  ).toList()

                  println("▸ Top 3 most similar documents:")
                  results.forEachIndexed { index, result ->
                      println(
                          "%d. (Score: %.4f, Category: %s)".format(
                              index + 1,
                              result.getDouble("score"),
                              result.getString("category"),
                          ),
                      )
                      println("   ${result.getString("text")}")
                      println()
                  }

                  client.models.unload(modelId)
              } finally {
                  client.close()
              }
          } finally {
              mongo.close()
          }
      }

      /** Load [model], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(model: ModelConstant): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(model.src, model.engine, model.name).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

In Kotlin, the [examples build](/sdk/v0.23/kotlin-sdk#quickstart) adds the coroutine driver, `org.mongodb:mongodb-driver-kotlin-coroutine:5.13.0`, to this example only, so there is nothing to install.

#### SQLite

This example needs the vector extension for SQLite, which arrives differently per language. JavaScript and TypeScript use a SQLite WASM build that has the extension compiled in; Python uses the standard library's `sqlite3` module and loads the extension from a prebuilt binary. Install the one for the language you are using:

```bash
# JavaScript and TypeScript
npm i "@sqliteai/sqlite-wasm@3.50.4-sync.0.8.30-vector.0.9.23"

# Python
pip install "sqliteai-vector>=1.1"
```

Those are the versions these docs are tested against. Loading an extension also needs a Python configured with `--enable-loadable-sqlite-extensions`. Most distribution and python.org builds are; `pyenv`'s default build is not, and no package you install changes that — pass `-p` to `virtualenv` (or `--python` to `uv venv`) to base the environment on an interpreter that qualifies. The example checks before it starts and tells you if yours does not. The database is in-memory, so there is nothing else to set up.

The following script shows the same workflow using `embed()` plus a SQLite vector index:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/rag/rag-sqlite.js title="rag-sqlite.js" lineNumbers
      import { embed, loadModel, unloadModel, GTE_LARGE_FP16 } from '@qvac/sdk';
      import sqlite3InitModule from '@sqliteai/sqlite-wasm';
      try {
          // Get query from command line or use default
          const query = process.argv[2] || 'machine learning algorithms';
          console.log(`▸ Query: "${query}"`);
          // Initialize SQLite with vector extension
          const sqlite3 = await sqlite3InitModule();
          const db = new sqlite3.oo1.DB(':memory:', 'c');
          const modelId = await loadModel({
              modelSrc: GTE_LARGE_FP16,
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          const samples = [
              {
                  id: 1,
                  text: 'Machine learning is a subset of artificial intelligence that focuses on algorithms that can learn and make predictions from data without being explicitly programmed for every task.'
              },
              {
                  id: 2,
                  text: 'Deep learning uses neural networks with multiple layers to process and learn from complex data patterns, enabling breakthroughs in image recognition and natural language processing.'
              },
              {
                  id: 3,
                  text: 'Natural language processing combines computational linguistics with machine learning to help computers understand, interpret, and generate human language in a meaningful way.'
              },
              {
                  id: 4,
                  text: 'Computer vision enables machines to interpret and understand visual information from the world, using techniques like image classification, object detection, and facial recognition.'
              },
              {
                  id: 5,
                  text: 'Quantum computing leverages quantum mechanical phenomena to process information in fundamentally different ways than classical computers, potentially solving certain problems exponentially faster.'
              },
              {
                  id: 6,
                  text: 'Blockchain technology creates decentralized, immutable ledgers that enable secure peer-to-peer transactions without requiring a central authority or intermediary.'
              },
              {
                  id: 7,
                  text: 'Cloud computing delivers computing services over the internet, allowing users to access resources like storage, processing power, and applications on-demand from anywhere.'
              },
              {
                  id: 8,
                  text: 'Cybersecurity protects digital systems, networks, and data from malicious attacks, unauthorized access, and various forms of cyber threats through multiple layers of defense.'
              }
          ];
          // Create table for documents with vector storage
          db.exec(`
        CREATE TABLE IF NOT EXISTS documents (
          id INTEGER PRIMARY KEY,
          text TEXT NOT NULL,
          embedding BLOB NOT NULL
        )
      `);
          console.log('▸ Embedding documents...');
          for (const sample of samples) {
              const { embedding } = await embed({ modelId, text: sample.text });
              db.exec({
                  sql: 'INSERT INTO documents VALUES (?, ?, vector_as_f32(?))',
                  bind: [sample.id, sample.text, JSON.stringify(embedding)]
              });
          }
          // Initialize and optimize vector index
          db.exec(`SELECT vector_init('documents', 'embedding', 'type=FLOAT32,dimension=1024')`);
          // Quantize vectors
          db.exec(`SELECT vector_quantize('documents', 'embedding')`);
          // [Optional] Preload quantized vectors in memory for optimal performance
          db.exec(`SELECT vector_quantize_preload('documents', 'embedding')`);
          // Search for similar documents
          console.log('▸ Searching for similar documents...');
          const { embedding: queryEmbedding } = await embed({ modelId, text: query });
          const results = [];
          // Perform vector search
          db.exec({
              sql: `
          SELECT d.id, d.text, v.distance 
          FROM documents d
          JOIN vector_quantize_scan('documents', 'embedding', vector_as_f32(?), 3) v
          ON d.id = v.rowid
        `,
              bind: [JSON.stringify(queryEmbedding)],
              rowMode: 'object',
              callback: (row) => {
                  const typedRow = row;
                  results.push(typedRow);
              }
          });
          console.log('\n▸ Top 3 most similar documents:');
          results.forEach((result, index) => {
              console.log('='.repeat(50) + ' Top result:');
              console.log(`\n${index + 1}. [ID: ${result.id}] (Score: ${result.distance.toFixed(4)})`);
              console.log(`   ${result.text}`);
              console.log('='.repeat(100));
              console.log();
          });
          await unloadModel({ modelId });
          db.close();
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/rag/rag-sqlite.ts title="rag-sqlite.ts" lineNumbers
      import { embed, loadModel, unloadModel, GTE_LARGE_FP16 } from '@qvac/sdk'
      import sqlite3InitModule from '@sqliteai/sqlite-wasm'

      try {
        // Get query from command line or use default
        const query = process.argv[2] || 'machine learning algorithms'
        console.log(`▸ Query: "${query}"`)

        // Initialize SQLite with vector extension
        const sqlite3 = await sqlite3InitModule()
        const db = new sqlite3.oo1.DB(':memory:', 'c')

        const modelId = await loadModel({
          modelSrc: GTE_LARGE_FP16,
          onProgress: (p) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        const samples = [
          {
            id: 1,
            text: 'Machine learning is a subset of artificial intelligence that focuses on algorithms that can learn and make predictions from data without being explicitly programmed for every task.'
          },
          {
            id: 2,
            text: 'Deep learning uses neural networks with multiple layers to process and learn from complex data patterns, enabling breakthroughs in image recognition and natural language processing.'
          },
          {
            id: 3,
            text: 'Natural language processing combines computational linguistics with machine learning to help computers understand, interpret, and generate human language in a meaningful way.'
          },
          {
            id: 4,
            text: 'Computer vision enables machines to interpret and understand visual information from the world, using techniques like image classification, object detection, and facial recognition.'
          },
          {
            id: 5,
            text: 'Quantum computing leverages quantum mechanical phenomena to process information in fundamentally different ways than classical computers, potentially solving certain problems exponentially faster.'
          },
          {
            id: 6,
            text: 'Blockchain technology creates decentralized, immutable ledgers that enable secure peer-to-peer transactions without requiring a central authority or intermediary.'
          },
          {
            id: 7,
            text: 'Cloud computing delivers computing services over the internet, allowing users to access resources like storage, processing power, and applications on-demand from anywhere.'
          },
          {
            id: 8,
            text: 'Cybersecurity protects digital systems, networks, and data from malicious attacks, unauthorized access, and various forms of cyber threats through multiple layers of defense.'
          }
        ]

        // Create table for documents with vector storage
        db.exec(`
        CREATE TABLE IF NOT EXISTS documents (
          id INTEGER PRIMARY KEY,
          text TEXT NOT NULL,
          embedding BLOB NOT NULL
        )
      `)

        console.log('▸ Embedding documents...')
        for (const sample of samples) {
          const { embedding } = await embed({ modelId, text: sample.text })
          db.exec({
            sql: 'INSERT INTO documents VALUES (?, ?, vector_as_f32(?))',
            bind: [sample.id, sample.text, JSON.stringify(embedding)]
          })
        }

        // Initialize and optimize vector index
        db.exec(`SELECT vector_init('documents', 'embedding', 'type=FLOAT32,dimension=1024')`)

        // Quantize vectors
        db.exec(`SELECT vector_quantize('documents', 'embedding')`)

        // [Optional] Preload quantized vectors in memory for optimal performance
        db.exec(`SELECT vector_quantize_preload('documents', 'embedding')`)

        // Search for similar documents
        console.log('▸ Searching for similar documents...')
        const { embedding: queryEmbedding } = await embed({ modelId, text: query })

        const results: Array<{
          id: number
          text: string
          distance: number
        }> = []

        // Perform vector search
        db.exec({
          sql: `
          SELECT d.id, d.text, v.distance 
          FROM documents d
          JOIN vector_quantize_scan('documents', 'embedding', vector_as_f32(?), 3) v
          ON d.id = v.rowid
        `,
          bind: [JSON.stringify(queryEmbedding)],
          rowMode: 'object',
          callback: (row: unknown) => {
            const typedRow = row as { id: number; text: string; distance: number }
            results.push(typedRow)
          }
        })

        console.log('\n▸ Top 3 most similar documents:')
        results.forEach((result, index) => {
          console.log('='.repeat(50) + ' Top result:')
          console.log(`\n${index + 1}. [ID: ${result.id}] (Score: ${result.distance.toFixed(4)})`)
          console.log(`   ${result.text}`)
          console.log('='.repeat(100))
          console.log()
        })

        await unloadModel({ modelId })
        db.close()
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/rag_sqlite.py title="rag_sqlite.py" lineNumbers
      """Python port of packages/sdk/examples/rag/rag-sqlite.ts.

      Keep each document in SQLite alongside its vector and retrieve matches with
      the SQLite-Vector extension's quantized scan. QVAC only produces the vectors
      through `embed`; the storage, quantization and search all happen in SQL.

      The extension and its SQL are the same ones the TypeScript example uses, but
      they arrive differently. There the npm `@sqliteai/sqlite-wasm` build has the
      extension compiled in; here the stdlib `sqlite3` module loads a prebuilt
      binary, shipped by `pip install sqliteai-vector`. That needs an interpreter
      configured with `--enable-loadable-sqlite-extensions`, which pyenv's default
      build is not (`sqlite3.Connection.enable_load_extension` is absent when it is
      missing), so this example checks for it before trying.

      RUN: python examples/rag_sqlite.py [query]
      """

      from __future__ import annotations

      import asyncio
      import importlib.resources
      import json
      import sqlite3
      import sys

      from tetherto.qvac_sdk import Client, EmbedRequest, embed, load_model, unload_model
      from tetherto.qvac_sdk.models import GTE_LARGE_FP16


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def embed_text(t, model_id, text):
          """Embed one string or a list of strings; returns the vector(s)."""
          response = await embed(
              t,
              EmbedRequest.model_validate(
                  {"type": "embed", "modelId": model_id, "text": text}
              ),
          )
          if not response.success:
              raise RuntimeError(response.error)
          return response.embedding


      async def main() -> int:
          # Get query from command line or use default
          query = sys.argv[1] if len(sys.argv) > 1 else "machine learning algorithms"
          print(f'▸ Query: "{query}"')

          # Initialize SQLite with vector extension
          db = sqlite3.connect(":memory:")
          if not hasattr(db, "enable_load_extension"):
              print(
                  "✖ This Python cannot load SQLite extensions, so the vector "
                  "extension is unavailable",
                  file=sys.stderr,
              )
              print(
                  "▸ Nothing is missing from your environment: the interpreter itself "
                  "must be built with --enable-loadable-sqlite-extensions. Most "
                  "distribution and python.org builds are; pyenv's default build is not",
                  file=sys.stderr,
              )
              return 1

          try:
              extension = importlib.resources.files("sqlite_vector.binaries") / "vector"
          except ModuleNotFoundError:
              print(
                  "✖ This example needs the SQLite vector extension: "
                  "pip install sqliteai-vector",
                  file=sys.stderr,
              )
              return 1

          db.enable_load_extension(True)
          db.load_extension(str(extension))
          db.enable_load_extension(False)

          try:
              async with Client() as client:
                  t = client.transport
                  model_id = await load_model(
                      t, model_src=GTE_LARGE_FP16, on_progress=print_progress
                  )

                  samples = [
                      {
                          "id": 1,
                          "text": "Machine learning is a subset of artificial intelligence that focuses on algorithms that can learn and make predictions from data without being explicitly programmed for every task.",
                      },
                      {
                          "id": 2,
                          "text": "Deep learning uses neural networks with multiple layers to process and learn from complex data patterns, enabling breakthroughs in image recognition and natural language processing.",
                      },
                      {
                          "id": 3,
                          "text": "Natural language processing combines computational linguistics with machine learning to help computers understand, interpret, and generate human language in a meaningful way.",
                      },
                      {
                          "id": 4,
                          "text": "Computer vision enables machines to interpret and understand visual information from the world, using techniques like image classification, object detection, and facial recognition.",
                      },
                      {
                          "id": 5,
                          "text": "Quantum computing leverages quantum mechanical phenomena to process information in fundamentally different ways than classical computers, potentially solving certain problems exponentially faster.",
                      },
                      {
                          "id": 6,
                          "text": "Blockchain technology creates decentralized, immutable ledgers that enable secure peer-to-peer transactions without requiring a central authority or intermediary.",
                      },
                      {
                          "id": 7,
                          "text": "Cloud computing delivers computing services over the internet, allowing users to access resources like storage, processing power, and applications on-demand from anywhere.",
                      },
                      {
                          "id": 8,
                          "text": "Cybersecurity protects digital systems, networks, and data from malicious attacks, unauthorized access, and various forms of cyber threats through multiple layers of defense.",
                      },
                  ]

                  # Create table for documents with vector storage
                  db.execute("""
                      CREATE TABLE IF NOT EXISTS documents (
                        id INTEGER PRIMARY KEY,
                        text TEXT NOT NULL,
                        embedding BLOB NOT NULL
                      )
                  """)

                  print("▸ Embedding documents...")
                  for sample in samples:
                      embedding = await embed_text(t, model_id, sample["text"])
                      db.execute(
                          "INSERT INTO documents VALUES (?, ?, vector_as_f32(?))",
                          (sample["id"], sample["text"], json.dumps(embedding)),
                      )

                  # Initialize and optimize vector index
                  db.execute(
                      "SELECT vector_init('documents', 'embedding', ?)",
                      ("type=FLOAT32,dimension=1024",),
                  )

                  # Quantize vectors
                  db.execute("SELECT vector_quantize('documents', 'embedding')")

                  # [Optional] Preload quantized vectors in memory for optimal performance
                  db.execute("SELECT vector_quantize_preload('documents', 'embedding')")

                  # Search for similar documents
                  print("▸ Searching for similar documents...")
                  query_embedding = await embed_text(t, model_id, query)

                  # Perform vector search. The scan returns only rowid and distance,
                  # so the table is self-joined to read the text back.
                  results = db.execute(
                      """
                      SELECT d.id, d.text, v.distance
                      FROM documents d
                      JOIN vector_quantize_scan('documents', 'embedding', vector_as_f32(?), 3) v
                      ON d.id = v.rowid
                      """,
                      (json.dumps(query_embedding),),
                  ).fetchall()

                  print("\n▸ Top 3 most similar documents:")
                  for index, (doc_id, text, distance) in enumerate(results, start=1):
                      print("=" * 50 + " Top result:")
                      print(f"\n{index}. [ID: {doc_id}] (Score: {distance:.4f})")
                      print(f"   {text}")
                      print("=" * 100)
                      print()

                  await unload_model(t, model_id)
          except Exception as error:
              print(f"✖ {error}", file=sys.stderr)
              return 1
          finally:
              db.close()
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/RagSqlite.kt title="RagSqlite.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/rag/rag-sqlite.ts.
      //
      // Keep each document in SQLite alongside its vector and retrieve matches with
      // the SQLite-Vector extension's quantized scan. QVAC only produces the vectors
      // through `client.embeddings.embed()`; the storage, quantization and search all
      // happen in SQL.
      //
      // The extension and its SQL are the same ones the TypeScript example uses, but
      // they arrive differently. There the npm `@sqliteai/sqlite-wasm` build has the
      // extension compiled in; here the `org.xerial:sqlite-jdbc` driver (scoped to
      // this example in build.gradle.kts) loads a prebuilt native binary that you
      // download from https://github.com/sqliteai/sqlite-vector/releases and point
      // SQLITE_VECTOR_EXTENSION at. sqlite-jdbc builds always support loadable
      // extensions; `SQLiteConfig.enableLoadExtension(true)` turns them on for this
      // connection, and they are turned off again once the vector extension loads.
      //
      // RUN: SQLITE_VECTOR_EXTENSION=/path/to/vector ./gradlew -p examples run -Pexample=RagSqlite --args="[query]"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.embeddings
      import io.tether.qvac.sdk.generated.ModelConstant
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import java.sql.Connection
      import kotlin.system.exitProcess
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonArray
      import kotlinx.serialization.json.JsonPrimitive
      import org.sqlite.SQLiteConfig
      import org.sqlite.SQLiteConnection

      private data class Sample(val id: Int, val text: String)

      private val SAMPLES = listOf(
          Sample(
              1,
              "Machine learning is a subset of artificial intelligence that focuses on algorithms that can learn and " +
                  "make predictions from data without being explicitly programmed for every task.",
          ),
          Sample(
              2,
              "Deep learning uses neural networks with multiple layers to process and learn from complex data patterns, " +
                  "enabling breakthroughs in image recognition and natural language processing.",
          ),
          Sample(
              3,
              "Natural language processing combines computational linguistics with machine learning to help computers " +
                  "understand, interpret, and generate human language in a meaningful way.",
          ),
          Sample(
              4,
              "Computer vision enables machines to interpret and understand visual information from the world, using " +
                  "techniques like image classification, object detection, and facial recognition.",
          ),
          Sample(
              5,
              "Quantum computing leverages quantum mechanical phenomena to process information in fundamentally " +
                  "different ways than classical computers, potentially solving certain problems exponentially faster.",
          ),
          Sample(
              6,
              "Blockchain technology creates decentralized, immutable ledgers that enable secure peer-to-peer " +
                  "transactions without requiring a central authority or intermediary.",
          ),
          Sample(
              7,
              "Cloud computing delivers computing services over the internet, allowing users to access resources like " +
                  "storage, processing power, and applications on-demand from anywhere.",
          ),
          Sample(
              8,
              "Cybersecurity protects digital systems, networks, and data from malicious attacks, unauthorized access, " +
                  "and various forms of cyber threats through multiple layers of defense.",
          ),
      )

      fun main(args: Array<String>): Unit = runBlocking {
          // Get query from command line or use default
          val query = args.getOrNull(0) ?: "machine learning algorithms"
          println("▸ Query: \"$query\"")

          val extension = System.getenv("SQLITE_VECTOR_EXTENSION")
          if (extension.isNullOrEmpty()) {
              System.err.println("✖ This example needs the SQLite vector extension: set SQLITE_VECTOR_EXTENSION")
              System.err.println(
                  "▸ Download the prebuilt binary for your platform from " +
                      "https://github.com/sqliteai/sqlite-vector/releases and point SQLITE_VECTOR_EXTENSION at it",
              )
              exitProcess(1)
          }

          // Initialize SQLite with vector extension
          val config = SQLiteConfig().apply { enableLoadExtension(true) }
          config.createConnection("jdbc:sqlite::memory:").use { db ->
              db.select("SELECT load_extension(?)", extension)
              db.unwrap(SQLiteConnection::class.java).database.enable_load_extension(false)

              val client = QvacClient(JvmBareKitTransport.connect())
              try {
                  val modelId = client.loadWithProgress(Models.GTE_LARGE_FP16)

                  // Create table for documents with vector storage
                  db.createStatement().use {
                      it.execute(
                          """
                          CREATE TABLE IF NOT EXISTS documents (
                            id INTEGER PRIMARY KEY,
                            text TEXT NOT NULL,
                            embedding BLOB NOT NULL
                          )
                          """.trimIndent(),
                      )
                  }

                  println("▸ Embedding documents...")
                  db.prepareStatement("INSERT INTO documents VALUES (?, ?, vector_as_f32(?))").use { insert ->
                      for (sample in SAMPLES) {
                          val embedding = client.embeddings.embed(modelId, sample.text)
                          insert.setInt(1, sample.id)
                          insert.setString(2, sample.text)
                          insert.setString(3, toJson(embedding))
                          insert.executeUpdate()
                      }
                  }

                  // Initialize and optimize vector index
                  db.select("SELECT vector_init('documents', 'embedding', ?)", "type=FLOAT32,dimension=1024")

                  // Quantize vectors
                  db.select("SELECT vector_quantize('documents', 'embedding')")

                  // [Optional] Preload quantized vectors in memory for optimal performance
                  db.select("SELECT vector_quantize_preload('documents', 'embedding')")

                  // Search for similar documents
                  println("▸ Searching for similar documents...")
                  val queryEmbedding = client.embeddings.embed(modelId, query)

                  // Perform vector search. The scan returns only rowid and distance, so
                  // the table is self-joined to read the text back.
                  val search = """
                      SELECT d.id, d.text, v.distance
                      FROM documents d
                      JOIN vector_quantize_scan('documents', 'embedding', vector_as_f32(?), 3) v
                      ON d.id = v.rowid
                  """.trimIndent()
                  println("\n▸ Top 3 most similar documents:")
                  db.prepareStatement(search).use { statement ->
                      statement.setString(1, toJson(queryEmbedding))
                      statement.executeQuery().use { rows ->
                          var index = 1
                          while (rows.next()) {
                              println("=".repeat(50) + " Top result:")
                              println("\n$index. [ID: ${rows.getInt(1)}] (Score: %.4f)".format(rows.getDouble(3)))
                              println("   ${rows.getString(2)}")
                              println("=".repeat(100))
                              println()
                              index++
                          }
                      }
                  }

                  client.models.unload(modelId)
              } finally {
                  client.close()
              }
          }
      }

      /** Run a SELECT for its side effect, binding [params] in order. */
      private fun Connection.select(sql: String, vararg params: String) {
          prepareStatement(sql).use { statement ->
              params.forEachIndexed { index, value -> statement.setString(index + 1, value) }
              statement.executeQuery().close()
          }
      }

      /** The JSON array text `vector_as_f32()` parses. */
      private fun toJson(vector: List<Double>): String = JsonArray(vector.map(::JsonPrimitive)).toString()

      /** Load [model], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(model: ModelConstant): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(model.src, model.engine, model.name).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

In Kotlin, the [examples build](/sdk/v0.23/kotlin-sdk#quickstart) adds the SQLite JDBC driver, `org.xerial:sqlite-jdbc:3.53.4.0`, to this example only. The driver always supports loadable extensions, but the vector extension itself is a prebuilt binary: download the one for your platform from the [sqlite-vector releases](https://github.com/sqliteai/sqlite-vector/releases) and point `SQLITE_VECTOR_EXTENSION` at it:

```bash
SQLITE_VECTOR_EXTENSION=/path/to/vector ./gradlew -p examples run -Pexample=RagSqlite
```

<Callout type="success">
  **Tip:** all examples throughout this documentation are self-contained and runnable. For instructions on how to run them, see the [JS/TS quickstart](/sdk/v0.23/js-ts-sdk#quickstart), the [Python quickstart](/sdk/v0.23/python-sdk#quickstart), or the [Kotlin quickstart](/sdk/v0.23/kotlin-sdk#quickstart).
</Callout>
