Skip to main content
Swift SDK / MossClient

MossClient

The entry point for the Swift SDK. Construct it with your project credentials (or a custom Authenticator), then open on-device sessions and track push jobs. All methods are async throws and dispatch native work onto a background thread. The underlying native client is thread-safe.

Example

import Moss

let client = try MossClient(projectId: "your-project-id", projectKey: "your-project-key")
defer { client.close() }

// Open an on-device session and search locally.
let session = try await client.session("docs")
try await session.addDocs([
  .init(id: "1", text: "Machine learning fundamentals"),
  .init(id: "2", text: "Deep learning neural networks"),
])
let results = try await session.query("AI and neural networks")

Constructors

init(projectId:projectKey:)

init(projectId: String, projectKey: String) throws
Creates a client backed by a static project key.
ParameterTypeDescription
projectIdStringYour project identifier.
projectKeyStringYour project authentication key. Prefer the Authenticator form for shipped apps so the key never ships in the binary.

init(projectId:authenticator:baseUrl:)

init(projectId: String, authenticator: any Authenticator, baseUrl: String? = nil) throws
Creates a client whose bearer tokens come from a custom Authenticator. Use this in shipped apps so the long-lived project key stays on your backend.
ParameterTypeDescription
projectIdStringYour project identifier.
authenticatorany AuthenticatorSupplies a short-lived bearer token from your backend.
baseUrlString?Optional override for the API base URL.

Statics

sdkVersion

static var sdkVersion: String
The native runtime version string.

setModelCacheDir(_:)

static func setModelCacheDir(_ path: String) throws
Override where embedding-model files are cached. You normally don’t need this - the client caches under <Library/Caches>/moss-models/ automatically on first init. Call it before constructing your first client if you need a custom location (e.g. a shared App Group container).

Methods

close()

func close()
Frees the underlying native handle. Idempotent and safe to call while operations are in flight (it blocks until they drain). Also called automatically on deinit.

session(_:options:)

func session(_ name: String, options: SessionOptions = SessionOptions()) async throws -> MossSession
func session(_ name: String, modelId: String?) async throws -> MossSession
Opens an on-device MossSession. Documents are embedded locally with the bundled model (default moss-litelm on iOS) and queried without a network round-trip. Configure with SessionOptions.
let session = try await client.session("notes")
defer { session.close() }

createIndex(_:docs:modelId:)

func createIndex(_ name: String, docs: [DocumentInfo], modelId: String? = nil) async throws -> MutationResult
Creates a cloud index from the given documents and polls until it is ready. When modelId is nil the server picks a default ("custom" when documents carry pre-computed embeddings). Returns a MutationResult.
ParameterTypeDescription
nameStringName of the index to create.
docs[DocumentInfo]Documents to index, optionally with pre-computed embeddings.
modelIdString?Embedding model id. nil selects the server default.
let result = try await client.createIndex("docs", docs: [
  .init(id: "1", text: "Machine learning fundamentals"),
  .init(id: "2", text: "Deep learning neural networks"),
])

getIndex(_:)

func getIndex(_ name: String) async throws -> IndexInfo
Gets metadata about a single cloud index. Returns an IndexInfo. Throws if the index does not exist.

listIndexes()

func listIndexes() async throws -> [IndexInfo]
Lists all cloud indexes for the project. Returns an array of IndexInfo.
for index in try await client.listIndexes() {
  print("\(index.name): \(index.docCount) docs")
}

refreshIndex(_:)

func refreshIndex(_ name: String) async throws -> RefreshResult
Checks the cloud for a newer version of a loaded index and updates it in place if one exists. Returns a RefreshResult describing whether an update was applied.

loadIndex(_:options:)

func loadIndex(_ name: String, options: LoadIndexOptions = LoadIndexOptions()) async throws
Downloads a cloud index and loads it for fast local querying. Configure caching and background auto-refresh with LoadIndexOptions. Throws if the index does not exist or loading fails.
ParameterTypeDescription
nameStringName of the index to load.
optionsLoadIndexOptionsCache path and auto-refresh configuration.
try await client.loadIndex("docs", options: .init(cachePath: cachePath))

query(::options:)

func query(_ indexName: String, _ query: String, options: QueryOptions = QueryOptions()) async throws -> SearchResult
Runs a semantic search against a loaded index. The index must be loaded with loadIndex(_:options:) first; querying an index that has not been loaded throws. Configure with QueryOptions and read matches from the returned SearchResult.
ParameterTypeDescription
indexNameStringName of the loaded index to search.
queryStringSearch query text.
optionsQueryOptionstopK, alpha, and metadata filter.
try await client.loadIndex("docs", options: .init(cachePath: cachePath))
let results = try await client.query("docs", "vector search on mobile")
for doc in results.docs {
  print("\(doc.id): \(doc.score)")
}

unloadIndex(_:)

func unloadIndex(_ name: String) async throws
Unloads a previously loaded index, releasing the resources it held. Subsequent query(_:_:options:) calls for that index throw until it is loaded again.

addDocs(_:docs:upsert:)

func addDocs(_ name: String, docs: [DocumentInfo], upsert: Bool = true) async throws -> MutationResult
Adds or updates documents in a cloud index and polls until the rebuild completes. Returns a MutationResult.
ParameterTypeDescription
nameStringName of the target index.
docs[DocumentInfo]Documents to add or update.
upsertBoolUpdate documents that already share an id. Default true.

getDocs(_:docIds:)

func getDocs(_ name: String, docIds: [String]? = nil) async throws -> [DocumentInfo]
Retrieves documents from a cloud index. Pass docIds to fetch specific documents; omit it to fetch all of them. Returns an array of DocumentInfo.
let all = try await client.getDocs("docs")
let some = try await client.getDocs("docs", docIds: ["1", "2"])

deleteDocs(_:docIds:)

func deleteDocs(_ name: String, docIds: [String]) async throws -> MutationResult
Deletes documents from a cloud index by id and polls until the rebuild completes. Returns a MutationResult.
ParameterTypeDescription
nameStringName of the target index.
docIds[String]Ids of the documents to delete.

getJobStatus(_:)

func getJobStatus(_ jobId: String) async throws -> JobStatus
Gets the current status of an async job - for example, the job returned by MossSession.pushIndex. Poll until status is ready. Returns a JobStatus.
let push = try await session.pushIndex()
while try await client.getJobStatus(push.jobId).status != "ready" {
  try await Task.sleep(nanoseconds: 1_000_000_000)
}

deleteIndex(_:)

func deleteIndex(_ name: String) async throws -> Bool
Deletes a cloud index (e.g. one created by MossSession.pushIndex) and all its data. Returns true if deleted.

onMemoryPressure(_:)

func onMemoryPressure(_ level: MemoryPressureLevel = .critical) async throws -> Int
Frees reclaimable native memory in response to an OS memory-pressure signal. Wire this from UIApplication.didReceiveMemoryWarningNotification. Returns the number of indexes freed. See MemoryPressureLevel.