API Reference

The Primordial API.

This reference summarizes the public Primordial SDK API.

Client and integration

PrimordialClient is the SDK entry point. Copies share the same coordinated runtime.

Declarations

// PrimordialClient
init(
    aiConfiguration: PrimordialAIConfiguration? = nil,
    configuration: PrimordialConfiguration = .init(),
    identifier: String = "default"
)

let identifier: String
let configuration: PrimordialConfiguration
let aiConfiguration: PrimordialAIConfiguration
var ai: PrimordialAI { get }
var advanced: PrimordialAdvanced { get }
func integrationStatus() throws -> PrimordialIntegrationStatus

// Global
func checkIntegration() throws -> PrimordialIntegrationStatus

Types

PrimordialConfiguration

  • activationConfiguration: PrimordialActivationConfiguration
  • init(activationConfiguration:)

PrimordialIntegrationStatus

  • sdkVersion: String
  • platform: PrimordialPlatform
  • isSimulator: Bool

PrimordialPlatform

  • .iOS
  • .macOS
  • .unsupported

PrimordialError

  • .unsupportedDistribution
  • errorDescription

Activation

Declarations

// PrimordialClient
@discardableResult
func activate(
    _ credential: PrimordialActivationCredential,
    feature: PrimordialActivationFeature = .runtime
) async throws -> PrimordialActivationStatus
@discardableResult
func activate(
    _ credential: PrimordialProductionActivationCredential,
    feature: PrimordialActivationFeature = .runtime
) throws -> PrimordialActivationStatus
func activate(
    _ credential: PrimordialProductionActivationCredential,
    feature: PrimordialActivationFeature = .runtime
) async throws -> PrimordialActivationStatus
var isActivated: Bool { get }
func activationStatus() -> PrimordialActivationStatus

// Global
@discardableResult
func activate(
    _ credential: PrimordialActivationCredential,
    configuration: PrimordialActivationConfiguration = .default,
    feature: PrimordialActivationFeature = .runtime
) async throws -> PrimordialActivationStatus
@discardableResult
func activate(
    _ credential: PrimordialProductionActivationCredential,
    feature: PrimordialActivationFeature = .runtime
) throws -> PrimordialActivationStatus
@discardableResult
func activate(
    _ credential: PrimordialProductionActivationCredential,
    configuration: PrimordialActivationConfiguration = .default,
    feature: PrimordialActivationFeature = .runtime
) async throws -> PrimordialActivationStatus
var isActivated: Bool { get }
func activationStatus() -> PrimordialActivationStatus

Types

PrimordialActivationConfiguration

  • .default
  • .defaultActivationEndpoint
  • .defaultLicenseRefreshEndpoint
  • activationEndpoint: URL
  • licenseRefreshEndpoint: URL
  • requestTimeout: TimeInterval
  • init(activationEndpoint:licenseRefreshEndpoint:requestTimeout:)

PrimordialActivationCredential

  • .evaluationKey(String)

PrimordialProductionActivationCredential

  • .license(PrimordialLicenseSource)

PrimordialLicenseSource

  • .bundled(String)
  • .file(URL)

PrimordialActivationFeature

  • .runtime
  • .textGeneration
  • .embeddings
  • .voice

PrimordialActivationStatus

  • .inactive
  • .evaluation(PrimordialEvaluationActivation)
  • .production(PrimordialProductionActivation)
  • isActivated: Bool

PrimordialEvaluationActivation

  • evaluationKeyId
  • projectId
  • appId
  • init(evaluationKeyId:projectId:appId:)

PrimordialProductionActivation

  • licenseId: String, plan: String
  • features: [PrimordialActivationFeature]
  • expiresAt: Date, gracePeriodEndsAt: Date
  • validity: PrimordialLicenseValidity

PrimordialLicenseValidity

  • .active
  • .gracePeriod

PrimordialActivationError

See Errors for all cases.

Background download events

Declarations

// SwiftUI Scene
func primordialBackgroundDownloads() -> some Scene

// UIKit fallback
@discardableResult
static func handleEventsForBackgroundURLSession(
    identifier: String,
    completionHandler: @escaping () -> Void
) -> Bool

Add .primordialBackgroundDownloads() once to a SwiftUI app's main scene. The modifier is a no-op outside iOS. UIKit apps forward background URL-session events with the static method, which returns true when the identifier belongs to Primordial. See AI Model Setup.

AI configuration

Declarations

// PrimordialAIConfiguration
init(
    generation: PrimordialGenerationSelection = .model(.init()),
    embedding: PrimordialEmbeddingModel = .paraphraseMultilingualMiniLML12V2CrossDeviceV1,
    speech: PrimordialSpeechModel = .parakeetMultilingual
)

// PrimordialModelConfiguration
init(
    model: PrimordialModelDescriptor = .qwen3_5_2B4Bit,
    defaultSystemPrompt: String = "You are a helpful assistant.",
    extraEOSTokens: [String] = ["<|im_end|>"],
    gpuCacheLimitBytes: Int = 20 * 1024 * 1024,
    maxTokens: Int = 1024,
    temperature: Float = 0.6,
    kvCacheCompression: PrimordialKVCacheCompression = .none
)

// PrimordialAppleFoundationModelConfiguration
init(
    defaultSystemPrompt: String = "You are a helpful assistant.",
    maxTokens: Int? = nil,
    temperature: Double? = 0.6,
    fallback: PrimordialGenerationFallback? = nil
)

Types

PrimordialAIConfiguration

  • generation: PrimordialGenerationSelection
  • embedding: PrimordialEmbeddingModel
  • speech: PrimordialSpeechModel
  • .default
  • .defaultVersion
  • init(generation:embedding:speech:)

