On-Device RAG in Swift: Vector Search with sqlite-vec and Apple Embeddings

On-Device RAG in Swift: Vector Search with sqlite-vec and Apple Embeddings

On-Device RAG in Swift: Vector Search with sqlite-vec and Apple Embeddings

Implementing on-device RAG Swift sqlite-vec pipelines enables offline, zero-latency retrieval-augmented generation directly on iOS and macOS devices. While server-side RAG relies on external vector databases (such as Pinecone or Qdrant) communicating over network APIs, enterprise privacy requirements often forbid transmitting sensitive user documents, financial statements, or chat logs to cloud infrastructure.

By pairing Apple’s native NLContextualEmbedding framework with sqlite-vec—a lightweight C-based vector search extension for SQLite—developers can store, index, and query high-dimensional embeddings locally with sub-15ms search latency and minimal memory overhead.

Architecture diagram demonstrating local document chunking, contextual embedding generation, and k-nearest-neighbor search inside a native sqlite-vec database.

The Verdict

  • Complete privacy and zero network latency: Querying vectors locally guarantees that raw user data never leaves the device, eliminating compliance overhead and ensuring functionality in flight or offline modes.
  • sqlite-vec runs inside existing SQLite containers: Rather than bundling complex vector database daemons, sqlite-vec compiles directly as an in-process SQLite virtual table extension, maintaining zero additional process overhead.
  • The background indexing battery constraint: Generating dense embeddings for thousands of local documents is CPU- and Neural Engine-intensive. Bulk indexing must be gated behind BGProcessingTask to run exclusively while the device is connected to power.
  • Architectural pattern: Use Apple’s 512-dimension contextual embeddings for mobile efficiency; higher-dimension models (1536+) balloon mobile disk storage without offering perceptible retrieval quality improvements on localized corpora.

The Local RAG Architecture

A local RAG execution follows a compact four-step pipeline entirely within the app process:

[User Query]
     │
     ▼
1. Embed Query (NLContextualEmbedding — 512 Float32 values)
     │
     ▼
2. Vector Search (sqlite-vec: SELECT rowid FROM vec_docs WHERE embedding MATCH ? k=3)
     │
     ▼
3. Retrieve Context Chunks (Standard SQLite relational table)
     │
     ▼
4. Generate Response (Core AI on-device Foundation Model)

Integrating sqlite-vec with Swift

Using SQLite’s C API directly from Swift allows binding raw vector memory buffers without intermediate string serialization:

import Foundation
import NaturalLanguage
import SQLite3

public final class OnDeviceVectorStore: Sendable {
    private let dbPointer: OpaquePointer

    public init(databaseURL: URL) throws {
        var db: OpaquePointer?
        guard sqlite3_open(databaseURL.path, &db) == SQLITE_OK, let validDB = db else {
            throw VectorStoreError.databaseOpenFailed
        }
        self.dbPointer = validDB

        // Enable sqlite-vec extension and create virtual vector table
        try executeSQL("""
            CREATE VIRTUAL TABLE IF NOT EXISTS document_vectors USING vec0(
                document_id INTEGER PRIMARY KEY,
                embedding float[512] distance_metric=cosine
            );
            CREATE TABLE IF NOT EXISTS document_content (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                text_content TEXT NOT NULL
            );
        """)
    }

    public func searchSimilarDocuments(query: String, topK: Int = 3) async throws -> [String] {
        // 1. Generate on-device embedding vector
        guard let embeddingModel = NLEmbedding.sentenceEmbedding(for: .english),
              let vector = embeddingModel.vector(for: query) else {
            throw VectorStoreError.embeddingGenerationFailed
        }
        
        let floatVector = vector.map { Float($0) }
        
        // 2. Query nearest neighbors using sqlite-vec cosine distance match
        let querySQL = """
            SELECT c.text_content
            FROM document_vectors v
            JOIN document_content c ON v.document_id = c.id
            WHERE v.embedding MATCH ? AND k = ?
            ORDER BY distance;
        """

        var statement: OpaquePointer?
        guard sqlite3_prepare_v2(dbPointer, querySQL, -1, &statement, nil) == SQLITE_OK else {
            throw VectorStoreError.queryPreparationFailed
        }
        defer { sqlite3_finalize(statement) }

        // Bind raw float buffer directly to statement parameter
        let byteCount = floatVector.count * MemoryLayout<Float>.size
        floatVector.withUnsafeBytes { rawBuffer in
            sqlite3_bind_blob(statement, 1, rawBuffer.baseAddress, Int32(byteCount), nil)
        }
        sqlite3_bind_int(statement, 2, Int32(topK))

        var results: [String] = []
        while sqlite3_step(statement) == SQLITE_ROW {
            if let textBytes = sqlite3_column_text(statement, 0) {
                results.append(String(cString: textBytes))
            }
        }
        return results
    }

    private func executeSQL(_ sql: String) throws {
        var error: UnsafeMutablePointer<CChar>?
        if sqlite3_exec(dbPointer, sql, nil, nil, &error) != SQLITE_OK {
            let msg = error.flatMap { String(cString: $0) } ?? "Unknown error"
            throw VectorStoreError.sqlExecutionError(msg)
        }
    }
}

enum VectorStoreError: Error {
    case databaseOpenFailed
    case embeddingGenerationFailed
    case queryPreparationFailed
    case sqlExecutionError(String)
}

Energy & Indexing Governance

  1. Incremental Updates: Embed documents when the user saves or edits a record; never re-index the entire database on app launch.
  2. Background Scheduling: For initial onboarding syncs, register a BGProcessingTask with requiresExternalPower = true and requiresNetworkConnectivity = false to guarantee that bulk embedding generation does not degrade user battery life.

References & Documentation

Ready for more depth?

Master these concepts with our structured technical roadmap.

View Roadmap