AidGen Android SDK Integration Guide
This guide is for Android developers using AidLLM for text generation, AidVLM for image and text generation, and AidT2E for text embeddings. All three engines share the Aidlite authorization API in aidbase. The typical workflow is: obtain a Business Code and model files → integrate the SDK → authorize with Aidlite.initialize() → initialize the engine → run inference → abort if needed → wait for inference to finish → release the engine.
For detailed parameters and return values, see the AidLite Android API and AidGen Android API reference, which covers LLM, VLM, and T2E.
1. Integrate the SDK
Configure repositories in your project's settings.gradle. If dependencyResolutionManagement already exists, merge the repositories into that configuration:
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
}
}If your project still manages dependency repositories in the root build.gradle, use this configuration instead:
allprojects {
repositories {
google()
mavenCentral()
}
}The dependencyResolutionManagement block belongs in settings.gradle. Projects that manage repositories centrally in settings only need the first approach.
Then add one SDK dependency to your app module's build.gradle, according to the target device.
Standard Android phones:
dependencies {
implementation 'com.aidlux:aidgen-phone:2.5.1'
}Devices running a custom ROM:
dependencies {
implementation 'com.aidlux:aidgen-customrom:2.5.1'
}Both variants provide the same LLM, VLM, and T2E APIs. They differ in how the device authorization identifier is obtained. After adding the dependency and syncing Gradle, follow the next section to authorize the SDK with Aidlite.initialize().
2. Obtain a Business Code and Authorize the SDK
- Open the AidLux registration page and register using your mobile phone number.
- Open the license management portal and sign in.
- On the Authorization Information page (授权信息), find the
Aidlux统一授权--000001card. Eligible users receive an initial authorization quota of 1 by default. - Find Business Code (企业码) on the card and click the adjacent copy icon to copy it.
- Call
Aidlite.initialize(application, businessCode, licensePath)in your app. Initialize an LLM, VLM, or T2E engine only after this call returnstrue.
import android.app.Application
import com.aidlux.aidbase.Aidlite
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
suspend fun authorizeSdk(
application: Application,
businessCode: String,
licensePath: String
): Boolean = withContext(Dispatchers.IO) {
Aidlite.initialize(application, businessCode, licensePath)
}Check the return value. If authorization fails, show an appropriate message and inspect the AIDLOG / XLog output.
Use the Business Code copied in the previous step as businessCode. Set licensePath to the actual license file directory used by your app; it defaults to /sdcard/Documents when omitted. Aidlite.initialize() returns a Boolean, unlike the engines' AidGenCode return values. Use Aidlite.getAuthorizationDeviceId(application) to query the unique device authorization identifier: the phone variant uses Android ID, while customRom reads /sys/devices/soc0/serial_number. The method returns null if the identifier cannot be read. Querying the identifier does not authorize the SDK.
3. Obtain Models
Online Downloads
AidSe uses Retrofit/OkHttp to query the Android model catalog and stream files from the returned download_url values to local storage. The SDK exposes only 2=LLM and 3=VLM. Embedding models are categorized as LLM by the service, so use category 2 to query them. Omitting categories or passing an empty list requests both LLM and VLM models. Other values, including 0, 1, 4, and 5, cause an IllegalArgumentException. Multiple categories are sent as repeated model_category query parameters, and the service matches any of them. The SDK detects the current device's SoC automatically; callers do not supply socType. Read the aidSe.socType property to inspect the detected value. Pagination is optional; omitting limit requests all matching models for the current device. Download and installation methods also accept only models in category 2 or 3.
On Android 12 and later, detection first uses Build.SOC_MODEL. If unavailable, the SDK tries system SoC properties, the board identifier, and the hardware identifier in that order. No additional permissions are required. If every identifier is empty or unknown, the query throws an IOException without sending a request that omits the SoC filter. Call AidSe methods and read socType for the first time on a worker thread.
import com.aidlux.aidgen.AidSe
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
val aidSe = AidSe() // Uses https://aiot.aidlux.com/api/v1/ by default.
val page = withContext(Dispatchers.IO) {
aidSe.getModelList(modelCategories = listOf(2, 3), index = 1, limit = 20)
}
val model = page.items.firstOrNull() ?: error("No matching models")
val installed = withContext(Dispatchers.IO) {
aidSe.installModel(
model,
File(application.getExternalFilesDir(null), "models"),
onProgress = { downloadedBytes, totalBytes ->
// Progress runs on the worker thread. Switch to the main thread for UI updates.
}
)
}
val configPath = installed.configFiles.firstOrNull()?.absolutePathinstallModel() downloads the ZIP, extracts it into modelsRoot/<installation-name>, and rewrites model configuration resource paths to absolute paths in the installed directory. It returns the installation directory and the configuration files found. Calling it again replaces the existing directory after the new archive has been extracted and its configuration checked. Use downloadModel() to save only the original ZIP; the destination file must not already exist. Temporary files are cleaned up if downloading or installation fails. The SDK uses the QNN2.48 backend and supports models built with QNN2.48 and QNN2.36. Check metadata such as backendName and socName to select resources matching the current device and SDK model type. Catalog and installation methods execute synchronously and must run on a worker thread.
The default production base URL is https://aiot.aidlux.com/api/v1/. The trailing / is required by Retrofit's base URL format. Specify another service with AidSe(baseUrl = "https://your-host/api/v1/"). Accessing the default HTTPS endpoint does not require enabling cleartext traffic. Network access requires the INTERNET permission, which the aidgen AAR already declares.
Some download_url values currently returned by the production service use HTTP and respond with a 301 redirect to HTTPS. Downloading from these original URLs still requires the Android host app to allow the initial cleartext request for that domain, as the sample app does. Alternatively, change download URLs on aiot.aidlux.com to HTTPS before using them.
Offline Downloads
Visit the AidLux Model Gallery to find and manually download resources matching your device, backend, and SDK model type. Place the model configuration and its referenced resources in a location readable by the app, then pass the configuration file path to the corresponding initialization parameters. AidLLM also accepts JSON configuration content directly. AidVLM and AidT2E require an existing configuration file. For VLM, modelType must match the configuration.
Refer to the downloaded model's instructions for filenames, directory structure, and configuration contents. The SDK exposes DEFAULT and QNN248 backend options. Both use QNN2.48 and also support QNN2.36 models. Continue using DEFAULT or QNN248 when loading a QNN2.36 model; no backend option change is required.
4. General Runtime Rules
- When
init(),run(),reset(), orrelease()returns anAidGenCode, compare it withAidGenCode.SUCCESS. T2E encoding and token operations returnAidGenResult<T>; checkisSuccessbefore readingvalue. - LLM and VLM
run()calls are synchronous and blocking. T2E encoding, tokenization, and decoding are synchronous as well. Run these operations on worker threads. Switch to the main thread when a callback updates the UI. - The SDK currently does not support pausing inference and resuming it later. LLM/VLM
abort()stops the current generation. Call it from another thread and wait forrun()to return before callingreset()orrelease(). Cancelling a coroutine alone does not guarantee that native inference stops. - T2E does not provide
abort(). Itsrelease()waits for the current synchronous operation to finish and must not be used as a cancellation method. - Do not run multiple inference operations concurrently on the same engine instance. Initialize, run, reset, and release in order. Releasing an LLM/VLM engine during inference returns
UNSUPPORTED; abort and wait forrun()to finish before retrying.
5. LLM: Load, Generate, Abort, and Release
The following session class demonstrates the basic lifecycle. Supply a CoroutineScope that remains valid while work is in progress. Call and await release() before destroying that scope. Wait for load() to complete before calling generate(), and start only one generation at a time. Callbacks run on the inference thread; this example only writes logs.
import android.app.Application
import android.util.Log
import com.aidlux.aidbase.Aidlite
import com.aidlux.aidgen.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class LlmSession(
private val application: Application,
private val scope: CoroutineScope
) {
private val llm = AidLLM(application)
private var generationJob: Job? = null
private val callback = object : AidLLM.ReplyCallback {
override fun onReply(reply: String, userData: Int) {
Log.i("AidLLM", "[$userData] $reply")
}
override fun endReply(end: String, userData: Int) {
Log.i("AidLLM", "[$userData] $end")
}
override fun completeReply(complete: String, userData: Int) = Unit
override fun abortReply(complete: String, userData: Int) {
Log.i("AidLLM", "[$userData] aborted")
}
override fun errorReply(error: String, userData: Int) {
Log.e("AidLLM", "[$userData] $error")
}
}
suspend fun load(
businessCode: String,
licensePath: String,
configPath: String
): Boolean = withContext(Dispatchers.IO) {
if (!Aidlite.initialize(application, businessCode, licensePath)) {
return@withContext false
}
llm.init(AidLMInitParam(configPath = configPath), callback) == AidGenCode.SUCCESS
}
fun generate(prompt: String, newConversation: Boolean = true): Job {
check(generationJob?.isActive != true) { "Generation is already running" }
return scope.launch(Dispatchers.IO) {
val code = llm.run(prompt, 1, newConversation, AidLLM.ModelCategory.QWEN)
Log.i("AidLLM", "run: $code (${code.code})")
}.also { generationJob = it }
}
// Call from a Stop Generation button; request abort on a different thread from run().
fun stop(): Job = scope.launch(Dispatchers.IO) {
val code = llm.abort()
Log.i("AidLLM", "abort: $code")
}
// Call when leaving the screen. Wait for run() before releasing native resources.
suspend fun release(): AidGenCode = withContext(Dispatchers.IO + NonCancellable) {
val job = generationJob
if (job?.isActive == true) llm.abort()
job?.join()
llm.release()
}
}ModelCategory.QWEN selects the Qwen prompt template and must match the loaded model. Choose the corresponding category for other models. Set isNewConversation=true to start a new conversation, or false to continue the history. To clear history while keeping the model loaded, call llm.reset() after generation has finished. Dispatch callback text to the main thread for display, and do not call abort() directly from a callback.
6. VLM: Image and Text Inference
VLM follows the same order as LLM: authorize, initialize, then run inference on a worker thread. Set imagePath=null for text-only input, or supply a readable image path for image and text inference. ModelType must match the model configuration.
val vlm = AidVLM(application)
val callback = object : AidVLM.ReplyCallback {
override fun onReply(reply: String) { Log.i("AidVLM", reply) }
override fun endReply(profil: String) { Log.i("AidVLM", profil) }
override fun abortReply() { Log.i("AidVLM", "aborted") }
override fun errorReply(error: String, userData: Int) {
Log.e("AidVLM", "[$userData] $error")
}
}
// Run on a worker thread after Aidlite.initialize() has succeeded:
val initCode = vlm.init(
AidVMInitParam(configPath = configPath, modelType = ModelType.QWEN25VL3B392),
callback
)
if (initCode == AidGenCode.SUCCESS) {
try {
val runCode = vlm.run(
prompt = "Please describe this image.",
imagePath = imagePath,
isNewConversation = true,
userData = 1
)
Log.i("AidVLM", "run: $runCode")
} finally {
vlm.release() // run() has returned.
}
}To stop generation early, call vlm.abort() from another worker thread. Wait for run() to return before calling vlm.release(). Pausing and resuming is not supported. Call vlm.reset() after inference to clear conversation history.
7. T2E: Text Embeddings
T2E does not provide streaming callbacks or an abort API. Read AidGenResult.value after encoding completes, and release the engine when finished.
// Run on a worker thread after Aidlite.initialize() has succeeded:
val t2e = AidT2E(application)
val initCode = t2e.init(AidT2EInitParam(configPath = configPath))
if (initCode == AidGenCode.SUCCESS) {
try {
val result = t2e.run("What is artificial intelligence?")
if (result.isSuccess) {
val embedding = requireNotNull(result.value)
Log.i("AidT2E", "Embedding dimension: ${embedding.size}")
} else {
Log.e("AidT2E", "Inference failed: ${result.code}")
}
} finally {
t2e.release()
}
}Use runBatch(texts) for batches, tokenize(text) for tokenization, and decode(tokens) for decoding. For full parameters, error codes, and performance data, see the AidGen Android API reference.