New clients use embedding defaults designed for consistent search between iPhone and Mac. Existing clients retain their saved defaults. When switching an existing collection to the new embedding setting, rebuild its search index.

PrimordialGenerationSelection

  • .model(PrimordialModelConfiguration)
  • .appleFoundationModel(PrimordialAppleFoundationModelConfiguration = .init())

PrimordialModelConfiguration

  • model: PrimordialModelDescriptor
  • defaultSystemPrompt: String
  • extraEOSTokens: [String]
  • gpuCacheLimitBytes: Int
  • maxTokens: Int
  • temperature: Float
  • kvCacheCompression: PrimordialKVCacheCompression
  • init(model:defaultSystemPrompt:extraEOSTokens:gpuCacheLimitBytes:maxTokens:temperature:kvCacheCompression:)

PrimordialKVCacheCompression

  • .none (default; uncompressed KV cache)
  • .turboQuant (compressed KV cache)

PrimordialAppleFoundationModelConfiguration

  • defaultSystemPrompt: String
  • maxTokens: Int?
  • temperature: Double?
  • fallback: PrimordialGenerationFallback?
  • init(defaultSystemPrompt:maxTokens:temperature:fallback:)

PrimordialGenerationFallback

  • .requireDecision(PrimordialModelConfiguration)

PrimordialSpeechModel

  • .parakeetMultilingual

AI Models

PrimordialModelIdentifier

  • rawValue: String
  • init(rawValue:)

PrimordialModelDescriptor

  • identifier, displayName
  • capabilities: PrimordialModelCapabilities; read-only to applications
  • license: String?
  • .qwen3_5_2B4Bit
  • .qwen3_1_7B4Bit
  • init(identifier:displayName:contextWindow:minimumMemoryBytes:license:)

PrimordialModelCapabilities

  • features: PrimordialTechnicalFeature
  • contextWindow: Int?
  • minimumMemoryBytes: Int64?
  • init(features:contextWindow:minimumMemoryBytes:)

PrimordialTechnicalFeature

  • rawValue: Int
  • .localExecution, .textGeneration
  • .streaming, .structuredOutput
  • .toolCalling, .speechRecognition
  • .audioRecording
  • init(rawValue:)

PrimordialEmbeddingModel

  • id: String
  • schema: VectorEmbeddingSchema
  • .paraphraseMultilingualMiniLML12V2
  • .paraphraseMultilingualMiniLML12V2CrossDeviceV1
  • custom(modelID:schema:)

PrimordialModel

  • identifier: String
  • displayName: String?
  • kind: PrimordialModelKind
  • init(identifier:displayName:kind:)

PrimordialModelKind

  • .generation
  • .embedding
  • .speech

Status, capabilities, and installation

Declarations

// PrimordialAI
func status() async -> PrimordialAIStatus
func storageUsage() async throws -> PrimordialAIStorageUsage
func capabilities() async -> PrimordialAICapabilities
var generation: PrimordialAIResource { get }
var embedding: PrimordialAIResource { get }
var speech: PrimordialAIResource { get }
func status(
    for capability: PrimordialAICapability
) async -> PrimordialCapabilityStatus
func status(
    for capabilities: [PrimordialAICapability]
) async -> PrimordialCapabilityStatus
func makeAvailable(
    _ capability: PrimordialAICapability
) -> AsyncThrowingStream<PrimordialCapabilityProgress, any Error>
func makeAvailable(
    _ capabilities: [PrimordialAICapability]
) -> AsyncThrowingStream<PrimordialCapabilityProgress, any Error>
func activateFallback(
    for capability: PrimordialAICapability = .generation
) -> AsyncThrowingStream<PrimordialCapabilityProgress, any Error>
func activateFallback(
    for capabilities: [PrimordialAICapability]
) -> AsyncThrowingStream<PrimordialCapabilityProgress, any Error>

// PrimordialAIResource
func capabilities() async -> PrimordialResourceCapabilities

Types

PrimordialAI

  • status()
  • storageUsage()
  • status(for: PrimordialAICapability)
  • status(for: [PrimordialAICapability])
  • capabilities()
  • makeAvailable(_: PrimordialAICapability)
  • makeAvailable(_: [PrimordialAICapability])
  • activateFallback(for: PrimordialAICapability = .generation)
  • activateFallback(for: [PrimordialAICapability])
  • generation, embedding, speech

PrimordialAIResource

  • capabilities() async -> PrimordialResourceCapabilities

PrimordialAICapability

  • .semanticSearch
  • .voiceInput
  • .answering
  • .generation

PrimordialAIStatus

  • generation, embedding, speech
  • downloadBytes
  • requiredAvailableBytes

PrimordialStorageUsage

  • logicalBytes: Int64
  • allocatedBytes: Int64

PrimordialResourceStorageUsage

  • model: PrimordialModel
  • isActive: Bool
  • usage: PrimordialStorageUsage

PrimordialAIStorageUsage

  • resources: [PrimordialResourceStorageUsage]
  • total: PrimordialStorageUsage
  • resources(for: PrimordialModelKind)

PrimordialCapabilityStatus

  • capabilities
  • generation, embedding, speech
  • downloadBytes, requiredAvailableBytes
  • isInstalled, isAvailable

PrimordialAICapabilities

  • generation: PrimordialResourceCapabilities
  • embedding: PrimordialResourceCapabilities
  • speech: PrimordialResourceCapabilities

PrimordialResourceCapabilities

  • model, features, availability
  • languageIdentifiers, dimensions
  • maximumInputTokens, minimumMemoryBytes
  • isAvailable

