From 78d738602f6673eb27ea516f1fb5556ac889ee96 Mon Sep 17 00:00:00 2001 From: Suryansh Bisen Date: Thu, 10 Jul 2025 15:23:57 +0530 Subject: [PATCH 1/2] added developer docs for iOS SDK public functions Signed-off-by: Suryansh Bisen --- .../Classes/sources/NimbleNetApi.swift | 66 ++++++- .../sources/dataModel/NimbleNetConfig.swift | 57 ++++++ .../sources/dataModel/NimbleNetResult.swift | 166 +++++++++++++----- .../sources/dataModel/UserEventData.swift | 14 +- 4 files changed, 256 insertions(+), 47 deletions(-) diff --git a/sdks/ios/deliteAI/Classes/sources/NimbleNetApi.swift b/sdks/ios/deliteAI/Classes/sources/NimbleNetApi.swift index bf93a6ef..7504996d 100644 --- a/sdks/ios/deliteAI/Classes/sources/NimbleNetApi.swift +++ b/sdks/ios/deliteAI/Classes/sources/NimbleNetApi.swift @@ -7,16 +7,42 @@ import Foundation import SwiftProtobuf +/// The main entry point for the NimbleNet iOS SDK. +/// +/// `NimbleNetApi` provides a high-level interface for integrating machine learning capabilities +/// and event tracking into your iOS applications. This class manages the SDK's lifecycle, +/// including initialization, session management, running inference on machine learning models, +/// and recording user events. +/// +/// Developers use `NimbleNetApi` to: +/// - **Initialize the SDK**: Configure the SDK with necessary credentials and settings. +/// - **Manage Sessions**: Control the active session for event tracking and model interactions. +/// - **Run Machine Learning Models**: Execute pre-trained models with custom inputs to get predictions or insights. +/// - **Add Events**: Track user interactions and other relevant data for analytics or model improvement. +/// - **Check Readiness**: Determine if the SDK and its underlying models are ready for operations. +/// +/// This class abstracts away the complexities of model loading, data handling, and native +/// interoperability, providing a clean and consistent API for mobile developers. public class NimbleNetApi{ private static let nimbleNetController: NimbleNetController = NimbleNetController(); + /// Restarts the current session. public static func restartSession(){ nimbleNetController.restartSession() } + + /// Restarts the session with a specific session identifier. + /// - Parameter sessionId: The ID for the new session. public static func restartSessionWithId(sessionId: String){ nimbleNetController.restartSession(withId: sessionId) } + + /// Initializes the NimbleNet SDK with the provided configuration. + /// - Parameters: + /// - config: The configuration object. + /// - assetsJson: Optional JSON array for asset configuration. + /// - Returns: A `NimbleNetResult` indicating success or failure. public static func initialize(config:NimbleNetConfig, assetsJson: [[String: Any]]? = nil)->NimbleNetResult{ var config = config @@ -64,6 +90,11 @@ public class NimbleNetApi{ } + /// Initializes the NimbleNet SDK with a JSON string configuration. + /// - Parameters: + /// - config: The configuration as a JSON string. + /// - assetsJson: Optional JSON array for asset configuration. + /// - Returns: A `NimbleNetResult` indicating success or failure. public static func initialize(config:String, assetsJson: [[String: Any]]?) -> NimbleNetResult{ if let jsonData = config.data(using: .utf8) { @@ -83,6 +114,11 @@ public class NimbleNetApi{ } } + /// Adds an event with dictionary-based data. + /// - Parameters: + /// - events: A dictionary containing event data. + /// - eventType: The type of event. + /// - Returns: A `NimbleNetResult` with the result of adding the event. public static func addEvent(events: [String: Any], eventType: String) -> NimbleNetResult { do { @@ -100,12 +136,19 @@ public class NimbleNetApi{ } } + /// Adds an event with a JSON string payload. + /// - Parameters: + /// - eventString: The event data as a JSON string. + /// - eventType: The type of event. + /// - Returns: A `NimbleNetResult` with the result of adding the event. public static func addEvent(eventString: String, eventType: String) -> NimbleNetResult { let res = nimbleNetController.add_event_controller(eventString, eventType:eventType)! return NimbleNetResult(data: NSDictionary(dictionary:res)) } - + + /// Checks if the NimbleNet SDK is ready. + /// - Returns: A `NimbleNetResult` indicating the readiness status. public static func isReady() -> NimbleNetResult { do{ @@ -118,6 +161,11 @@ public class NimbleNetApi{ } } + /// Runs a specified method with provided inputs. + /// - Parameters: + /// - methodName: The name of the method to run. + /// - inputs: A dictionary of input tensors. + /// - Returns: A `NimbleNetResult` containing the method's output. public static func runMethod(methodName: String, inputs: [String: NimbleNetTensor]) -> NimbleNetResult { do { @@ -180,7 +228,7 @@ public class NimbleNetApi{ func convertToDictionary(_ input: NimbleNetTensor) -> [String: Any] { if(input.datatype.rawValue == DataType.FE_OBJ.rawValue){ var message = input.data as! (Message & _ProtoNameProviding) - var wrapper = ProtoObjectWrapper(message: message) + var wrapper = ProtoObjectWrapper(message: message) return [ "data": wrapper, "type": input.datatype.value, @@ -197,6 +245,8 @@ public class NimbleNetApi{ } //utils + /// Creates the NimbleNet SDK directory. + /// - Returns: The path to the created directory. private static func createNimbleNetDirectory() -> String { guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { fatalError("Failed to get documents directory.") @@ -215,6 +265,9 @@ public class NimbleNetApi{ return folderURL.path } + /// Converts a value to an `UnsafeMutableRawPointer`. + /// - Parameter value: The value to convert. + /// - Returns: An `UnsafeMutableRawPointer` to the value. private static func convertToVoidPointer(_ value: T) -> UnsafeMutableRawPointer { let pointer = UnsafeMutablePointer.allocate(capacity: 1) pointer.initialize(to: value) @@ -222,6 +275,11 @@ public class NimbleNetApi{ } + /// Populates a `NimbleNetResult` with error information. + /// - Parameters: + /// - errorCode: The error code. + /// - errorMessage: The error message. + /// - Returns: A `NimbleNetResult` with error details. private static func populateNimbleNetResultWithError(errorCode:Int,errorMessage:String) -> NimbleNetResult{ let dict: NSDictionary = [ "status": false, @@ -236,7 +294,9 @@ public class NimbleNetApi{ } - +/// Verifies the types and shapes of user-provided inputs for model execution. +/// - Parameter inputs: A dictionary of input tensors to verify. +/// - Throws: `DataTypeMismatchError` if any input data type or shape is invalid. func verifyUserInputs(inputs: [String: NimbleNetTensor]) throws { for (_, modelInput) in inputs { let data = modelInput.data diff --git a/sdks/ios/deliteAI/Classes/sources/dataModel/NimbleNetConfig.swift b/sdks/ios/deliteAI/Classes/sources/dataModel/NimbleNetConfig.swift index 1d6f02ae..dacb573e 100644 --- a/sdks/ios/deliteAI/Classes/sources/dataModel/NimbleNetConfig.swift +++ b/sdks/ios/deliteAI/Classes/sources/dataModel/NimbleNetConfig.swift @@ -4,18 +4,75 @@ * SPDX-License-Identifier: Apache-2.0 */ +import Foundation +import SwiftProtobuf + +/// Configuration class for initializing the NimbleNet SDK. +/// +/// This class contains all the necessary parameters and settings required to initialize and +/// configure the NimbleNet SDK. It includes authentication credentials, server endpoints, resource +/// limits, and deployment options. public struct NimbleNetConfig: Codable { + + /// Your unique client identifier from NimbleNet platform. Must be a non-empty + /// string obtained from your NimbleNet account. public let clientId: String + + /// Authentication secret key for API access. Keep this value secure and never + /// expose it in logs or client-side code. public let clientSecret: String + + /// The base URL of the NimbleNet platform API endpoint. Must be a valid HTTPS URL (e.g., + /// "https://api.nimblenet.ai"). public let host: String + + /// Unique identifier for this device or application installation. Can be a UUID, + /// device fingerprint, or custom identifier. Should remain consistent across app sessions for the + /// same device. public let deviceId: String + + /// Enable debug mode for detailed logging and diagnostics. Set to `false` in production + /// builds for optimal performance. public let debug: Bool + + /// Version identifier for API compatibility checking. Should match your + /// application version or SDK compatibility version. Used to ensure client-server API + /// compatibility. public var compatibilityTag: String + + /// Optional custom session identifier for session management. If empty, the SDK + /// will generate a default session ID. Useful for multi-user applications or session persistence. public var sessionId: String + + /// Optional maximum database size limit in kilobytes. When reached, older data + /// may be purged to stay within limits. Set based on your device storage constraints. public var maxDBSizeKBs: Float? + + /// Optional maximum event data storage limit in kilobytes. Controls how much + /// event data can be cached before upload. public var maxEventsSizeKBs: Float? + + /// Array of cohort identifiers for A/B testing and experimentation. Used to assign + /// users to specific test groups or feature variants. public var cohortIds: [String] + + /// Whether the assets will be downloaded from cloud or they are + /// already bundled with the app. public var online: Bool + + /// Initializes a `NimbleNetConfig` instance. + /// - Parameters: + /// - clientId: Your unique client identifier from NimbleNet platform. Defaults to an empty string. + /// - clientSecret: Authentication secret key for API access. Defaults to an empty string. + /// - host: The base URL of the NimbleNet platform API endpoint. Defaults to an empty string. + /// - deviceId: Unique identifier for this device or application installation. Defaults to an empty string. + /// - debug: Enable debug mode for detailed logging and diagnostics. Defaults to `false`. + /// - compatibilityTag: Version identifier for API compatibility checking. Defaults to an empty string. + /// - sessionId: Optional custom session identifier for session management. Defaults to an empty string. + /// - maxDBSizeKBs: Optional maximum database size limit in kilobytes. Defaults to `nil`. + /// - maxEventsSizeKBs: Optional maximum event data storage limit in kilobytes. Defaults to `nil`. + /// - cohortIds: Array of cohort identifiers for A/B testing and experimentation. Defaults to an empty array. + /// - online: Whether the assets will be downloaded from cloud or they are already bundled with the app. Defaults to `false`. public init(clientId: String = "", clientSecret: String = "", host: String = "", diff --git a/sdks/ios/deliteAI/Classes/sources/dataModel/NimbleNetResult.swift b/sdks/ios/deliteAI/Classes/sources/dataModel/NimbleNetResult.swift index 2cd9d61f..14a7d7d5 100644 --- a/sdks/ios/deliteAI/Classes/sources/dataModel/NimbleNetResult.swift +++ b/sdks/ios/deliteAI/Classes/sources/dataModel/NimbleNetResult.swift @@ -6,13 +6,93 @@ import Foundation +public class NimbleNetResult { + /// Indicates whether the operation succeeded (`true`) or failed (`false`). + public var status: Bool + /// The actual result data when the operation succeeds. + /// Will be `nil` for failed operations. + public var payload: T? + /// Detailed error information when the operation fails. + /// Will be `nil` for successful operations. + public var error: NimbleNetError? + + /// Initializes a `NimbleNetResult` instance from a dictionary. + /// + /// This initializer parses a dictionary, typically received from the native controller, + /// to populate the `status`, `error`, and `payload` properties. + /// + /// ## Result States + /// + /// ### Success State + /// - `status = true` + /// - `payload` contains the actual result data + /// - `error = nil` + /// + /// ### Failure State + /// - `status = false` + /// - `payload = nil` + /// - `error` contains detailed failure information + /// + /// - Parameter data: A dictionary containing the result information, including "status", + /// "data" (for payload), and "error". + public init(data: NSDictionary) { + self.status = data["status"] as! Bool + self.error = NimbleNetError(errorDict: data["error"] as? NSDictionary) + + if let dataDict = data["data"] as? NSDictionary { + self.payload = parseData(dataDict) + } else { + self.payload = nil + } + } + + /// Parses the raw data dictionary into the appropriate payload type. + /// - Parameter data: The raw data dictionary from the native controller. + /// - Returns: An optional payload of type `T` if parsing is successful, otherwise `nil`. + private func parseData(_ data: Any) -> T? { + if T.self == NimbleNetOutput.self { + return NimbleNetOutput(data: data as! NSDictionary) as? T + } else if T.self == ModelStatusData.self { + return ModelStatusData(data: data as! NSDictionary) as? T + } else if T.self == Int.self { + return data as? T + } + else if T.self == UserEventdata.self{ + let dataDict = data as? [String: Any] + let userEventdata = UserEventdata(eventDataJSONString: dataDict?["eventJsonString"] as? String, eventType: dataDict?["eventType"] as? String) + return userEventdata as? T + } + + return nil + } +} + public class TensorInternal{ + + /// The name of the tensor. This typically corresponds to the output name + /// defined in the machine learning model. public var name:String + + /// An array of integers representing the dimensions of the tensor (its shape). + /// For example, `[1, 224, 224, 3]` might represent a batch of 1 image + /// with 224x224 pixels and 3 color channels. public var shape:[Int] + + /// The data type of the elements within the tensor. public var type:DataType + + /// The actual data contained within the tensor. Its type will vary based on `self.type`. public var data:Any - init(data: NSDictionary, name:String) { + /// Initializes a `TensorInternal` instance from a dictionary and a name. + /// + /// This initializer is used to reconstruct a tensor from a dictionary + /// representation, typically received from the native controller or a serialized source. + /// + /// - Parameters: + /// - data: A dictionary containing the tensor's "data", "shape", and "type". + /// - name: The name to assign to this tensor. + public init(data: NSDictionary, name:String) { self.data = data["data"]! self.shape = data["shape"] as! [Int] self.type = DataType(value: data["type"] as! Int) @@ -21,11 +101,26 @@ public class TensorInternal{ } public class NimbleNetOutput { + + /// An array of `TensorInternal` objects representing the output tensors, + /// ordered as they were received. public var array: [TensorInternal] = [] + + /// The total number of output tensors. public var numOutputs: Int = 0 + + /// A dictionary (map) of `TensorInternal` objects, where keys are the + /// names of the output tensors and values are the `TensorInternal` instances. public var map: [String: TensorInternal] = [:] - init(data: NSDictionary) { + /// Initializes a `NimbleNetOutput` instance from a dictionary. + /// + /// This initializer parses a dictionary, typically received from the native controller, + /// to populate the `map`, `array`, and `numOutputs` properties. + /// + /// - Parameter data: A dictionary containing the output information, expected to have + /// an "outputs" dictionary and a "size" integer. + public init(data: NSDictionary) { if let outputsDict = data["outputs"] as? [String: NSDictionary] { for (key, value) in outputsDict { let singleOutputData = TensorInternal(data: value, name: key) @@ -39,72 +134,61 @@ public class NimbleNetOutput { } } + /// Provides subscript access to output tensors by their name. + /// - Parameter key: The string name of the desired output tensor. + /// - Returns: The `TensorInternal` object associated with the given key, or `nil` if not found. public subscript(key: String) -> TensorInternal? { return map[key] } } public class ModelStatusData{ + /// A boolean indicating whether the model is ready for inference (`true`) or not (`false`). public var isModelReady: Bool = false + /// The version string of the model. public var version:String = "" - init(data:NSDictionary){ + /// Initializes a `ModelStatusData` instance from a dictionary. + /// + /// This initializer parses a dictionary, typically received from the native controller, + /// to populate the `isModelReady` and `version` properties. + /// + /// - Parameter data: A dictionary containing the model status information, + /// expected to have "isModelReady" (Bool) and "version" (String) keys. + public init(data:NSDictionary){ self.isModelReady = data["isModelReady"] as! Bool self.version = data["version"] as! String } } public class NimbleNetError { + + /// Numeric error code identifying the specific type of error. public var code: Int = 0 + + /// Human-readable description of the error. + /// May be empty if not specified. public var message: String = "" - init?(errorDict: NSDictionary?) { + /// Initializes a `NimbleNetError` instance from an optional dictionary. + /// + /// This failable initializer attempts to create an error object from a dictionary, + /// typically received from the native controller. If the `errorDict` is `nil`, + /// the initialization fails, returning `nil`. + /// + /// - Parameter errorDict: An optional dictionary containing error information, + /// expected to have "code" (Int) and "message" (String) keys. + public init?(errorDict: NSDictionary?) { guard let errorDict = errorDict else { return nil } self.code = errorDict["code"] as! Int self.message = errorDict["message"] as! String - - } -} - -public class NimbleNetResult { - public var status: Bool - public var payload: T? - public var error: NimbleNetError? - - init(data: NSDictionary) { - self.status = data["status"] as! Bool - self.error = NimbleNetError(errorDict: data["error"] as? NSDictionary) - - if let dataDict = data["data"] as? NSDictionary { - self.payload = parseData(dataDict) - } else { - self.payload = nil - } - } - - private func parseData(_ data: Any) -> T? { - if T.self == NimbleNetOutput.self { - return NimbleNetOutput(data: data as! NSDictionary) as? T - } else if T.self == ModelStatusData.self { - return ModelStatusData(data: data as! NSDictionary) as? T - } else if T.self == Int.self { - return data as? T - } - else if T.self == UserEventdata.self{ - let dataDict = data as? [String: Any] - let userEventdata = UserEventdata(eventDataJSONString: dataDict?["eventJsonString"] as? String, eventType: dataDict?["eventType"] as? String) - return userEventdata as? T - } - - return nil } } -//extensions to stringify - +//MARK: extensions to stringify extension NimbleNetResult: CustomStringConvertible { public var description: String { var description = "NimbleNetResult - Status: \(status)" diff --git a/sdks/ios/deliteAI/Classes/sources/dataModel/UserEventData.swift b/sdks/ios/deliteAI/Classes/sources/dataModel/UserEventData.swift index 374ff93a..3c35bc43 100644 --- a/sdks/ios/deliteAI/Classes/sources/dataModel/UserEventData.swift +++ b/sdks/ios/deliteAI/Classes/sources/dataModel/UserEventData.swift @@ -7,10 +7,18 @@ import Foundation public class UserEventdata{ - init(eventDataJSONString: String? = nil, eventType: String? = nil) { + + /// The serialized JSON representation of the event data. + public var eventDataJSONString: String? + + /// The classification or category of the recorded event. + public var eventType:String? + + /// - Parameters: + /// - eventDataJSONString: The serialized JSON string of the event data. Defaults to `nil`. + /// - eventType: The classification or category of the recorded event. Defaults to `nil`. + public init(eventDataJSONString: String? = nil, eventType: String? = nil) { self.eventDataJSONString = eventDataJSONString self.eventType = eventType } - public var eventDataJSONString: String? - public var eventType:String? } From 678c0b4120a2e75f7bad5f8dd24c25905d3858c9 Mon Sep 17 00:00:00 2001 From: Suryansh Bisen Date: Tue, 22 Jul 2025 12:06:37 +0530 Subject: [PATCH 2/2] updated function docs Signed-off-by: Suryansh Bisen --- .../Classes/sources/NimbleNetApi.swift | 29 +++++++------------ .../sources/dataModel/NimbleNetConfig.swift | 2 +- 2 files changed, 11 insertions(+), 20 deletions(-) diff --git a/sdks/ios/deliteAI/Classes/sources/NimbleNetApi.swift b/sdks/ios/deliteAI/Classes/sources/NimbleNetApi.swift index 7504996d..3df7ca08 100644 --- a/sdks/ios/deliteAI/Classes/sources/NimbleNetApi.swift +++ b/sdks/ios/deliteAI/Classes/sources/NimbleNetApi.swift @@ -9,16 +9,16 @@ import SwiftProtobuf /// The main entry point for the NimbleNet iOS SDK. /// -/// `NimbleNetApi` provides a high-level interface for integrating machine learning capabilities -/// and event tracking into your iOS applications. This class manages the SDK's lifecycle, -/// including initialization, session management, running inference on machine learning models, -/// and recording user events. +/// `NimbleNetApi` provides a high-level interface for integrating AI/ML capabilities +/// and event processing into your iOS applications. This class manages the SDK's lifecycle, +/// including initialization, session management, running local inference for AI/ML models, +/// and processing user events. /// -/// Developers use `NimbleNetApi` to: +/// Developers can use `NimbleNetApi` to: /// - **Initialize the SDK**: Configure the SDK with necessary credentials and settings. -/// - **Manage Sessions**: Control the active session for event tracking and model interactions. -/// - **Run Machine Learning Models**: Execute pre-trained models with custom inputs to get predictions or insights. -/// - **Add Events**: Track user interactions and other relevant data for analytics or model improvement. +/// - **Manage Sessions**: Control the active session for event processing and model interactions. +/// - **Run AI/ML Models**: Execute AI/ML models with custom inputs to get predictions or insights. +/// - **Add Events**: Process user interactions and other relevant data for analytics or model improvement. /// - **Check Readiness**: Determine if the SDK and its underlying models are ready for operations. /// /// This class abstracts away the complexities of model loading, data handling, and native @@ -41,7 +41,7 @@ public class NimbleNetApi{ /// Initializes the NimbleNet SDK with the provided configuration. /// - Parameters: /// - config: The configuration object. - /// - assetsJson: Optional JSON array for asset configuration. + /// - assetsJson: Optional JSON array for asset configuration. This is mandatory for offline initialization. /// - Returns: A `NimbleNetResult` indicating success or failure. public static func initialize(config:NimbleNetConfig, assetsJson: [[String: Any]]? = nil)->NimbleNetResult{ @@ -93,7 +93,7 @@ public class NimbleNetApi{ /// Initializes the NimbleNet SDK with a JSON string configuration. /// - Parameters: /// - config: The configuration as a JSON string. - /// - assetsJson: Optional JSON array for asset configuration. + /// - assetsJson: Optional JSON array for asset configuration. This is mandatory for offline initialization. /// - Returns: A `NimbleNetResult` indicating success or failure. public static func initialize(config:String, assetsJson: [[String: Any]]?) -> NimbleNetResult{ @@ -265,15 +265,6 @@ public class NimbleNetApi{ return folderURL.path } - /// Converts a value to an `UnsafeMutableRawPointer`. - /// - Parameter value: The value to convert. - /// - Returns: An `UnsafeMutableRawPointer` to the value. - private static func convertToVoidPointer(_ value: T) -> UnsafeMutableRawPointer { - let pointer = UnsafeMutablePointer.allocate(capacity: 1) - pointer.initialize(to: value) - return UnsafeMutableRawPointer(pointer) - } - /// Populates a `NimbleNetResult` with error information. /// - Parameters: diff --git a/sdks/ios/deliteAI/Classes/sources/dataModel/NimbleNetConfig.swift b/sdks/ios/deliteAI/Classes/sources/dataModel/NimbleNetConfig.swift index dacb573e..9e56f5d4 100644 --- a/sdks/ios/deliteAI/Classes/sources/dataModel/NimbleNetConfig.swift +++ b/sdks/ios/deliteAI/Classes/sources/dataModel/NimbleNetConfig.swift @@ -64,7 +64,7 @@ public struct NimbleNetConfig: Codable { /// - Parameters: /// - clientId: Your unique client identifier from NimbleNet platform. Defaults to an empty string. /// - clientSecret: Authentication secret key for API access. Defaults to an empty string. - /// - host: The base URL of the NimbleNet platform API endpoint. Defaults to an empty string. + /// - host: The base URL of the SaaS Configuration platform API endpoint. Defaults to an empty string. /// - deviceId: Unique identifier for this device or application installation. Defaults to an empty string. /// - debug: Enable debug mode for detailed logging and diagnostics. Defaults to `false`. /// - compatibilityTag: Version identifier for API compatibility checking. Defaults to an empty string.