### Quick Start: Initialize Chroma and Add Documents Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md Initializes Chroma in memory, creates a collection, adds documents with embeddings and metadata, and performs a nearest-neighbor query. Ensure Chroma is initialized before any collection or document operations. ```swift import Chroma try Chroma.initialize(allowReset: true) let collectionName = "my_collection" _ = try Chroma.createCollection(name: collectionName) let ids = ["cats_doc", "dogs_doc"] let embeddings: [[Float]] = [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0] ] let documents = [ "Cats are small carnivores often kept as companion animals.", "Dogs are domesticated canids known for companionship and work." ] let metadatas: [ChromaMetadata?] = [ [ "source_url": "file:///knowledge/animals/cats.txt", "content_type": "text/plain" ], [ "source_url": "file:///knowledge/animals/dogs.md", "content_type": "text/markdown", "reviewed": true ] ] _ = try Chroma.addDocuments( collectionName: collectionName, ids: ids, embeddings: embeddings, documents: documents, metadatas: metadatas ) let result = try Chroma.queryCollection( collectionName: collectionName, queryEmbeddings: [[1.0, 0.0, 0.0]], nResults: 1, whereFilter: nil, ids: nil, include: ["documents"] ) let topId = result.ids[0][0] let topDocument = result.documents[0][0] ?? "" print("Top match: \(topId) -> \(topDocument)") // expected: Top match: cats_doc -> Cats are small carnivores often kept as companion animals. ``` -------------------------------- ### Invoke Chroma Skill in Prompts Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md Refer to the installed Chroma skill by its name in your prompts to leverage its capabilities. ```text Use the chroma skill to review my collection schema and retrieval flow, then propose fixes. ``` -------------------------------- ### Get Documents with Filtering and Pagination in Swift Source: https://context7.com/chroma-core/chroma-swift/llms.txt Retrieves documents from a collection using various filters like IDs, metadata, and document content. Supports pagination and selective field inclusion. Ensure Chroma is initialized and the collection exists before calling. ```swift import Chroma try Chroma.initialize(allowReset: true) _ = try Chroma.createCollection(name: "pages") _ = try Chroma.addDocuments( collectionName: "pages", ids: ["p1", "p2", "p3", "p4", "p5"], embeddings: [[1,0],[0,1],[1,1],[0,0],[1,0.5]], documents: ["alpha", "beta", "gamma", "delta", "epsilon"] ) // Fetch by specific IDs, requesting only documents let byIds = try Chroma.getDocuments( collectionName: "pages", ids: ["p1", "p3"], whereClause: nil, limit: nil, offset: nil, whereDocument: nil, include: ["documents"] ) print("IDs: \(byIds.ids.sorted())") // ["p1", "p3"] print("Docs: \(byIds.documents?.compactMap{$0}.sorted() ?? [])") // ["alpha", "gamma"] // Paginate: page 1 (2 items), page 2 (2 items) let page1 = try Chroma.getDocuments( collectionName: "pages", ids: nil, whereClause: nil, limit: 2, offset: 0, whereDocument: nil, include: ["documents"] ) let page2 = try Chroma.getDocuments( collectionName: "pages", ids: nil, whereClause: nil, limit: 2, offset: 2, whereDocument: nil, include: ["documents"] ) print("Page1 count: \(page1.ids.count)") // 2 print("Page2 count: \(page2.ids.count)") // 2 // Request embeddings back let withEmb = try Chroma.getDocuments( collectionName: "pages", ids: ["p1"], whereClause: nil, limit: nil, offset: nil, whereDocument: nil, include: ["embeddings", "documents"] ) print("Has embeddings: \(withEmb.embeddings != nil)") // true ``` -------------------------------- ### Switch to Local Framework Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md Execute this script to point the package manifest to a local framework build instead of downloading from GitHub Releases. Use this for local debugging. ```bash ./scripts/use_local_framework.sh ``` -------------------------------- ### Get All Documents from Collection in Swift Source: https://context7.com/chroma-core/chroma-swift/llms.txt Retrieves all document IDs and their text content from a specified collection. This method is useful for a complete dump of a collection's documents. Ensure Chroma is initialized and the collection exists. ```swift import Chroma try Chroma.initialize(allowReset: true) _ = try Chroma.createCollection(name: "notes") _ = try Chroma.addDocuments( collectionName: "notes", ids: ["n1", "n2"], embeddings: [[1,0],[0,1]], documents: ["First note content.", "Second note content."] ) let result = try Chroma.getAllDocuments(collectionName: "notes") print("IDs: \(result.ids)") // ["n1", "n2"] (order may vary) print("Docs: \(result.documents)") // ["First note content.", "Second note content."] ``` -------------------------------- ### Switch to Release Framework (Alternative) Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md An alternative method to switch back to the release framework, often used after publishing. Requires URL and checksum. ```bash ./scripts/use_release_framework.sh ``` -------------------------------- ### Chroma.initializeWithPath(path:allowReset:) Source: https://context7.com/chroma-core/chroma-swift/llms.txt Initializes Chroma with a persistent on-disk store. Data at the specified path will be preserved across application launches. Ensure `allowReset` is set to `false` in production to prevent data loss. ```APIDOC ## Chroma.initializeWithPath(path:allowReset:) ### Description Initializes Chroma with a persistent on-disk store. Use the same path across app launches to retain data. Set `allowReset: false` in production to prevent accidental data loss. ### Method `Chroma.initializeWithPath(path: URL, allowReset: Bool)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import Chroma let chromaPath = URL.documentsDirectory .appendingPathComponent("chroma_db") .path do { try Chroma.initializeWithPath(path: chromaPath, allowReset: false) print("Chroma initialized at: \(chromaPath)") // Data is preserved between app sessions at this path } catch { print("Failed to initialize persistent store: \(error.localizedDescription)") } ``` ### Response #### Success Response Initializes the Chroma database with a persistent store. No direct return value, but subsequent calls to Chroma APIs will succeed. #### Response Example None (throws on failure) ``` -------------------------------- ### Switch to Release Framework Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md Use this script to revert to using the release framework from GitHub. You need to provide the download URL and checksum from the GitHub release asset. ```bash ./scripts/use_release_framework.sh ``` -------------------------------- ### Initialize and Manage Chroma Core Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md Functions for initializing the Chroma client, resetting the database, and retrieving system information like version and batch size. Ensure `allowReset` is true if `reset()` is needed. ```swift func initialize(allowReset: Bool) throws ``` ```swift func initializeWithPath(path: String?, allowReset: Bool) throws ``` ```swift func reset() throws ``` ```swift func getVersion() throws -> String ``` ```swift func getMaxBatchSize() throws -> UInt32 ``` ```swift func heartbeat() throws -> Int64 ``` -------------------------------- ### Initialize Chroma with Persistent On-Disk Store Source: https://context7.com/chroma-core/chroma-swift/llms.txt Initializes Chroma with a persistent on-disk store. Use the same path across app launches to retain data. Set `allowReset` to `false` in production to prevent accidental data loss. ```swift import Chroma let chromaPath = URL.documentsDirectory .appendingPathComponent("chroma_db") .path do { try Chroma.initializeWithPath(path: chromaPath, allowReset: false) print("Chroma initialized at: \(chromaPath)") // Data is preserved between app sessions at this path } catch { print("Failed to initialize persistent store: \(error.localizedDescription)") } ``` -------------------------------- ### Initialize Chroma and Add Documents with Local Embeddings Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md Initializes Chroma, creates a collection, and adds documents using a local embedding model. Ensure the model is loaded before adding documents. Querying can be done directly with text. ```swift import Chroma // Initialize Chroma and create a collection try Chroma.initialize(allowReset: true) let collectionName = "my_collection" let collectionId = try Chroma.createCollection(name: collectionName) // Create an embedder with your chosen model let embedder = ChromaEmbedder(model: .miniLML6) // Load the model (only needs to be done once) await embedder.loadModel() // Add documents with automatic embedding let ids = ["doc1", "doc2"] let texts = ["Document 1 text", "Document 2 text"] let count = try await embedder.addDocuments( to: collectionName, ids: ["doc1", "doc2"], texts: ["Document 1 text", "Document 2 text"] ) // Query using text instead of pre-computed embeddings let results = try await embedder.queryCollection( collectionName, queryText: "similar document", nResults: 5 ) ``` -------------------------------- ### Chroma.initialize(allowReset:) Source: https://context7.com/chroma-core/chroma-swift/llms.txt Initializes Chroma with an in-memory (ephemeral) store. This must be called before any collection or document operations. Setting `allowReset` to true is recommended for test/development environments. ```APIDOC ## Chroma.initialize(allowReset:) ### Description Initializes Chroma with an in-memory (ephemeral) store. Must be called before any collection or document operation. Pass `allowReset: true` in test or development environments to allow `Chroma.reset()`; set it to `false` in production. ### Method `Chroma.initialize(allowReset: Bool)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import Chroma do { try Chroma.initialize(allowReset: true) print("Chroma initialized (ephemeral)") let version = try Chroma.getVersion() let heartbeat = try Chroma.heartbeat() let maxBatch = try Chroma.getMaxBatchSize() print("version: \(version), heartbeat: \(heartbeat), maxBatch: \(maxBatch)") } catch { print("Initialization failed: \(error.localizedDescription)") } ``` ### Response #### Success Response Initializes the Chroma database. No direct return value, but subsequent calls to Chroma APIs will succeed. #### Response Example None (throws on failure) ``` -------------------------------- ### Initialize Chroma with Persistent Storage Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md Initialize Chroma with a specific file path for persistent storage. Ensure the same path is used on subsequent launches to preserve data. ```swift let chromaDirectory = URL.documentsDirectory .appendingPathComponent("chroma_db") .path try Chroma.initializeWithPath(path: chromaDirectory, allowReset: false) // Data will be preserved between app sessions ``` -------------------------------- ### Troubleshoot: Reset Fails Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md If `reset()` fails, it might be because initialization did not allow it. Initialize with `allowReset: true` if reset functionality is required. ```swift initialize with `allowReset: true` ``` -------------------------------- ### Chroma Core Functions Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md Provides functions for initializing the Chroma client, managing the system state, and retrieving system information. ```APIDOC ## Initialization and System ### `initialize(allowReset: Bool)` Initializes the Chroma client. `allowReset` determines if the database can be reset. ### `initializeWithPath(path: String?, allowReset: Bool)` Initializes the Chroma client with a specified path for data storage. ### `reset()` Resets the Chroma database. Requires initialization with `allowReset: true`. ### `getVersion()` Returns the current version of the Chroma client. ### `getMaxBatchSize()` Returns the maximum batch size supported by the Chroma client. ### `heartbeat()` Ping the Chroma server to check its status. Returns a timestamp. ## Collections ### `createCollection(name: String)` Creates a new collection with the given name. This operation is idempotent by name. ### `getCollection(collectionName: String)` Retrieves information about a specific collection. ### `listCollections()` Returns a list of all collection names. ### `updateCollection(collectionName: String, newName: String?)` Updates an existing collection's name. ### `deleteCollection(collectionName: String)` Deletes a collection by its name. ### `countCollections()` Returns the total number of collections. ## Documents ### `addDocuments(collectionName: String, ids: [String], embeddings: [[Float]], documents: [String])` Adds documents to a collection with provided IDs, embeddings, and content. ### `addDocuments(collectionName: String, ids: [String], embeddings: [[Float]], documents: [String], metadatas: [ChromaMetadata?])` Adds documents to a collection with provided IDs, embeddings, content, and metadata. ### `getAllDocuments(collectionName: String)` Retrieves all documents from a specified collection. ### `getDocuments(collectionName: String, ids: [String]?, whereClause: String?, limit: UInt32?, offset: UInt32?, whereDocument: String?, include: [String]?)` Retrieves documents from a collection with advanced filtering and inclusion options. `include` controls optional return fields like `["embeddings"]`. ### `updateDocuments(collectionName: String, ids: [String], embeddings: [[Float]]?, documents: [String]?)` Updates existing documents in a collection. Can update embeddings and content. ### `upsertDocuments(collectionName: String, ids: [String], embeddings: [[Float]]?, documents: [String]?)` Upserts documents into a collection. Inserts new IDs and updates existing ones. ### `deleteDocuments(collectionName: String, ids: [String]?)` Deletes documents from a collection by their IDs. If `ids` is nil, deletes all documents. ### `countDocuments(collectionName: String)` Returns the total number of documents in a collection. Use for authoritative counts. ## Queries ### `queryCollection(collectionName: String, queryEmbeddings: [[Float]], nResults: UInt32, whereFilter: String?, ids: [String]?, include: [String]?)` Queries a collection using embeddings. `nResults` specifies the number of results, and `include` can specify fields like `["embeddings"]`. ## Databases ### `createDatabase(name: String)` Creates a new database with the given name. ### `getDatabase(name: String)` Retrieves information about a specific database. ### `listDatabases()` Returns a list of all database names. ### `deleteDatabase(name: String)` Deletes a database by its name. ``` -------------------------------- ### Troubleshoot: Metadata Write Not Supported Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md If metadata writes fail, the current binary may not support it. Omit metadata or pass only `nil` placeholders for writes. ```swift omit metadata on writes or pass only `nil` metadata placeholders ``` -------------------------------- ### Rebuild Swift Bindings Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md Run this script to rebuild the Swift bindings for Chroma. This is typically done when iterating on Rust bindings. ```bash cd ../chroma/rust/swift_bindings ./build_swift_package.sh ``` -------------------------------- ### Database APIs: `createDatabase`, `getDatabase`, `listDatabases`, `deleteDatabase` Source: https://context7.com/chroma-core/chroma-swift/llms.txt Provides APIs for database-level operations, suitable for multi-tenant or namespace-separated deployments. These functions allow for the creation, retrieval, listing, and deletion of databases, each identified by a name string. ```APIDOC ## Database APIs: `createDatabase` / `getDatabase` / `listDatabases` / `deleteDatabase` ### Description Provides APIs for database-level operations, suitable for multi-tenant or namespace-separated deployments. These functions allow for the creation, retrieval, listing, and deletion of databases, each identified by a name string. ### Methods #### `createDatabase(name: String)` Creates a new database with the specified name. #### `getDatabase(name: String)` Retrieves information about a database by its name. Returns a `DatabaseInfo` struct. #### `listDatabases()` Returns a list of all available database names. #### `deleteDatabase(name: String)` Deletes a database with the specified name. ### Parameters - **name** (String) - Required - The name of the database to create, retrieve, or delete. ### Request Example ```swift // Create a database let dbId = try Chroma.createDatabase(name: "tenant_acme") // Get database info let info = try Chroma.getDatabase(name: "tenant_acme") // List all databases let all = try Chroma.listDatabases() // Delete a database try Chroma.deleteDatabase(name: "tenant_acme") ``` ### Response - `createDatabase`: Returns the ID of the created database. - `getDatabase`: Returns a `DatabaseInfo` struct containing database details. - `listDatabases`: Returns an array of strings, where each string is a database name. - `deleteDatabase`: Does not return a value upon success, but may throw an error. ``` -------------------------------- ### Initialize Chroma Embedder with MLX Models Source: https://context7.com/chroma-core/chroma-swift/llms.txt Wraps MLXEmbedders for on-device text embedding. Initialize with a model case and call `loadModel()` before use. The default model is `.miniLML6`. ```swift import Chroma // Default model: MiniLM-L6-v2 (balanced quality/speed) let embedder = ChromaEmbedder() print("Model: \(embedder.model.displayName)") // "MiniLM L6 v2" print("Dimensions: \(embedder.embeddingDimensions)") // 384 // Heavy-weight model for desktop (1024 dimensions) let largeEmbedder = ChromaEmbedder(model: .bgeLarge) print("Large model: \(largeEmbedder.model.displayName)") // "BGE Large EN v1.5" // Load model before use (async, downloads from Hugging Face on first run) do { try await embedder.loadModel() print("Model loaded. Info: \(embedder.modelInfo)") // {"model_id": "sentence-transformers/all-MiniLM-L6-v2", // "embedding_dimensions": 384, "is_loaded": true, ...} } catch let error as ChromaEmbedderError { print("Load failed: \(error.localizedDescription)") } ``` -------------------------------- ### Initialize Chroma with In-Memory Store Source: https://context7.com/chroma-core/chroma-swift/llms.txt Initializes Chroma with an ephemeral, in-memory store. This must be called before any collection or document operations. Set `allowReset` to `true` for testing to enable `Chroma.reset()`, and `false` for production. ```swift import Chroma do { try Chroma.initialize(allowReset: true) print("Chroma initialized (ephemeral)") let version = try Chroma.getVersion() let heartbeat = try Chroma.heartbeat() let maxBatch = try Chroma.getMaxBatchSize() print("version: \(version), heartbeat: \(heartbeat), maxBatch: \(maxBatch)") } catch { print("Initialization failed: \(error.localizedDescription)") } ``` -------------------------------- ### Add Chroma Swift to Package.swift Source: https://context7.com/chroma-core/chroma-swift/llms.txt Add the Chroma Swift package to your project's Package.swift file and import the Chroma product in your target. ```swift // Package.swift dependencies: [ .package(url: "https://github.com/chroma-core/chroma-swift.git", from: "1.0.2") ], targets: [ .target( name: "YourApp", dependencies: [ .product(name: "Chroma", package: "ChromaSwift") ] ) ] ``` ```swift import Chroma ``` -------------------------------- ### Zip XCFramework for Release Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md This command zips the built XCFramework artifact for distribution. Ensure you are in the correct directory before running. ```bash cd chroma/rust/swift_bindings/Chroma ditto -c -k --sequesterRsrc --keepParent chroma_swift_framework.xcframework chroma_swift_framework.xcframework.zip ``` -------------------------------- ### Behavior Details Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md Important behavioral notes for using Chroma Swift functions. ```APIDOC ## Behavior Details - `createCollection(name:)` is idempotent by name. - `upsertDocuments(...)` inserts new IDs and updates existing IDs. - `deleteDocuments(collectionName:ids: nil)` deletes all documents in the collection. - `queryCollection(..., nResults: large)` returns only available matches. - `include` controls optional return fields. Example: `include: ["embeddings"]` to receive embeddings from `getDocuments`. - `decodedMetadatas()` converts metadata JSON strings to `[ChromaMetadata?]`. - Use `countDocuments(collectionName:)` for an authoritative post-write document count. - `FfiConverter*` and `uniffiEnsureChromaSwiftInitialized()` are generated UniFFI scaffolding, not application-level API. ``` -------------------------------- ### Initialize and Use Chroma Embedder Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md Functions for initializing and using the Chroma embedder, including loading the model, embedding single texts or batches, and performing collection queries. Call `loadModel()` before using `embed` or embedder query functions. ```swift public init(model: ChromaEmbedder.EmbeddingModel = .miniLML6) ``` ```swift public func loadModel() async throws ``` ```swift public func embed(text: String) async throws -> [Float] ``` ```swift public func embed(texts: [String]) async throws -> [[Float]] ``` ```swift public func addDocuments(to collectionName: String, ids: [String], texts: [String], metadatas: [ChromaMetadata?]? = nil) async throws -> UInt32 ``` ```swift public func queryCollection(_ collectionName: String, queryTexts: [String], nResults: UInt32 = 10, whereFilter: String? = nil, ids: [String]? = nil, include: [String]? = nil) async throws -> QueryResult ``` ```swift public func queryCollection(_ collectionName: String, queryText: String, nResults: UInt32 = 10, whereFilter: String? = nil, ids: [String]? = nil, include: [String]? = nil) async throws -> QueryResult ``` ```swift public func createCollection(name: String) throws -> String ``` ```swift public var modelInfo: [String: Any] { get } ``` -------------------------------- ### `ChromaEmbedder` Initialization and Model Loading Source: https://context7.com/chroma-core/chroma-swift/llms.txt Initializes `ChromaEmbedder` for on-device text embedding using MLXEmbedders models. Models must be loaded using `loadModel()` before embedding can occur. ```APIDOC ## `ChromaEmbedder` — Initialization and Model Loading ### Description Initializes `ChromaEmbedder` for on-device text embedding using MLXEmbedders models. Models must be loaded using `loadModel()` before embedding can occur. ### Initialization ```swift // Initialize with the default model (MiniLM-L6-v2) let embedder = ChromaEmbedder() // Initialize with a specific model (e.g., BGE Large) let largeEmbedder = ChromaEmbedder(model: .bgeLarge) ``` ### Model Loading ```swift // Load the model (asynchronous operation) do { try await embedder.loadModel() } catch let error as ChromaEmbedderError { print("Load failed: \(error.localizedDescription)") } ``` ### Properties - **model**: The selected embedding model. - **embeddingDimensions**: The dimensionality of the embeddings generated by the model. - **modelInfo**: A dictionary containing detailed information about the loaded model. ### Usage After loading the model, you can use the `ChromaEmbedder` instance to generate embeddings for text. ``` -------------------------------- ### Import Chroma Module Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md Import the Chroma module into your Swift files where you intend to use its functionalities. ```swift import Chroma ``` -------------------------------- ### Construct and Decode Chroma Metadata Source: https://context7.com/chroma-core/chroma-swift/llms.txt Illustrates creating `ChromaMetadata` with various value types (`string`, `int`, `float`, `bool`) and decoding metadata from `getDocuments` results. Note that metadata writes are currently unsupported. ```swift import Chroma // Constructing metadata with literal syntax let metadata: ChromaMetadata = [ "source_url": "file:///docs/chapter1.txt", // .string "page_count": 42, // .int(42) "relevance_score": 0.95, // .float(0.95) "reviewed": true // .bool(true) ] // Switch over a value for (key, value) in metadata { switch value { case .string(let s): print("\(key): string(\(s))") case .int(let i): print("\(key): int(\(i))") case .float(let f): print("\(key): float(\(f))") case .bool(let b): print("\(key): bool(\(b))") } } // Decoding metadata returned from getDocuments try Chroma.initialize(allowReset: true) _ = try Chroma.createCollection(name: "meta_col") _ = try Chroma.addDocuments( collectionName: "meta_col", ids: ["doc1"], embeddings: [[1, 0, 0]], documents: ["content"] ) let result = try Chroma.getDocuments( collectionName: "meta_col", ids: nil, whereClause: nil, limit: nil, offset: nil, whereDocument: nil, include: ["metadatas"] ) let decoded: [ChromaMetadata?] = result.decodedMetadatas() print("Decoded metadatas: \(decoded)") ``` -------------------------------- ### Manage Chroma Collections Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md Functions for creating, retrieving, listing, updating, and deleting collections. Collection creation by name is idempotent. ```swift func createCollection(name: String) throws -> String ``` ```swift func getCollection(collectionName: String) throws -> CollectionInfo ``` ```swift func listCollections() throws -> [String] ``` ```swift func updateCollection(collectionName: String, newName: String?) throws ``` ```swift func deleteCollection(collectionName: String) throws ``` ```swift func countCollections() throws -> UInt32 ``` -------------------------------- ### Troubleshoot: Embedding Model Not Loaded Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md If you encounter 'Embedding model not loaded', ensure `loadModel()` is called before `embed` or query functions. This is a common startup requirement. ```swift try await embedder.loadModel() ``` -------------------------------- ### Chroma Database Operations Source: https://context7.com/chroma-core/chroma-swift/llms.txt Manages databases for multi-tenant deployments using `createDatabase`, `getDatabase`, `listDatabases`, and `deleteDatabase`. `getDatabase` returns a `DatabaseInfo` struct. ```swift import Chroma try Chroma.initialize(allowReset: true) let dbId = try Chroma.createDatabase(name: "tenant_acme") print("Created DB ID: \(dbId)") let info = try Chroma.getDatabase(name: "tenant_acme") print("DB name: \(info.name), tenant: \(info.tenant)") let all = try Chroma.listDatabases() print("Databases: \(all)") // ["tenant_acme", ...] try Chroma.deleteDatabase(name: "tenant_acme") print("Deleted. Remaining: \(try Chroma.listDatabases())") ``` -------------------------------- ### `Chroma.reset()` Source: https://context7.com/chroma-core/chroma-swift/llms.txt Clears all collections and documents from the in-memory store. This function is only available if `initialize(allowReset: true)` was used during Chroma initialization and is typically used for testing purposes. ```APIDOC ## `Chroma.reset()` ### Description Clears all collections and documents from the in-memory store. This function is only available if `initialize(allowReset: true)` was used during Chroma initialization and is typically used for testing purposes. ### Method ```swift Chroma.reset() ``` ### Parameters This method does not accept any parameters. ### Request Example ```swift try Chroma.reset() ``` ### Response This method does not return a value upon success, but may throw an error. ``` -------------------------------- ### Chroma.listCollections() / Chroma.countCollections() / Chroma.deleteCollection(collectionName:) Source: https://context7.com/chroma-core/chroma-swift/llms.txt Provides methods to list all collection names, count the total number of collections, and delete a specific collection by its name. Deleting a non-existent collection will result in an error. ```APIDOC ## Chroma.listCollections() / Chroma.countCollections() / Chroma.deleteCollection(collectionName:) ### Description Lists all collection names, counts collections, and deletes a named collection. `deleteCollection` throws if the collection does not exist. ### Methods - `Chroma.listCollections() -> [String]` - `Chroma.countCollections() -> Int` - `Chroma.deleteCollection(collectionName: String)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import Chroma try Chroma.initialize(allowReset: true) _ = try Chroma.createCollection(name: "col_a") _ = try Chroma.createCollection(name: "col_b") _ = try Chroma.createCollection(name: "col_c") let names = try Chroma.listCollections() print("Collections: \(names)") // ["col_a", "col_b", "col_c"] let count = try Chroma.countCollections() print("Count: \(count)") // 3 try Chroma.deleteCollection(collectionName: "col_b") print("After delete: \(try Chroma.listCollections())") // ["col_a", "col_c"] // Deleting nonexistent collection throws do { try Chroma.deleteCollection(collectionName: "nonexistent") } catch { print("Expected error: \(error.localizedDescription)") } ``` ### Response #### Success Response - **listCollections**: Returns an array of strings, where each string is a collection name. - **countCollections**: Returns an integer representing the total number of collections. - **deleteCollection**: No direct return value upon successful deletion. #### Response Example ```json { "listCollections": ["col_a", "col_b", "col_c"], "countCollections": 3 } ``` ``` -------------------------------- ### List, Count, and Delete Chroma Collections Source: https://context7.com/chroma-core/chroma-swift/llms.txt Provides functions to list all collection names, count the total number of collections, and delete a specific collection by name. `deleteCollection` will throw an error if the specified collection does not exist. Ensure Chroma is initialized before using these functions. ```swift import Chroma try Chroma.initialize(allowReset: true) _ = try Chroma.createCollection(name: "col_a") _ = try Chroma.createCollection(name: "col_b") _ = try Chroma.createCollection(name: "col_c") let names = try Chroma.listCollections() print("Collections: \(names)") // ["col_a", "col_b", "col_c"] let count = try Chroma.countCollections() print("Count: \(count)") // 3 try Chroma.deleteCollection(collectionName: "col_b") print("After delete: \(try Chroma.listCollections())") // ["col_a", "col_c"] // Deleting nonexistent collection throws do { try Chroma.deleteCollection(collectionName: "nonexistent") } catch { print("Expected error: \(error.localizedDescription)") } ``` -------------------------------- ### Troubleshoot: Query Missing Text Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md If queries return IDs but missing text, ensure `documents` are requested in the `include` parameter, e.g., `include: ["documents"]`. ```swift include: ["documents"] ``` -------------------------------- ### Manage Chroma Databases Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md Functions for creating, retrieving, listing, and deleting databases. These operations manage the top-level organizational units within Chroma. ```swift func createDatabase(name: String) throws -> String ``` ```swift func getDatabase(name: String) throws -> DatabaseInfo ``` ```swift func listDatabases() throws -> [String] ``` ```swift func deleteDatabase(name: String) throws ``` -------------------------------- ### Add Chroma Product to App Target Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md Include the Chroma product in your application's target dependencies. ```swift .target( name: "YourApp", dependencies: [ .product(name: "Chroma", package: "ChromaSwift") ] ) ``` -------------------------------- ### Create a Chroma Collection Source: https://context7.com/chroma-core/chroma-swift/llms.txt Creates a new collection with a given name. The operation is idempotent by name; calling it multiple times with the same name returns the same collection ID without creating duplicates. Ensure Chroma is initialized before calling. ```swift import Chroma try Chroma.initialize(allowReset: true) do { let collectionId = try Chroma.createCollection(name: "articles") print("Created collection ID: \(collectionId)") // Idempotent: second call returns the same ID let sameId = try Chroma.createCollection(name: "articles") assert(collectionId == sameId) let count = try Chroma.countCollections() print("Total collections: \(count)") // 1 } catch let error as ChromaError { print("Chroma error: \(error.localizedDescription)") } ``` -------------------------------- ### Chroma.createCollection(name:) Source: https://context7.com/chroma-core/chroma-swift/llms.txt Creates a new collection with the specified name. This operation is idempotent; calling it multiple times with the same name will return the same collection ID without creating duplicates. ```APIDOC ## Chroma.createCollection(name:) ### Description Creates a new collection and returns its UUID string. The operation is idempotent by name: calling it twice with the same name returns the same collection ID without creating a duplicate. ### Method `Chroma.createCollection(name: String) -> String` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import Chroma try Chroma.initialize(allowReset: true) do { let collectionId = try Chroma.createCollection(name: "articles") print("Created collection ID: \(collectionId)") // Idempotent: second call returns the same ID let sameId = try Chroma.createCollection(name: "articles") assert(collectionId == sameId) let count = try Chroma.countCollections() print("Total collections: \(count)") // 1 } catch let error as ChromaError { print("Chroma error: \(error.localizedDescription)") } ``` ### Response #### Success Response (200) - **collectionId** (String) - The UUID string of the created or existing collection. #### Response Example ```json { "collectionId": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ``` ``` -------------------------------- ### Compute Checksum for XCFramework Zip Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md Calculate the checksum for the zipped XCFramework. This checksum is required when updating the package manifest for release. ```bash swift package compute-checksum ../chroma/rust/swift_bindings/Chroma/chroma_swift_framework.xcframework.zip ``` -------------------------------- ### Query Collection with ChromaEmbedder Source: https://context7.com/chroma-core/chroma-swift/llms.txt Embed query text(s) on-device and perform nearest-neighbor search within a Chroma collection using `queryCollection`. Supports both single-text and multi-text (batch) queries. ```swift import Chroma try Chroma.initialize(allowReset: true) let embedder = ChromaEmbedder(model: .miniLML6) try await embedder.loadModel() _ = try embedder.createCollection(name: "corpus") _ = try await embedder.addDocuments( to: "corpus", ids: ["swift_doc", "python_doc", "rust_doc"], texts: [ "Swift is Apple's modern programming language.", "Python is widely used in machine learning and data science.", "Rust focuses on systems programming with memory safety." ] ) // Single text query let result = try await embedder.queryCollection( "corpus", queryText: "Apple programming language", nResults: 2, include: ["documents"] ) print("Top result: \(result.ids[0][0])") // "swift_doc" print("Doc: \(result.documents[0][0] ?? "")") // "Swift is Apple's..." // Multi-text batch query let batch = try await embedder.queryCollection( "corpus", queryTexts: ["memory safety systems", "data analysis Python"], nResults: 1, include: ["documents"] ) print("Query 1: \(batch.ids[0][0])") // "rust_doc" print("Query 2: \(batch.ids[1][0])") // "python_doc" ``` -------------------------------- ### `ChromaEmbedder.queryCollection(_:queryText:nResults:)` / `queryCollection(_:queryTexts:nResults:)` Source: https://context7.com/chroma-core/chroma-swift/llms.txt Embeds query text(s) on-device and performs a nearest-neighbor search within a specified collection. Supports both single and multiple query texts for batch processing. ```APIDOC ## `ChromaEmbedder.queryCollection(_:queryText:nResults:)` / `queryCollection(_:queryTexts:nResults:)` ### Description Embeds the query text(s) on-device and runs nearest-neighbor search in one call. Use the single-text variant for interactive queries; use the multi-text variant to batch multiple queries. ### Method Signature - `queryCollection(_: String, queryText: String, nResults: Int, include: [String]? = nil) async throws -> QueryResults` - `queryCollection(_: String, queryTexts: [String], nResults: Int, include: [String]? = nil) async throws -> QueryResults` ### Parameters - **collectionName** (String) - The name of the collection to query. - **queryText** (String) - The text to embed and use for a single query. - **queryTexts** ([String]) - An array of texts to embed and use for batch queries. - **nResults** (Int) - The number of nearest neighbors to return. - **include** ([String]?, Optional) - An array of strings specifying which data to include in the results (e.g., `["documents", "metadatas", "distances"]`). ### Response - **QueryResults** - An object containing the results of the query, including `ids`, `documents`, `metadatas`, and `distances`. ### Example Usage ```swift import Chroma try Chroma.initialize(allowReset: true) let embedder = ChromaEmbedder(model: .miniLML6) try await embedder.loadModel() _ = try embedder.createCollection(name: "corpus") _ = try await embedder.addDocuments( to: "corpus", ids: ["swift_doc", "python_doc", "rust_doc"], texts: [ "Swift is Apple's modern programming language.", "Python is widely used in machine learning and data science.", "Rust focuses on systems programming with memory safety." ] ) // Single text query let result = try await embedder.queryCollection( "corpus", queryText: "Apple programming language", nResults: 2, include: ["documents"] ) print("Top result: \(result.ids[0][0])") print("Doc: \(result.documents[0][0] ?? "")") // Multi-text batch query let batch = try await embedder.queryCollection( "corpus", queryTexts: ["memory safety systems", "data analysis Python"], nResults: 1, include: ["documents"] ) print("Query 1: \(batch.ids[0][0])") print("Query 2: \(batch.ids[1][0])") ``` ``` -------------------------------- ### Reset Chroma Database Source: https://context7.com/chroma-core/chroma-swift/llms.txt Clears all collections and documents from the in-memory store using `reset()`. This is only available if `initialize(allowReset: true)` was used and is typically for testing purposes. ```swift import Chroma try Chroma.initialize(allowReset: true) _ = try Chroma.createCollection(name: "test_col") print(try Chroma.countCollections()) // 1 try Chroma.reset() print(try Chroma.countCollections()) // 0 ``` -------------------------------- ### Inspect Available Embedding Models Source: https://context7.com/chroma-core/chroma-swift/llms.txt Iterate through all available on-device embedding models to inspect their raw value (Hugging Face model ID), display name, and embedding dimensions. Useful for understanding model options. ```swift import Chroma // Inspect all available models for model in ChromaEmbedder.EmbeddingModel.allCases { print("\(model): \(model.displayName) — \(model.embeddingDimensions)d — \(model.rawValue)") } // bgeMicro: BGE Micro v2 — 384d — TaylorAI/bge-micro-v2 (~17 MB, mobile) // gteTiny: GTE Tiny — 384d — TaylorAI/gte-tiny (~25 MB, mobile) // miniLML6: MiniLM L6 v2 — 384d — sentence-transformers/all-MiniLM-L6-v2 (~90 MB) // miniLML12: MiniLM L12 v2 — 384d — sentence-transformers/all-MiniLM-L12-v2 (~130 MB) // bgeSmall: BGE Small EN v1.5 — 384d — BAAI/bge-small-en-v1.5 (~130 MB) // bgeBase: BGE Base EN v1.5 — 768d — BAAI/bge-base-en-v1.5 (~440 MB, desktop) // bgeLarge: BGE Large EN v1.5 —1024d — BAAI/bge-large-en-v1.5 (~1.3 GB) // mixedbreadLarge: Mixedbread Large v1 —1024d — mixedbread-ai/mxbai-embed-large-v1 (~1.3 GB) // Model selection for constrained environments let mobileEmbedder = ChromaEmbedder(model: .bgeMicro) // iOS, low memory let desktopEmbedder = ChromaEmbedder(model: .bgeBase) // macOS, higher quality ``` -------------------------------- ### `ChromaEmbedder.embed(text:)` / `embed(texts:)` Source: https://context7.com/chroma-core/chroma-swift/llms.txt Generates normalized embeddings for single or batch texts. Batch inference is optimized with chunking, padding, and attention masking. Output vectors are L2 normalized to approximately 1.0. ```APIDOC ## `ChromaEmbedder.embed(text:)` / `embed(texts:)` ### Description Generates normalized embeddings for one text or a batch of texts. Batch inference is processed in chunks of 32 with proper padding and attention masking. Output vectors have L2 norm ≈ 1.0. ### Method Signature - `embed(text: String) async throws -> [Float]` - `embed(texts: [String]) async throws -> [[Float]]` ### Parameters #### `embed(text:)` - **text** (String) - The input text to embed. #### `embed(texts:)` - **texts** ([String]) - An array of texts to embed. ### Response - **[Float]** (for single text) or **[[Float]]** (for batch of texts) - An array of embedding vectors, where each vector is an array of Floats. The L2 norm of each vector is approximately 1.0. ### Example Usage ```swift import Chroma let embedder = ChromaEmbedder(model: .bgeMicro) try await embedder.loadModel() // Single text let vec = try await embedder.embed(text: "The quick brown fox") print("Dimensions: \(vec.count)") let norm = sqrt(vec.map { $0 * $0 }.reduce(0, +)) print("L2 norm: \(norm)") // Batch of texts let texts = [ "Cats are independent animals.", "Dogs are loyal companions.", "Birds can fly long distances." ] let vecs = try await embedder.embed(texts: texts) print("Batch count: \(vecs.count)") print("Each dimension: \(vecs[0].count)") ``` ``` -------------------------------- ### Add and Manage Documents in Chroma Source: https://github.com/chroma-core/chroma-swift/blob/master/README.md Functions for adding, retrieving, updating, upserting, and deleting documents within a collection. `upsertDocuments` handles both new and existing IDs. Use `countDocuments` for an authoritative count. ```swift func addDocuments(collectionName: String, ids: [String], embeddings: [[Float]], documents: [String]) throws -> UInt32 ``` ```swift func addDocuments(collectionName: String, ids: [String], embeddings: [[Float]], documents: [String], metadatas: [ChromaMetadata?]) throws -> UInt32 ``` ```swift func getAllDocuments(collectionName: String) throws -> GetResult ``` ```swift func getDocuments(collectionName: String, ids: [String]?, whereClause: String?, limit: UInt32?, offset: UInt32?, whereDocument: String?, include: [String]?) throws -> AdvancedGetResult ``` ```swift func updateDocuments(collectionName: String, ids: [String], embeddings: [[Float]]?, documents: [String]?) ``` ```swift func upsertDocuments(collectionName: String, ids: [String], embeddings: [[Float]]?, documents: [String]?) ``` ```swift func deleteDocuments(collectionName: String, ids: [String]?) throws ``` ```swift func countDocuments(collectionName: String) throws -> UInt32 ```