activateFallback(for:) is the explicit, application-authorized path for a configured Apple generation fallback. It is available only while Apple generation is unavailable, installs every resource required by the requested capabilities, and selects the fallback on the same client after installation succeeds. Ordinary makeAvailable never selects it.

State and progress payloads

States and progress values are returned by the status and installation declarations above.

PrimordialModelState

  • .systemAvailable, .systemUnavailable
  • .downloadRequired, .downloading, .downloaded
  • .loading, .ready, .failed

PrimordialSystemModelUnavailableReason

  • .operatingSystemNotSupported: Apple’s model requires iOS 26 or macOS 26.
  • .deviceNotEligible
  • .appleIntelligenceNotEnabled
  • .modelNotReady
  • .unsupportedLocale(identifier:)
  • .unknown(String? = nil)

PrimordialResourceAvailability

  • .available
  • .unavailable(String)
  • .systemUnavailable(PrimordialSystemModelUnavailableReason)

PrimordialModelPhase

  • .checking, .downloading
  • .verifying, .loading, .ready

PrimordialCapabilityProgress

  • fractionCompleted, downloadedBytes, totalBytes
  • currentModel, currentCapability
  • phase, resources

PrimordialResourceProgress

  • model, capabilities, phase
  • fractionCompleted, downloadedBytes, totalBytes

PrimordialCapabilityRequirement

  • capability, models
  • downloadBytes, requiredAvailableBytes
  • reason: PrimordialCapabilityUnavailableReason

PrimordialCapabilityUnavailableReason

  • .notInstalled, .systemUnavailable
  • .incompatibleDevice, .insufficientStorage
  • .verificationFailed, .resourceConflict
  • .corruptedStorage

PrimordialStorageRequirement

  • contentBytes, safetyMarginBytes
  • requiredAvailableBytes, availableBytes
  • init(contentBytes:safetyMarginBytes:requiredAvailableBytes:availableBytes:)

PrimordialDownloadOptions

  • checksAvailableStorage
  • storageSafetyMarginFraction
  • minimumStorageSafetyMarginBytes
  • .default, .withoutStorageCheck
  • init(checksAvailableStorage:storageSafetyMarginFraction:minimumStorageSafetyMarginBytes:)

Generation tasks

Declarations

func summarize(
    _ text: String,
    style: PrimordialSummaryStyle = .concise,
    generationOptions: PrimordialGenerationOptions = .default
) async throws -> String

func streamSummarize(
    _ text: String,
    style: PrimordialSummaryStyle = .concise,
    generationOptions: PrimordialGenerationOptions = .default
) -> AsyncThrowingStream<PrimordialTextChunk, any Error>

func classify(_ text: String, into categories: [String], generationOptions: PrimordialGenerationOptions = .default) async throws -> String

func task(
    prompt: String,
    generationOptions: PrimordialGenerationOptions = .default
) async throws -> PrimordialTaskResult<String>

func task(
    prompt: String,
    retrieving query: String,
    from collections: [PrimordialCollection],
    where filter: PrimordialFilter? = nil,
    options: PrimordialAnswerOptions = .init(),
    generationOptions: PrimordialGenerationOptions = .default
) async throws -> PrimordialTaskResult<String>

func task(
    prompt: String,
    retrieving query: String,
    from files: PrimordialFiles,
    options: PrimordialRetrievalOptions = .init(),
    generationOptions: PrimordialGenerationOptions = .default
) async throws -> PrimordialTaskResult<String>

func task(
    prompt: String,
    retrieving query: String,
    from sources: PrimordialSources,
    options: PrimordialRetrievalOptions = .init(),
    generationOptions: PrimordialGenerationOptions = .default
) async throws -> PrimordialTaskResult<String>

func streamTask(
    prompt: String,
    generationOptions: PrimordialGenerationOptions = .default
) -> AsyncThrowingStream<PrimordialTaskEvent, any Error>

func streamTask(
    prompt: String,
    retrieving query: String,
    from collections: [PrimordialCollection],
    where filter: PrimordialFilter? = nil,
    options: PrimordialAnswerOptions = .init(),
    generationOptions: PrimordialGenerationOptions = .default
) -> AsyncThrowingStream<PrimordialTaskEvent, any Error>

func streamTask(
    prompt: String,
    retrieving query: String,
    from files: PrimordialFiles,
    options: PrimordialRetrievalOptions = .init(),
    generationOptions: PrimordialGenerationOptions = .default
) -> AsyncThrowingStream<PrimordialTaskEvent, any Error>

func streamTask(
    prompt: String,
    retrieving query: String,
    from sources: PrimordialSources,
    options: PrimordialRetrievalOptions = .init(),
    generationOptions: PrimordialGenerationOptions = .default
) -> AsyncThrowingStream<PrimordialTaskEvent, any Error>

func extract<Output: Decodable & Sendable>(
    _ text: String,
    as output: PrimordialOutputSchema<Output>,
    generationOptions: PrimordialGenerationOptions = .default
) async throws -> Output

func task<Output: Decodable & Sendable>(
    prompt: String,
    as output: PrimordialOutputSchema<Output>,
    generationOptions: PrimordialGenerationOptions = .default
) async throws -> PrimordialTaskResult<Output>

