Skip to content

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.

kotlin
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})")
}
kotlin
fun init(aidLMInitParam: AidLMInitParam, replyCallback: AidLLM.ReplyCallback): AidGenCode
fun getLastErrorCode(): AidGenCode

configPath 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.

AidGenCodeValueMeaning
SUCCESS0Success
INVALID_PARAM-1Invalid parameter
NOT_INITIALIZED-2Engine not initialized
ALREADY_INITIALIZED-3Already initialized or running
OUT_OF_MEMORY-4Insufficient memory
UNSUPPORTED-5Unsupported operation, including reset or release during generation
ABORTED-6Operation aborted
FILE_NOT_FOUND-10File not found
FILE_OPEN_FAILED-11Could not open file
FILE_EMPTY-12Empty file
FILE_READ_ERROR-13File read failed
FILE_PARSE_ERROR-14JSON parse failed
BACKEND_ERROR-20Backend error
BACKEND_NOT_FOUND-21Backend library not found
INTERNAL_ERROR-99SDK internal error

The former AidGenErrorCode name has been replaced by AidGenCode.

Generation and conversation history ​

kotlin
fun run(prompt: String, userData: Int, isNewConversation: Boolean,
        modelCategory: AidLLM.ModelCategory): AidGenCode
fun setSystemPrompt(systemPrompt: String)
fun registerReplyCallback(replyCallback: AidLLM.ReplyCallback)
fun isChatAble(): Boolean

run() 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.

  • prompt is the current user's text. The SDK adds the model template; do not prepend ChatML or another template yourself.
  • userData is passed unchanged to event and completion callbacks.
  • isNewConversation=true clears managed history and resets the native KV cache before this turn. Use false to continue a conversation.
  • modelCategory selects a prompt template and must match the loaded model. It does not switch the model or backend.
CategoryPrompt behavior
QWENChatML with system prompt and conversation history
TIMEKETTLEChatML with an empty system message and history; put translation instructions in prompt
DEEPSEEKDeepSeek user/assistant template with history
MINICPMMiniCPM user/assistant template with history
MINICPM5MiniCPM5: <s> + ChatML with history and an empty prefilled thinking section
HY_MT_CN, HY_MT_ENSingle turn translation to Chinese or English
AIDLLM_CN2EN, AIDLLM_EN2CNSingle 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 ​

kotlin
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 ​

kotlin
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 ​

kotlin
fun reset(): AidGenCode
fun clearHistory(): AidGenCode
fun abort(): AidGenCode
fun release(): AidGenCode

reset() 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 ​

kotlin
fun getLibraryVersion(): String
fun getAbiVersion(): Long
fun setLogLevel(level: AidGenLogLevel)
fun setLogFilePrefix(prefix: String): String

AidGenBackendType 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 ​

kotlin
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.

kotlin
fun init(aidVMInitParam: AidVMInitParam, replyCallback: AidVLM.ReplyCallback): AidGenCode
fun getLastErrorCode(): AidGenCode

init() 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 fieldDefaultPurpose
configPath: StringRequiredModel configuration file path
modelType: ModelTypeRequiredModel family and configuration variant
enableProfiler: BooleantrueDefault profiler setting used when constructing contextProperties
dbgOptPath: String?nullDeprecated and ignored by native code
backendType: AidGenBackendTypeDEFAULTBackend selection
contextProperties: AidGenContextPropertiesstream=true, enableProfiler=enableProfiler, enablePromptCache=trueContext behavior
contextConfig: Map<String, String>EmptyContext 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 ​

kotlin
@JvmOverloads
fun run(
    systemPrompt: String = "You are a helpful assistant.",
    prompt: String,
    imagePath: String?,
    isNewConversation: Boolean = true,
    userData: Int = 0
): AidGenCode

run() 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 ​

kotlin
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 ​

kotlin
fun setGeneratorProperty(key: String, value: String): AidGenCode
fun getGeneratorProperties(): AidGenResult<String>
fun getContextConfig(): AidGenResult<String>
fun getProfiler(): AidGenResult<GeneratorProfile>
fun getProfileData(): String

Set 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 ​

kotlin
fun abort(): AidGenCode
fun reset(): AidGenCode
fun release(): AidGenCode
fun getLibraryVersion(): String
fun getAbiVersion(): Long
fun setLogLevel(level: AidGenLogLevel)
fun setLogFilePrefix(prefix: String): String

abort() 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 ​

ModelTypetypeName
QWEN25VL3B392qwen25vl3b392
QWEN25VL3B672qwen25vl3b672
QWEN25VL3B644qwen25vl3b644
QWEN25VL7B392qwen25vl7b392
QWEN25VL7B672qwen25vl7b672
QWEN25VL7B644qwen25vl7b644
QWEN3VL4B448qwen3vl4b448
LOCATE_ANYTHINGlocateanything
INTERNVL3internvl3
MAGEVLmagevl

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.typeDefault image sizeRequired vision resources
qwen2.5From configurationmodel, cos, sin, window mask, full mask
qwen3448 × 448model, cos, sin
locateanything672 × 392model, cos, sin
internvl3448 × 448model
magevl512 × 288model, cos, sin; mask if exposed by the model

Kotlin example ​

kotlin
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 with AidGenCode.SUCCESS; use .code for the native integer value.
  • Data methods return AidGenResult<T> with code, nullable value, and isSuccess. Check success before reading value; failures have a null value.
  • getLastErrorCode() reports the latest engine operation. Prefer the current method's return value. Version, log, and isInitialized() 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 ​

kotlin
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(): AidGenCode

configPath 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 ​

kotlin
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>
MethodInput and output
runOne nonblank text; returns its embedding vector
runBatchA nonempty list of nonblank texts; returns embeddings in input order
tokenizeNonblank text; returns token IDs
decodeNonempty 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 ​

kotlin
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 ​

kotlin
fun getLibraryVersion(): String
fun getAbiVersion(): Long
fun setLogLevel(level: AidGenLogLevel)
fun setLogFilePrefix(prefix: String): String
fun release(): AidGenCode

Version 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 ​

kotlin
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 APICurrent API
init(...): Booleaninit(...): 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(): StringgetProfiler(): AidGenResult<EmbeddingProfile>
getProperty(): StringgetExtractorProperties(): AidGenResult<String>
setProperty(...): IntsetExtractorProperty(...): AidGenCode
finalize(): Intrelease(): AidGenCode

T2E shares AidGenCode and AidGenResult<T> with the LLM and VLM APIs. Removed result suffix methods and legacy overloads are not retained.