AidGen Android SDK API Reference
This page combines the Android APIs for AidLLM, AidVLM, and AidT2E. For setup and authorization, see the Android integration guide. For the underlying API, see the C++ API reference. Authorize through the shared Aidlite API before initializing an engine.
AidLLM: Text Generation
AidLLM wraps the aidgen Context and Generator for text generation. Its error codes, generation states, and profile data correspond to the native aidgen API.
Initialization
Create an AidLLM(application: Application) after Aidlite.initialize(application, businessCode, licensePath) succeeds.
val llm = AidLLM(application)
val code = llm.init(
AidLMInitParam(
configPath = configPath,
contextProperties = AidGenContextProperties(enableProfiler = true),
backendType = AidGenBackendType.QNN248,
contextConfig = mapOf("generator_n-threads" to "4")
),
callback
)
if (code != AidGenCode.SUCCESS) {
Log.e("AidLLM", "init failed: $code (${code.code})")
}fun init(aidLMInitParam: AidLMInitParam, replyCallback: AidLLM.ReplyCallback): AidGenCode
fun getLastErrorCode(): AidGenCodeconfigPath accepts a model configuration file path or inline JSON. A blank value returns INVALID_PARAM. Calling init() without Aidlite authorization returns NOT_INITIALIZED; calling it again on an initialized instance returns ALREADY_INITIALIZED. contextConfig is applied after Context.initialize() and before Generator creation.
AidLMInitParam defaults to backendType=QNN248, contextProperties=AidGenContextProperties(stream=true, enableProfiler=false, enablePromptCache=true), and an empty contextConfig. The old three Boolean argument init() overload and initResult() have been removed.
Result and error types
Compare an AidGenCode with AidGenCode.SUCCESS; use .code for its native integer value. AidGenResult<T> has code, nullable value, and isSuccess. Check the code before reading the value.
AidGenCode | Value | Meaning |
|---|---|---|
SUCCESS | 0 | Success |
INVALID_PARAM | -1 | Invalid parameter |
NOT_INITIALIZED | -2 | Engine not initialized |
ALREADY_INITIALIZED | -3 | Already initialized or running |
OUT_OF_MEMORY | -4 | Insufficient memory |
UNSUPPORTED | -5 | Unsupported operation, including reset or release during generation |
ABORTED | -6 | Operation aborted |
FILE_NOT_FOUND | -10 | File not found |
FILE_OPEN_FAILED | -11 | Could not open file |
FILE_EMPTY | -12 | Empty file |
FILE_READ_ERROR | -13 | File read failed |
FILE_PARSE_ERROR | -14 | JSON parse failed |
BACKEND_ERROR | -20 | Backend error |
BACKEND_NOT_FOUND | -21 | Backend library not found |
INTERNAL_ERROR | -99 | SDK internal error |
The former AidGenErrorCode name has been replaced by AidGenCode.
Generation and conversation history
fun run(prompt: String, userData: Int, isNewConversation: Boolean,
modelCategory: AidLLM.ModelCategory): AidGenCode
fun setSystemPrompt(systemPrompt: String)
fun registerReplyCallback(replyCallback: AidLLM.ReplyCallback)
fun isChatAble(): Booleanrun() is synchronous and blocks until generation finishes. Call it on a worker thread, such as Dispatchers.IO. Serialize initialization, generation, history reset, property changes, and release on the same instance. Move UI updates from callbacks to the main thread.
promptis the current user's text. The SDK adds the model template; do not prepend ChatML or another template yourself.userDatais passed unchanged to event and completion callbacks.isNewConversation=trueclears managed history and resets the native KV cache before this turn. Usefalseto continue a conversation.modelCategoryselects a prompt template and must match the loaded model. It does not switch the model or backend.
| Category | Prompt behavior |
|---|---|
QWEN | ChatML with system prompt and conversation history |
TIMEKETTLE | ChatML with an empty system message and history; put translation instructions in prompt |
DEEPSEEK | DeepSeek user/assistant template with history |
MINICPM | MiniCPM user/assistant template with history |
MINICPM5 | MiniCPM5: <s> + ChatML with history and an empty prefilled thinking section |
HY_MT_CN, HY_MT_EN | Single turn translation to Chinese or English |
AIDLLM_CN2EN, AIDLLM_EN2CN | Single turn Chinese to English or English to Chinese translation |
setSystemPrompt() affects QWEN only. Its default is You are a helpful assistant.; blank values are ignored. A completed turn is saved to managed history. Aborted or erroneous turns are discarded. Start a new conversation when switching templates. The two and three argument run() overloads and runResult() have been removed.
Callbacks
interface AidLLM.ReplyCallback {
fun onEvent(event: AidGenEvent, userData: Int)
fun onComplete(profile: GeneratorProfile?, userData: Int)
fun errorReply(error: String, userData: Int)
fun onReply(reply: String, userData: Int)
fun endReply(end: String, userData: Int)
fun completeReply(complete: String, userData: Int)
fun abortReply(complete: String, userData: Int)
}AidGenEvent.state is IDLE, BEGIN, CONTINUE, END, ABORT, or ERROR; text contains that event's fragment. The default onEvent() forwards BEGIN and CONTINUE to onReply(), END to endReply(), ABORT to abortReply(), and ERROR to errorReply(). The default errorReply() forwards to abortReply() for compatibility. Override it or onEvent() to distinguish errors from user aborts.
The default onComplete() converts profile data to legacy text and calls completeReply(). Overriding onComplete() does not also call that legacy method. The four legacy callback methods remain abstract and must be implemented. profile can be null. Use the return value of the current operation to determine its result; getLastErrorCode() is not a universal substitute. Do not call abort() directly from a generation callback; call it from another thread.
Configuration, state, and profile
fun setGeneratorProperty(key: String, value: String): AidGenCode
fun setSamplerParam(samplerParams: SamplerParams): AidGenCode
fun getGeneratorProperties(): AidGenResult<String>
fun getContextConfig(): AidGenResult<String>
fun getState(): AidGenResult<AidGenState>
fun getProfiler(): AidGenResult<GeneratorProfile>Generator properties include stream, temp, top-k, top-p, penalize-last-n, frequency-penalty, repetition-penalty, and presence-penalty. Use setGeneratorProperty() for key/value updates; setSampler() is private. setSamplerParam() supports Greedy, Top_N, and Top_P: Greedy sets top-k=1, top-p=1.0; Top_N removes a previous top-p limit; Top_P sets top-k=0 to disable a previous top-k limit. Unsupported backend settings return an error code.
Enable enableProfiler=true at initialization to collect GeneratorProfile: initTimeUs, promptTokenCount, timeToFirstTokenUs, promptProcessingTps, generatedTokenCount, generateTimeUs, and generateTps. Times are in microseconds and throughput is in tokens per second.
Reset, abort, release
fun reset(): AidGenCode
fun clearHistory(): AidGenCode
fun abort(): AidGenCode
fun release(): AidGenCodereset() clears the native KV cache first, then managed history and pending turn data on success. On failure, managed data is retained. The system prompt is retained. clearHistory() is an alias of reset().
During generation, only abort() may be called from another thread; reset, property changes, and release return UNSUPPORTED. Wait for run() to return before retrying release. A successful release clears the native handle; a second release returns NOT_INITIALIZED. An UNSUPPORTED release leaves the handle valid. The old abortResult(), resetResult(), and finalize() methods have been removed.
Version, logging, and backend
fun getLibraryVersion(): String
fun getAbiVersion(): Long
fun setLogLevel(level: AidGenLogLevel)
fun setLogFilePrefix(prefix: String): StringAidGenBackendType exposes only DEFAULT and QNN248. Both select QNN248; there is no auto detection or fallback to QNN236/QNN240. A missing QNN248 plugin returns an error. Older backend enum values have been removed; native code rejects their numeric values with UNSUPPORTED. Logging options apply globally to aidgen.
Complete Kotlin example
import android.app.Application
import android.util.Log
import com.aidlux.aidbase.Aidlite
import com.aidlux.aidgen.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
suspend fun runLlmExample(
application: Application, businessCode: String,
licensePath: String, configPath: String
) = withContext(Dispatchers.IO) {
check(Aidlite.initialize(application, businessCode, licensePath))
val llm = AidLLM(application)
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: $complete")
}
}
val code = llm.init(AidLMInitParam(configPath), callback)
if (code != AidGenCode.SUCCESS) return@withContext
try {
val first = llm.run("Hello, my name is Sam.", 1, true, AidLLM.ModelCategory.QWEN)
if (first == AidGenCode.SUCCESS) {
llm.run("What is my name?", 2, false, AidLLM.ModelCategory.QWEN)
}
} finally {
llm.release()
}
}Replace the license and model paths with your deployment values. See app/src/main/java/com/aidlux/qnngeniesample/LLMNewApiTestActivity.kt for an Activity example. Canceling a coroutine alone does not guarantee that native inference stops; call abort() from a different thread, wait for run() to return, then reset or release.
AidVLM: Image and Text Generation
AidVLM provides multimodal text and image generation. Create it with AidVLM(application: Application).
Authorization and initialization
Call Aidlite.initialize(application, businessCode, licensePath) successfully before using the engine. It returns a Boolean; licensePath defaults to /sdcard/Documents. Use actual business code, license, model configuration, and image paths for your deployment.
The shared Aidlite singleton also exposes getSN(application: Application): String? (nullable device serial number), getDeviceId(context: Context): String, getSdkVersion(): String, and getSdkBuildTime(): String.
fun init(aidVMInitParam: AidVMInitParam, replyCallback: AidVLM.ReplyCallback): AidGenCode
fun getLastErrorCode(): AidGenCodeinit() accepts a configuration file, not inline JSON. The file must exist and match modelType. Duplicate initialization returns ALREADY_INITIALIZED; missing authorization returns NOT_INITIALIZED; a missing file returns FILE_NOT_FOUND; a failed configuration check returns FILE_PARSE_ERROR. The old init(AidVMConfigParam, ReplyCallback) overload and initResult() have been removed.
AidVMInitParam field | Default | Purpose |
|---|---|---|
configPath: String | Required | Model configuration file path |
modelType: ModelType | Required | Model family and configuration variant |
enableProfiler: Boolean | true | Default profiler setting used when constructing contextProperties |
dbgOptPath: String? | null | Deprecated and ignored by native code |
backendType: AidGenBackendType | DEFAULT | Backend selection |
contextProperties: AidGenContextProperties | stream=true, enableProfiler=enableProfiler, enablePromptCache=true | Context behavior |
contextConfig: Map<String, String> | Empty | Context configuration overrides |
contextProperties is passed to native initialization. If you supply it explicitly, its enableProfiler value is used rather than the standalone enableProfiler field. Context configuration overrides are applied after Context.initialize() and before Generator creation. AidGenBackendType.DEFAULT and QNN248 both select the validated QNN248 backend. There is no older backend fallback; missing QNN248 plugins return an error.
Inference
@JvmOverloads
fun run(
systemPrompt: String = "You are a helpful assistant.",
prompt: String,
imagePath: String?,
isNewConversation: Boolean = true,
userData: Int = 0
): AidGenCoderun() is a synchronous call: it invokes native generation and returns when that generation call finishes. Run it on a worker thread. SUCCESS means inference finished successfully, not merely that a job was submitted. The callback receives output while run() is executing. Wait for run() to return before calling release() on the same instance.
prompt is required and cannot be empty. imagePath=null selects text only input; a real image path selects image input. An empty native system prompt is replaced with the default. isNewConversation=true starts a new conversation; userData is passed to event and completion callbacks. Kotlin callers can use named arguments. The old runResult() has been removed.
Serialize initialization, inference, property updates, reset, and release on one instance. Do not update Android UI directly from inference callbacks. To interrupt generation, call abort() from another thread, never directly from a generation callback.
Callbacks and state
interface AidVLM.ReplyCallback {
fun onEvent(event: AidGenEvent, userData: Int)
fun onComplete(profile: GeneratorProfile?, userData: Int)
fun errorReply(error: String, userData: Int)
fun onReply(reply: String)
fun endReply(profil: String)
fun abortReply()
}
fun registerReplyCallback(replyCallback: AidVLM.ReplyCallback)
fun isChatAble(): Boolean
fun getState(): AidGenResult<AidGenState>AidGenEvent contains a state (IDLE, BEGIN, CONTINUE, END, ABORT, or ERROR) and the current text fragment. The default onEvent() forwards BEGIN, CONTINUE, and END fragments to onReply(), ABORT to abortReply(), and ERROR to errorReply(). The default errorReply() calls abortReply() for legacy compatibility. Override it to distinguish errors from aborts.
onComplete() receives a nullable structured GeneratorProfile. Its default implementation converts the profile to legacy text and calls endReply(). If you override it, call endReply() yourself if you still need that callback. The three legacy methods remain abstract. isChatAble() is false while generation is active or before initialization; use run()'s return code for the operation outcome.
Properties and performance
fun setGeneratorProperty(key: String, value: String): AidGenCode
fun getGeneratorProperties(): AidGenResult<String>
fun getContextConfig(): AidGenResult<String>
fun getProfiler(): AidGenResult<GeneratorProfile>
fun getProfileData(): StringSet properties only while generation is idle; during inference this operation returns UNSUPPORTED. Typical keys include temp, top-k, and top-p. The getter methods return an AidGenResult<T>: check isSuccess or code before using nullable value. getProfileData() is the legacy JSON string form and returns {"errorCode":-2} before initialization. Enable profiling at initialization to collect meaningful data.
GeneratorProfile contains initTimeUs, promptTokenCount, timeToFirstTokenUs, promptProcessingTps, generatedTokenCount, generateTimeUs, and generateTps. Time fields are microseconds; throughput fields are tokens per second.
Abort, reset, release, and utilities
fun abort(): AidGenCode
fun reset(): AidGenCode
fun release(): AidGenCode
fun getLibraryVersion(): String
fun getAbiVersion(): Long
fun setLogLevel(level: AidGenLogLevel)
fun setLogFilePrefix(prefix: String): Stringabort() requests interruption of active inference from another thread. reset() clears conversation context and history; call it after inference returns. release() frees the engine. During inference, release returns UNSUPPORTED and keeps the handle valid; abort, wait for run() to finish, then retry. A second release returns NOT_INITIALIZED. The old free() method has been removed. Log settings affect aidgen globally.
Compare operation results with AidGenCode.SUCCESS; .code gives the native integer. Shared error values are documented in the shared error table.
Model types and JSON resources
ModelType | typeName |
|---|---|
QWEN25VL3B392 | qwen25vl3b392 |
QWEN25VL3B672 | qwen25vl3b672 |
QWEN25VL3B644 | qwen25vl3b644 |
QWEN25VL7B392 | qwen25vl7b392 |
QWEN25VL7B672 | qwen25vl7b672 |
QWEN25VL7B644 | qwen25vl7b644 |
QWEN3VL4B448 | qwen3vl4b448 |
LOCATE_ANYTHING | locateanything |
INTERNVL3 | internvl3 |
MAGEVL | magevl |
ModelType.family exposes the stable VlmModelFamily. Keep image dimensions, patch settings, and model file paths in JSON rather than encoding them in new enum names.
vlm_model.type | Default image size | Required vision resources |
|---|---|---|
qwen2.5 | From configuration | model, cos, sin, window mask, full mask |
qwen3 | 448 × 448 | model, cos, sin |
locateanything | 672 × 392 | model, cos, sin |
internvl3 | 448 × 448 | model |
magevl | 512 × 288 | model, cos, sin; mask if exposed by the model |
Kotlin example
import android.app.Application
import android.util.Log
import com.aidlux.aidbase.Aidlite
import com.aidlux.aidgen.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
suspend fun runVlmExample(
application: Application, businessCode: String, licensePath: String,
configPath: String, imagePath: String
) = withContext(Dispatchers.IO) {
check(Aidlite.initialize(application, businessCode, licensePath))
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")
}
}
val initCode = vlm.init(AidVMInitParam(configPath = configPath,
modelType = ModelType.QWEN25VL3B392), callback)
if (initCode != AidGenCode.SUCCESS) return@withContext
try {
val runCode = vlm.run(prompt = "Describe this image.",
imagePath = imagePath, isNewConversation = true, userData = 1)
Log.i("AidVLM", "run: $runCode (${runCode.code})")
} finally {
vlm.release()
}
}See app/src/main/java/com/aidlux/qnngeniesample/VLMNewApiTestActivity.kt for a runnable Activity example.
AidT2E: Text Embeddings
AidT2E is the synchronous text embedding engine. It wraps aidgen Context, Tokenizer, and EmbeddingExtractor. Construct it with AidT2E(application: Application).
API conventions
- Status only methods return
AidGenCode. Compare withAidGenCode.SUCCESS; use.codefor the native integer value. - Data methods return
AidGenResult<T>withcode, nullablevalue, andisSuccess. Check success before readingvalue; failures have a null value. getLastErrorCode()reports the latest engine operation. Prefer the current method's return value. Version, log, andisInitialized()queries do not update it.- All model operations are synchronous and have no generation callback. Call them on a worker thread, such as
Dispatchers.IO. - Calls on the same instance are serialized.
release()waits for an active synchronous call and does not abort it. Canceling a coroutine does not guarantee cancellation of native inference. - Before initialization,
Aidlite.initialize(application, businessCode, licensePath)must succeed. That authorization method returns a Boolean.
Shared AidGenCode values are listed in the shared error table.
Initialization
data class AidT2EInitParam(
val configPath: String,
val enableProfiler: Boolean = true,
val backendType: AidGenBackendType = AidGenBackendType.DEFAULT,
val contextConfig: Map<String, String> = emptyMap()
)
fun init(initParam: AidT2EInitParam): AidGenCode
fun isInitialized(): Boolean
fun getLastErrorCode(): AidGenCodeconfigPath must point to an existing file; inline JSON is not accepted. A blank path returns INVALID_PARAM; a missing path or a nonfile path returns FILE_NOT_FOUND. Reinitializing an active instance returns ALREADY_INITIALIZED and leaves its handle intact.
Only DEFAULT and QNN248 are public backend selections. Both select QNN248, with no automatic detection or fallback to QNN236/QNN240. A missing QNN248 plugin returns an error. The backendType argument controls this choice; the old backend_type configuration field is ignored. Native code rejects older backend selector values with UNSUPPORTED.
After Context.initialize() succeeds and before creating the Tokenizer and EmbeddingExtractor, each contextConfig entry is passed to Context.set_config(). Keys and values are strings; unsupported settings return the underlying error. T2E fixes stream=false and enable_prompt_cache=false internally; enableProfiler controls performance collection.
Embedding and tokenization
fun run(text: String): AidGenResult<FloatArray>
fun runBatch(texts: List<String>): AidGenResult<List<FloatArray>>
fun tokenize(text: String): AidGenResult<IntArray>
fun decode(tokens: IntArray): AidGenResult<String>| Method | Input and output |
|---|---|
run | One nonblank text; returns its embedding vector |
runBatch | A nonempty list of nonblank texts; returns embeddings in input order |
tokenize | Nonblank text; returns token IDs |
decode | Nonempty token IDs; returns decoded text, which may validly be an empty string |
Before initialization these methods return NOT_INITIALIZED; invalid input returns INVALID_PARAM. If one item in a batch fails, the entire call returns its error without partial vectors. runBatch() encodes items sequentially; it does not promise parallel processing or hardware batch acceleration. The profile after a batch describes the last actual encoding.
Native aidgen errors are passed through C++ and JNI rather than collapsed into -1 or null. Failures without a more specific native code, such as invalid output tensors or failed object creation, return INTERNAL_ERROR. An authorization failure currently also maps to INTERNAL_ERROR; check logs for detail.
Profile, configuration, and properties
fun getProfiler(): AidGenResult<EmbeddingProfile>
fun getContextConfig(): AidGenResult<String>
fun getExtractorProperties(): AidGenResult<String>
fun setExtractorProperty(key: String, value: String): AidGenCode
data class EmbeddingProfile(
val initTimeUs: Long,
val promptTokenCount: Long,
val executeTimeUs: Long,
val promptProcessingTps: Float
)Times are microseconds and throughput is tokens per second. EmbeddingProfile comes from ProfileData.extractor, rather than the generator's GeneratorProfile. Enable enableProfiler=true during initialization. If profile data is unavailable, the API returns an error code rather than a fabricated zero profile.
getContextConfig() and getExtractorProperties() return native JSON strings. Valid extractor property names and values depend on the EmbeddingExtractor backend; Generator sampling keys are not automatically applicable. A blank key passed to setExtractorProperty() returns INVALID_PARAM; unsupported properties return the underlying error.
Version, logging, and release
fun getLibraryVersion(): String
fun getAbiVersion(): Long
fun setLogLevel(level: AidGenLogLevel)
fun setLogFilePrefix(prefix: String): String
fun release(): AidGenCodeVersion and log methods follow the LLM/VLM APIs. Logging settings affect aidgen globally. release() frees the Extractor, Tokenizer, and Context, and clears the native handle. Repeated release returns NOT_INITIALIZED; the instance can be initialized again. If a native finalizer reports an error, that error is returned, but the handle has still been destroyed and must not be reused.
Kotlin example
import android.app.Application
import android.util.Log
import com.aidlux.aidbase.Aidlite
import com.aidlux.aidgen.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
suspend fun embeddingExample(
application: Application, businessCode: String,
licensePath: String, configPath: String
) = withContext(Dispatchers.IO) {
check(Aidlite.initialize(application, businessCode, licensePath))
val engine = AidT2E(application)
val initCode = engine.init(AidT2EInitParam(configPath = configPath))
if (initCode != AidGenCode.SUCCESS) {
Log.e("T2E", "init failed: $initCode (${initCode.code})")
return@withContext
}
try {
val result = engine.run("What is artificial intelligence?")
if (result.isSuccess) {
val embedding = requireNotNull(result.value)
Log.i("T2E", "dimension=${embedding.size}")
} else {
Log.e("T2E", "encode failed: ${result.code}")
}
val batch = engine.runBatch(listOf("Hello", "Good morning"))
Log.i("T2E", "batch status=${batch.code}, count=${batch.value?.size}")
val tokens = engine.tokenize("Hello")
if (tokens.isSuccess) {
val decoded = engine.decode(requireNotNull(tokens.value))
Log.i("T2E", "decoded: ${decoded.value}, status=${decoded.code}")
}
val profile = engine.getProfiler()
Log.i("T2E", "profile: ${profile.code}, ${profile.value}")
} finally {
engine.release()
}
}Replace the authorization and model paths with real values. app/src/main/java/com/aidlux/qnngeniesample/T2ETestActivity.kt demonstrates single and batch encoding, tokenization, decoding, profiling, and property queries.
Migration from the former API
This source API change requires recompiling callers against the new AAR and updating the JNI library with it.
| Former API | Current API |
|---|---|
init(...): Boolean | init(...): AidGenCode |
run(text): FloatArray? / encodeText(text) | run(text): AidGenResult<FloatArray> |
encodeTexts(texts) | runBatch(texts): AidGenResult<List<FloatArray>> |
tokenize(text): IntArray? | tokenize(text): AidGenResult<IntArray> |
decode(tokens): String? | decode(tokens): AidGenResult<String> |
getProfileData(): String | getProfiler(): AidGenResult<EmbeddingProfile> |
getProperty(): String | getExtractorProperties(): AidGenResult<String> |
setProperty(...): Int | setExtractorProperty(...): AidGenCode |
finalize(): Int | release(): AidGenCode |
T2E shares AidGenCode and AidGenResult<T> with the LLM and VLM APIs. Removed result suffix methods and legacy overloads are not retained.