func task<Output: Decodable & Sendable>(
    prompt: String,
    retrieving query: String,
    from collections: [PrimordialCollection],
    where filter: PrimordialFilter? = nil,
    options: PrimordialAnswerOptions = .init(),
    as output: PrimordialOutputSchema<Output>,
    generationOptions: PrimordialGenerationOptions = .default
) async throws -> PrimordialTaskResult<Output>
func task<Output: Decodable & Sendable>(
    prompt: String,
    retrieving query: String,
    from files: PrimordialFiles,
    options: PrimordialRetrievalOptions = .init(),
    as output: PrimordialOutputSchema<Output>,
    generationOptions: PrimordialGenerationOptions = .default
) async throws -> PrimordialTaskResult<Output>
func task<Output: Decodable & Sendable>(
    prompt: String,
    retrieving query: String,
    from sources: PrimordialSources,
    options: PrimordialRetrievalOptions = .init(),
    as output: PrimordialOutputSchema<Output>,
    generationOptions: PrimordialGenerationOptions = .default
) async throws -> PrimordialTaskResult<Output>

Supporting types

PrimordialTaskPlaceholder

  • sources

Retrieval-enhanced task prompts must include PrimordialTaskPlaceholder.sources exactly once.

PrimordialGenerationOptions

  • maximumResponseTokens: Int?
  • maximumThinkingTokens: Int?
  • minimumAnswerTokens: Int?
  • temperature: Double?
  • thinking: PrimordialThinkingMode
  • reasoning: PrimordialReasoningDisclosure
  • .default

.default uses thinking: .automatic and reasoning: .hidden. For local generation, automatic thinking is currently off.

PrimordialThinkingMode: .automatic, .enabled, .disabled.

PrimordialReasoningDisclosure: .hidden, .summarized, .verbatim. For MLX generation, .verbatim retains raw thinking in returned text and stream fragments; .summarized requests a separate brief rationale. Reasoning disclosure does not enable thinking.

maximumThinkingTokens requires thinking: .enabled and a nonnegative value. minimumAnswerTokens requires a positive value, an enabled thinking mode, and a thinking budget. It validates answer capacity within maximumResponseTokens; it does not guarantee answer content. See Thinking Mode, Budgets, and Rationale.

PrimordialSummaryStyle

  • .concise
  • .bulletPoints(maximum: Int)

PrimordialTextChunk

  • text: String
  • isFinal: Bool
  • metrics: PrimordialGenerationMetrics?

PrimordialGenerationMetrics

  • generatedTokenCount: Int?
  • tokensPerSecond: Double?
  • duration: TimeInterval
  • stopReason: PrimordialGenerationStopReason?

Token values are exact when supported and otherwise nil. Downloadable local generation reports token count and rate from completion metadata. Apple Foundation Model reports output-token count only on OS 27+ with a binary built using Xcode 27+; its token rate remains nil. Stream metrics appear on the final chunk.

PrimordialGenerationStopReason: .stop (model stop or end token), .length (generation limit), .cancelled (engine cancellation). stopReason is nil when the engine does not report one.

PrimordialTaskResult<Output>

  • output: Output
  • reasoningSummary: String?
  • citations: [PrimordialCitation]
  • metrics: PrimordialGenerationMetrics

PrimordialTaskEvent

  • .fragment(String)
  • .reasoningSummary(String)
  • .citation(PrimordialCitation)
  • .completed(PrimordialTaskResult<String>)

PrimordialOutputSchema<Output>

  • schema: PrimordialValueSchema
  • init(_:schema:)

PrimordialValueSchema

  • .string, .oneOf, .integer, .number, .boolean
  • .array(PrimordialValueSchema)
  • .object(_:optional:)

Imported files

Declarations

// PrimordialClient
func openFiles(named name: String) async throws -> PrimordialFiles
func deleteFiles(named name: String) async throws
func files(_ fileURLs: Set<URL>) async throws -> PrimordialFiles
func files(
    _ fileURLs: Set<URL>,
    onProgress: @escaping @MainActor @Sendable
        (PrimordialFileImportProgress) -> Void
) async throws -> PrimordialFiles

// PrimordialFiles
var names: [String] { get }
func search(
    _ query: String,
    minimumScore: Double? = nil,
    limit: Int = 8,
    strategy: PrimordialSearchStrategy = .hybrid
) async throws -> [PrimordialMatch]
func statistics(for fileURL: URL) async throws -> PrimordialCollectionStatistics
func statistics(named name: String) async throws -> PrimordialCollectionStatistics
func attach(
    _ fileURLs: Set<URL>,
    onProgress: (@MainActor @Sendable (PrimordialFileImportProgress) -> Void)? = nil
) async throws
func add(_ fileURLs: Set<URL>) async throws
func add(
    _ fileURLs: Set<URL>,
    onProgress: @escaping @MainActor @Sendable
        (PrimordialFileImportProgress) -> Void
) async throws
func replace(_ fileURLs: Set<URL>) async throws
func replace(
    _ fileURLs: Set<URL>,
    onProgress: @escaping @MainActor @Sendable
        (PrimordialFileImportProgress) -> Void
) async throws
func remove(named name: String) async throws
func remove(_ fileURL: URL) async throws
func removeAll() async throws

Set<URL> cannot contain the same URL twice. The filename including extension is the identifier; different URLs with the same filename throw duplicateFileName in one import.

add(_:) atomically imports new filenames. replace(_:) requires existing filenames, stages every replacement before switching, and then deletes all old managed records. Both provide optional progress callbacks; failed staging leaves the current files unchanged.

A named workspace persists for the same client identifier and embedding configuration. Keep one client instance while it is open. Reopening the workspace reuses indexed files without their original URLs. attach(_:) adds new filenames and replaces exact matches in one committed update; identical content keeps its index. Other files are unchanged. Names are case-sensitive. remove(named:) removes one index without a URL. removeAll() deletes the workspace's indexes and invalidates that handle; opening the name again creates an empty workspace. Source documents are not deleted. attach(_:) and remove(named:) require a named workspace. Workspace names contain 1 to 128 UTF-8 bytes. A changed embedding configuration cannot reopen an existing workspace; create another workspace or delete and reattach it with deleteFiles(named:). Release any chat and file handle before calling deleteFiles(named:); a live handle returns resourceConflict. Only one client runtime may hold a workspace at a time. Reattaching requires the original source files.

Supporting types

PrimordialFileImportProgress

  • fileName: String
  • phase: PrimordialFileImportPhase
  • completedFileCount, totalFileCount
  • fractionCompleted: Double

Phases: .reading, .chunking, .embedding, .indexing.

PrimordialRetrievalOptions

  • resultLimit: Int
  • contextCharacterLimit: Int
  • searchStrategy: PrimordialSearchStrategy
  • emptySourcesResponse: String
  • init(resultLimit:contextCharacterLimit:searchStrategy:emptySourcesResponse:)

emptySourcesResponse returns a message without generation when an answer or source-backed chat question about content has no sources. It uses the same default and behavior as PrimordialAnswerOptions. Structured tasks ignore this option.

PrimordialFileError

See Errors for all cases.

Combined sources

Declarations

func sources(
    files: PrimordialFiles? = nil,
    collections: [PrimordialCollection] = []
) throws -> PrimordialSources

// PrimordialSources
func search(
    _ query: String,
    minimumScore: Double? = nil,
    limit: Int = 8,
    strategy: PrimordialSearchStrategy = .hybrid
) async throws -> [PrimordialMatch]

A source group searches imported files and collections together. Removing files changes later operations; its collections remain available.

Managed collections

Declarations

func collection(_ name: String) throws -> PrimordialCollection

nonisolated func replaceAll(with records: [PrimordialRecord])
    -> AsyncThrowingStream<PrimordialSynchronizationEvent, any Error>
nonisolated func apply(_ changes: [PrimordialRecordChange])
    -> AsyncThrowingStream<PrimordialSynchronizationEvent, any Error>
nonisolated func synchronize(
    from source: any PrimordialRecordSource,
    options: PrimordialSynchronizationOptions = .init()
) -> AsyncThrowingStream<PrimordialSynchronizationEvent, any Error>
func synchronizationStatus() async throws -> PrimordialSynchronizationStatus
func reset() async throws
func statistics() async throws -> PrimordialCollectionStatistics
func search(
    _ query: String,
    fields: [String]? = nil,
    weights: [String: Double] = [:],
    filter: PrimordialFilter? = nil,
    minimumScore: Double? = nil,
    limit: Int = 8,
    strategy: PrimordialSearchStrategy = .hybrid
) async throws -> [PrimordialMatch]
func related(
    to id: String,
    fields: [String]? = nil,
    weights: [String: Double] = [:],
    filter: PrimordialFilter? = nil,
    minimumScore: Double? = nil,
    limit: Int = 8,
    strategy: PrimordialSearchStrategy = .hybrid
) async throws -> [PrimordialMatch]
nonisolated func reindex() -> AsyncThrowingStream<PrimordialIndexProgress, any Error>

Collection names are normalized and scoped to the client identifier. replaceAll, apply, and synchronize emit synchronization events; reindex emits index progress.

Record source contract

protocol PrimordialRecordSource: Sendable {
    var identifier: String { get }
    var schemaVersion: String { get }
    var supportsIncrementalChanges: Bool { get }

    func snapshot(
        after cursor: PrimordialSourceCursor?,
        limit: Int
    ) async throws -> PrimordialSourceSnapshotPage

    func changes(
        after checkpoint: PrimordialSourceCheckpoint,
        limit: Int
    ) async throws -> PrimordialSourceChangePage
}

SwiftData source

struct PrimordialSwiftDataSource<Model>: PrimordialRecordSource
where Model: PersistentModel {
    init<ID>(
        identifier: String,
        schemaVersion: String,
        container: ModelContainer,
        descriptor: FetchDescriptor<Model> = .init(),
        recordID: any KeyPath<Model, ID> & Sendable,
        encodeID: @escaping @Sendable (ID) throws -> String,
        fields: @escaping @Sendable (Model) throws
            -> [String: PrimordialFieldValue]
    ) throws
    where ID: Codable & Comparable & Hashable & Sendable
}

Supporting types

PrimordialCollection

  • name: String
  • clientIdentifier: String

PrimordialRecord

  • id: String
  • fields: [String: PrimordialFieldValue]
  • init(id:fields:)

PrimordialRecordChange

  • .upsert(PrimordialRecord)
  • .remove(id: String)

PrimordialFieldValue

  • .text(String), .markdown(String), .customProcessor(_:using:)
  • .keyword, .stringList
  • .integer, .double, .bool, .date

.text splits text into searchable chunks. .markdown also uses Markdown headings and structure when creating chunks.

.customProcessor accepts PrimordialChunkingStrategy. Built-ins include .characters(size:stride:) and .segments(separator:includeSeparator:omittingEmptySegments:).

Custom text processing

  • PrimordialChunkingStrategy.custom(identifier:version:_:)
  • PrimordialChunkingStrategy.custom(_: PrimordialTextChunker)
  • PrimordialChunkingInput.text, paragraphs, sentences
  • characterWindows(size:stride:), segments(separatedBy:includeSeparator:omittingEmptySegments:)
  • expanding(_:before:after:)
  • PrimordialTextSegment.text, sourceRange
  • PrimordialChunk(sourceRange:embeddingRange:context:)

Identifiers must be reverse-DNS-style and versions positive. Primordial rejects invalid or unordered ranges, empty output for nonempty text, more than 10,000 chunks, over 4,096 context characters, and embedding inputs over 32,768 characters.

PrimordialSourceCursor

  • data: Data
  • init(data:)

PrimordialSourceCheckpoint

  • data: Data
  • init(data:)

PrimordialSourceSnapshotPage

  • records: [PrimordialRecord]
  • nextCursor: PrimordialSourceCursor?
  • checkpoint: PrimordialSourceCheckpoint?

PrimordialSourceChangePage

  • changes: [PrimordialRecordChange]
  • nextCheckpoint: PrimordialSourceCheckpoint
  • hasMore: Bool

PrimordialRecordSourceError

  • .checkpointExpired, .invalidCheckpoint
  • .invalidSource, .malformedPage, .unavailable

PrimordialSynchronizationOptions

  • mode: PrimordialSynchronizationMode
  • batchSize: Int, default 100
  • init(mode:batchSize:)

PrimordialSynchronizationMode

  • .automatic, .incremental, .snapshot

PrimordialSynchronizationEvent

  • .progress(PrimordialSynchronizationProgress)
  • .completed(PrimordialSynchronizationReport)

PrimordialSynchronizationProgress

  • phase: PrimordialSynchronizationPhase
  • changedRecords: Int
  • Phases: .readingSource, .validating, .embedding, .committing, .ready

PrimordialSynchronizationReport

  • changedRecords, removedRecords
  • reusedEmbeddings, generatedEmbeddings

PrimordialSynchronizationStatus

  • sourceIdentifier, sourceSchemaVersion
  • hasCheckpoint, requiresSnapshot
  • lastCompletedAt, lastReport

PrimordialFilter

  • .all, .any, .not
  • .field(String, PrimordialFilterComparison)

PrimordialFilterComparison

  • .equals, .notEquals, .oneOf
  • .lessThan, .lessThanOrEqual
  • .greaterThan, .greaterThanOrEqual
  • .contains(String)

PrimordialMatch

  • source: PrimordialSource
  • collection, recordID, field
  • excerpt, context: [String], fields, score, sourceRange

context describes where the chunk belongs, such as its Markdown heading path.

PrimordialCollectionStatistics

  • recordCount, fieldCount, chunkCount
  • embeddingModelID, embeddingDimensions, chunkingVersion
  • storageUsage: PrimordialStorageUsage

PrimordialIndexProgress

  • phase: PrimordialIndexPhase
  • completedRecords: Int: records prepared for the new index, not records committed.
  • totalRecords: Int: fixed record count for the operation.
  • fractionCompleted: Double: overall progress from 0 to 1.
  • Phases: .validating, .embedding, .committing, .ready.

Use .ready to identify a saved, usable index. See reindexing progress for the upcoming per-record updates, preparation percentages, and skipped intermediate counts.

PrimordialCollectionError

See Errors for all cases.

Grounded answers

Declarations

func answer(
    _ question: String,
    using collections: [PrimordialCollection],
    options: PrimordialAnswerOptions = .init(),
    generationOptions: PrimordialGenerationOptions = .default
) async throws -> PrimordialAnswer

func streamAnswer(
    _ question: String,
    using collections: [PrimordialCollection],
    options: PrimordialAnswerOptions = .init(),
    generationOptions: PrimordialGenerationOptions = .default
) -> AsyncThrowingStream<PrimordialAnswerEvent, any Error>

func answer(
    _ question: String,
    using files: PrimordialFiles,
    options: PrimordialRetrievalOptions = .init(),
    generationOptions: PrimordialGenerationOptions = .default
) async throws -> PrimordialAnswer

func streamAnswer(
    _ question: String,
    using files: PrimordialFiles,
    options: PrimordialRetrievalOptions = .init(),
    generationOptions: PrimordialGenerationOptions = .default
) -> AsyncThrowingStream<PrimordialAnswerEvent, any Error>

func answer(
    _ question: String,
    using sources: PrimordialSources,
    options: PrimordialRetrievalOptions = .init(),
    generationOptions: PrimordialGenerationOptions = .default
) async throws -> PrimordialAnswer

func streamAnswer(
    _ question: String,
    using sources: PrimordialSources,
    options: PrimordialRetrievalOptions = .init(),
    generationOptions: PrimordialGenerationOptions = .default
) -> AsyncThrowingStream<PrimordialAnswerEvent, any Error>

Supporting types

PrimordialAnswerOptions

  • fields, contextFields, weights, filter
  • resultLimit, contextCharacterLimit, searchStrategy
  • emptySourcesResponse: String
  • init(fields:contextFields:weights:filter:resultLimit:contextCharacterLimit:searchStrategy:emptySourcesResponse:)

contextFields: [String] defaults to []. It adds stored metadata to the source context after retrieval. See Answer options.

emptySourcesResponse defaults to "I couldn't find anything relevant.". Answers, source-backed chat questions about content, and grounded text tasks return it without generation when no sources remain. Structured tasks ignore this option. See Empty sources.

PrimordialAnswer

  • text: String
  • reasoningSummary: String?
  • citations: [PrimordialCitation]
  • metrics: PrimordialGenerationMetrics

PrimordialCitation

  • source: PrimordialSource
  • collection, recordID, field
  • excerpt, fields, sourceRange

PrimordialSource

  • .collection(name:recordID:field:)
  • .file(name:)

PrimordialAnswerEvent

  • .fragment(String)
  • .reasoningSummary(String)
  • .completed(PrimordialAnswer)

Chat

Declarations

// PrimordialClient
func chat(
    messages: [PrimordialChatMessage] = [],
    generationOptions: PrimordialGenerationOptions = .default
) throws -> PrimordialChat
func chat(
    using collections: [PrimordialCollection],
    options: PrimordialAnswerOptions = .init(),
    messages: [PrimordialChatMessage] = [],
    generationOptions: PrimordialGenerationOptions = .default
) throws -> PrimordialChat
func chat(
    using files: PrimordialFiles,
    options: PrimordialRetrievalOptions = .init(),
    messages: [PrimordialChatMessage] = [],
    generationOptions: PrimordialGenerationOptions = .default
) throws -> PrimordialChat
func chat(
    using sources: PrimordialSources,
    options: PrimordialRetrievalOptions = .init(),
    messages: [PrimordialChatMessage] = [],
    generationOptions: PrimordialGenerationOptions = .default
) throws -> PrimordialChat

// PrimordialChat
var messages: [PrimordialChatMessage] { get }
func send(_ text: String, generationOptions: PrimordialGenerationOptions? = nil) async throws -> PrimordialChatMessage
func send(
    _ text: String,
    generationOptions: PrimordialGenerationOptions? = nil,
    onStage: @escaping @MainActor @Sendable (PrimordialChatStage) -> Void
) async throws -> PrimordialChatMessage
nonisolated func stream(
    _ text: String,
    generationOptions: PrimordialGenerationOptions? = nil
) -> AsyncThrowingStream<PrimordialChatEvent, any Error>
func clear() throws
func reset() throws

onStage runs on the main actor. stream(_:) emits the same activity hints as .stage events. Stages can be skipped; clear the displayed status when send returns or throws, or when streaming ends.

Supporting types

PrimordialChat

  • messages: [PrimordialChatMessage]
  • send(_:), stream(_:)
  • clear(), reset()

PrimordialChatMessage

  • role: PrimordialChatRole
  • text: String
  • reasoningSummary: String?
  • citations: [PrimordialCitation]
  • metrics: PrimordialGenerationMetrics
  • init(role:text:reasoningSummary:citations:metrics:)

PrimordialChatRole

  • .user
  • .assistant

PrimordialChatStage

  • .analyzingMessage
  • .searchingSources
  • .answering

PrimordialChatEvent

  • .stage(PrimordialChatStage)
  • .fragment(String)
  • .reasoningSummary(String)
  • .completed(PrimordialChatMessage)

Speech

Declarations

func transcribe(_ audioURL: URL) async throws -> PrimordialTranscription
func recording(localeIdentifier: String = "en-US") -> PrimordialRecordingSession

func start(
    onUpdate: (@MainActor @Sendable (PrimordialRecordingUpdate) -> Void)? = nil
) async throws
func pause() async throws
func resume() async throws
func stop() async throws -> PrimordialRecordingResult
func cancel() async

Supporting types

PrimordialTranscription

  • text: String
  • segments: [PrimordialTranscriptSegment]
  • languageIdentifier: String?
  • duration: TimeInterval

PrimordialTranscriptSegment

  • text: String
  • startTime: TimeInterval
  • endTime: TimeInterval

PrimordialRecordingUpdate

  • liveText, confirmedText
  • isFinal, isDualTrack
  • state: PrimordialRecordingState

PrimordialRecordingState

  • .idle, .recording, .paused
  • .stopping, .ended

PrimordialRecordingResult

  • transcription: PrimordialTranscription
  • audioData: Data?

PrimordialRecordingSession

  • start(onUpdate:)
  • pause() async throws
  • resume() async throws
  • stop() async throws -> PrimordialRecordingResult
  • cancel()

Advanced API

primordial.advanced APIs provide deliberate low-level control.

Declarations

func embed(_ input: String) async throws -> PrimordialEmbedding
func embed(_ inputs: [String]) async throws -> [PrimordialEmbedding]
func session(
    prompt: String = "",
    messages: [PrimordialChatMessage] = [],
    generationOptions: PrimordialGenerationOptions = .default
) throws -> PrimordialAdvancedGenerationSession
func vectorStore(_ name: String) throws -> PrimordialRawVectorStore

// PrimordialAdvancedGenerationSession
func generate(_ input: String, generationOptions: PrimordialGenerationOptions? = nil) async throws -> String
nonisolated func stream(_ input: String, generationOptions: PrimordialGenerationOptions? = nil) -> AsyncThrowingStream<PrimordialTextChunk, any Error>
func clear() throws
func reset() throws

// PrimordialAdvancedResource
func load() async throws
func unload() async throws
func removeDownload() async throws
func storageUsage() async throws -> PrimordialResourceStorageUsage
func residency() async -> PrimordialResourceResidency
func residencyUpdates() -> AsyncStream<PrimordialResourceResidency>

// PrimordialAdvanced
func recording(
    localeIdentifier: String = "en-US"
) -> PrimordialAdvancedRecordingSession

// PrimordialAdvancedRecordingSession
nonisolated let updates: AsyncStream<PrimordialRecordingUpdate>
func requestAuthorization() async throws
func start() async throws
func pause() async throws
func resume() async throws
func stop() async throws -> PrimordialRecordingResult
func cancel() async

Supporting types

PrimordialAdvanced

  • embed(_: String), embed(_: [String])
  • session(prompt:messages:generationOptions:)
  • vectorStore(_:)
  • recording(localeIdentifier:)
  • generation, embedding, speech

PrimordialAdvancedResource

  • load()
  • unload()
  • removeDownload()
  • storageUsage()
  • residency(), residencyUpdates()

PrimordialResourceResidencyState

  • .unloaded, .loading, .loaded, .unloading
  • .failed(PrimordialAIError)

PrimordialResourceResidency

  • model: PrimordialModel
  • state: PrimordialResourceResidencyState
  • isRetained: Bool
  • activeLeaseCount: Int

PrimordialAdvancedGenerationSession

  • messages: [PrimordialChatMessage]
  • generate(_:), stream(_:)
  • clear(), reset()

PrimordialAdvancedRecordingSession

  • updates: AsyncStream<PrimordialRecordingUpdate>
  • requestAuthorization()
  • start(), pause(), resume()
  • stop(), cancel()

Advanced vector store

Declarations

actor PrimordialRawVectorStore {
    func upsert(_ records: [VectorRecord]) async throws
    func search(
        _ query: String,
        limit: Int = 8,
        threshold: Double? = nil,
        filter: VectorFilter? = nil,
        spaces: [String]? = nil,
        strategy: PrimordialSearchStrategy = .hybrid
    ) async throws -> [VectorSearchResult]
    func search(
        _ embedding: PrimordialEmbedding,
        limit: Int = 8,
        threshold: Double? = nil,
        filter: VectorFilter? = nil,
        spaces: [String]? = nil
    ) async throws -> [VectorSearchResult]
    func delete(ids: [String]) async throws
    func delete(where filter: VectorFilter) async throws
    func reindex(where filter: VectorFilter? = nil) async throws
    func status() async throws -> VectorStoreStatus
    func removeAll() async throws
}

Supporting types

PrimordialRawVectorStore

A Primordial-owned actor for isolated vector records, hybrid or explicit text search, semantic embedding search, deletion, reindexing, status, and removal.

PrimordialEmbedding

  • values: [Float]
  • model: PrimordialEmbeddingModel
  • init(values:model:)

VectorRecord

  • id, metadata, representations
  • init(id:text:metadata:embeddingText:)
  • init(id:metadata:representations:)

VectorRepresentation

  • .defaultSpace
  • space, text, embeddingText, embedding
  • embeddingInput
  • init(space:text:embeddingText:embedding:)

VectorEmbeddingSchema

  • dimensions
  • .d384Cosine, .d768Cosine
  • .d1024Cosine, .d1536Cosine

VectorMetadataValue

  • .string, .stringArray, .int
  • .double, .bool, .date

VectorFilter

  • .all, .any, .not
  • .condition(key:comparison:)
  • .where(_:_:)

VectorFilterComparison

  • .equals, .notEquals, .in
  • .lessThan, .lessThanOrEqual
  • .greaterThan, .greaterThanOrEqual
  • .contains(String)

PrimordialSearchStrategy

  • .hybrid, .semantic, .lexical

VectorSearchResult

  • id, score, text
  • matchedSpace, metadata

VectorStoreStatus

  • recordCount, embeddingCount, spaces
  • embeddingModelID, embeddingDimensions, lastUpdatedAt

VectorStoreError

See Errors for all cases.

Errors and cancellation

SDK failures use stable typed errors. Cancelling a Swift task remains CancellationError and is not converted into an SDK error.

Call cancel() on the Swift task running the request. For a stream, cancel the task containing the stream loop. Your app must connect this to its Stop button or screen navigation.

Examples: text generation, answers, and chat replies.

Error types

PrimordialAIError

  • .capabilityUnavailable, .unsupportedFeature
  • .invalidConfiguration, .invalidQuery, .invalidRecord
  • .contextWindowExceeded, .generationFailed, .embeddingFailed
  • .transcriptionFailed, .recordingFailed, .structuredOutputInvalid
  • .permissionDenied, .resourceConflict, .resourceOperationFailed
  • .insufficientStorage, .downloadFailed, .verificationFailed, .corruptedStorage

PrimordialActivationError

  • .activationRequired, .evaluationKeyRequired
  • .evaluationKeyInvalid, .evaluationKeyRevoked, .evaluationKeyExpired
  • .activationMetadataMissing, .unregisteredAppIdentifier
  • .invalidActivationResponse, .activationRequestFailed, .activationServerError
  • .licenseRequired, .licenseMissing, .licenseMalformed
  • .licenseInvalidSignature, .licenseUnknownKey, .licenseUnsupportedVersion
  • .licenseWrongAppIdentifier, .licenseWrongPublisherId, .licenseWrongPlatform, .licenseWrongChannel
  • .licenseExpired, .featureNotLicensed, .sdkVersionNotAllowed, .productionLicenseRequired

PrimordialCollectionError

  • .invalidName, .invalidClientIdentifier
  • .invalidRecord, .invalidField, .invalidQuery
  • .invalidSynchronizationOptions, .sourceManaged, .checkpointRequired
  • .sourceMismatch, .sourceSchemaMismatch
  • .recordNotFound, .incompatibleIndex, .operationFailed

PrimordialFileError

  • .noFiles, .invalidURL, .duplicateFileName
  • .unsupportedFormat, .unreadable, .fileNotFound
  • .invalidEncoding, .empty, .tooLarge
  • .invalidWorkspaceName, .removed, .resourceConflict, .operationFailed

PrimordialRecordSourceError

  • .checkpointExpired, .invalidCheckpoint
  • .invalidSource, .malformedPage, .unavailable

VectorStoreError

  • .unavailable, .embeddingProviderRequired, .embeddingGenerationFailed
  • .invalidRecord, .invalidMetadata, .invalidEmbeddingModel
  • .invalidVectorDimensions
  • .unsupportedEmbeddingSchema, .unsupportedEmbeddingModel
  • .embeddingModelNotDownloaded, .embeddingModelNotLoaded
  • .storeInitializationFailed, .storageOperationFailed