openassistant: restore LiteRT-LM functionality from v2.6.8
- Commit
e563d1579722f2f81e3e3447b1d76996daff3618- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-02 16:41 UTC (2 months ago)
- Parents
0542c4a
Diff
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 910ea2d77a..7e1bc5f543 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -100,6 +100,7 @@ javaxAnnotation = "1.3.2" jsr305 = "3.0.2" zxing = "3.5.4" libphonenumber = "9.0.38"+litertlmAndroid = "0.14.0" brotli = "0.1.2" # Standalone library from the AGP toolchain (com.android.tools.build), not the plugin — # :appstore uses it at runtime to verify APK source stamps.@@ -115,6 +116,9 @@ quickjs = "1.0.15" # Git jgit = "7.8.0.202609011348-r" +# On-device AI (openassistant: LiteRT-LM chat + SigLIP2 ONNX embeddings)+onnxruntimeAndroid = "1.27.0"+ # Crypto, security & credential storage sqlcipherAndroid = "4.19.0" # Pinned at 0.101.0, not Maven Central's newest (0.86.5): the CDSI enclave identity is compiled into the@@ -294,6 +298,7 @@ javax-annotation-api = { module = "javax.annotation:javax.annotation-api", versi google-jsr305 = { module = "com.google.code.findbugs:jsr305", version.ref = "jsr305" } zxing-core = { module = "com.google.zxing:core", version.ref = "zxing" } libphonenumber = { module = "com.googlecode.libphonenumber:libphonenumber", version.ref = "libphonenumber" }+litertlm-android = { module = "com.google.ai.edge.litertlm:litertlm-android", version.ref = "litertlmAndroid" } brotli-dec = { module = "org.brotli:dec", version.ref = "brotli" } apksig = { module = "com.android.tools.build:apksig", version.ref = "apksig" } @@ -307,6 +312,9 @@ quickjs-kt = { module = "io.github.dokar3:quickjs-kt", version.ref = "quickjs" } # Git jgit = { module = "org.eclipse.jgit:org.eclipse.jgit", version.ref = "jgit" } +# On-device AI (openassistant: LiteRT-LM chat + SigLIP2 ONNX embeddings)+onnxruntime-android = { module = "com.microsoft.onnxruntime:onnxruntime-android", version.ref = "onnxruntimeAndroid" }+ # Crypto, security & credential storage sqlcipher-android = { module = "net.zetetic:sqlcipher-android", version.ref = "sqlcipherAndroid" } libsignal-android = { module = "org.signal:libsignal-android", version.ref = "libsignalAndroid" }
library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt
diff --git a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.ktindex 3441f18a55..65e6d1fd31 100644--- a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt+++ b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt@@ -6,131 +6,49 @@ package com.vayunmathur.library.downloadservice * The server must host each file under https://data.vayunmathur.com/models/ * and set Content-Length + ETag. *- * # Gemma 4 is five files, not one+ * To populate the mirror, upload these HuggingFace source files under the given+ * mirror paths (left = mirror path, right = HuggingFace source): *- * The single `.litertlm` was replaced by this repo's own `.maml` format when `:openassistant`- * moved off `com.google.ai.edge.litertlm` onto `:library:ml`. Several files rather than one because- * they have different lifetimes and different readers:- *- * * the decoder, which the GPU binds,- * * the embedding, which only the host reads a row at a time and which is therefore its own- * graph rather than tensors inside the decoder,- * * the tokenizer table, which is tiny and is read once into memory,- * * the vision tower and the audio tower, each of which is a separate encoder that produces- * soft tokens in the decoder's embedding space.- *- * The first three must be present before the assistant will start - see `Gemma4Handle.FILES`.- * The two encoders are optional at load: a device that never sends a picture or a clip still- * answers text.- *- * To populate the mirror, produce the files from the ONNX export and upload them:- *- * models/gemma4_text.maml- * <- python3 scripts/ml/maml_convert.py decoder_model_merged_fp16.onnx \- * --graph gemma4_text -o gemma4_text.maml- * models/gemma4_embed.maml- * <- python3 scripts/ml/maml_convert.py embed_tokens_fp16.onnx \- * --graph gemma4_embed -o gemma4_embed.maml- * models/gemma4_tokenizer.spm1- * <- python3 scripts/ml/gemma4_tokenizer.py --tokenizer tokenizer.json \- * -o gemma4_tokenizer.spm1- * models/gemma4_vision.maml- * <- python3 scripts/ml/maml_convert.py vision_encoder_fp16.onnx \- * --graph gemma4_vision -o gemma4_vision.maml- * models/gemma4_audio.maml- * <- python3 scripts/ml/maml_convert.py audio_encoder_fp16.onnx \- * --graph gemma4_audio -o gemma4_audio.maml- *- * The ONNX inputs are `onnx-community/gemma-4-E2B-it-ONNX`, which is Apache-2.0 and ungated.+ * models/gemma-4-E2B-it.litertlm+ * <- https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm/resolve/main/gemma-4-E2B-it.litertlm+ * models/siglip2_vision_model_fp16.onnx+ * <- https://huggingface.co/onnx-community/siglip2-base-patch16-224-ONNX/resolve/main/onnx/vision_model_fp16.onnx+ * models/siglip2_text_model_int8.onnx+ * <- https://huggingface.co/onnx-community/siglip2-base-patch16-224-ONNX/resolve/main/onnx/text_model_int8.onnx+ * models/siglip2_tokenizer.model+ * <- https://huggingface.co/onnx-community/siglip2-base-patch16-224-ONNX/resolve/main/tokenizer.model */ object ModelUrls { const val MIRROR_BASE = "https://data.vayunmathur.com/models/" - /** The decoder: 35 layers at int4 with per-block scales, converted DIRECTLY- * from the litertlm GPU bundle (scripts/ml/litertlm_to_maml.py; the ONNX- * export is a different model). Tied head (no head tensors). */- const val GEMMA_TEXT_FILE = "gemma4_text.maml"- const val GEMMA_TEXT_URL = "${MIRROR_BASE}gemma4_text.maml"- const val GEMMA_TEXT_SHA256 =- "e6b392c9d72f61d490099531edfaa38ac772f9a3fa7cc24be23f13b329ff3da3"-- /** The two embedding tables, gathered on the host. */- const val GEMMA_EMBED_FILE = "gemma4_embed.maml"- const val GEMMA_EMBED_URL = "${MIRROR_BASE}gemma4_embed.maml"- const val GEMMA_EMBED_SHA256 =- "ba0171d25feae227fc20f2c6203df7c98b3810c0f814b3be539fb0d3ed5c289f"-- /** The BPE table: 262144 pieces, byte fallback. Built from the SM- * tokenizer.json (same Gemma 4 tokenizer) by scripts/ml/gemma4_tokenizer.py. */- const val GEMMA_TOKENIZER_FILE = "gemma4_tokenizer.spm1"- const val GEMMA_TOKENIZER_URL = "${MIRROR_BASE}gemma4_tokenizer.spm1"- const val GEMMA_TOKENIZER_SHA256 =- "520d011da5e54c4319a943b636f77e9b2e3ab1eda95a860e40184300bb1c4900"-- /**- * The vision tower: 16 layers at int4, with the patch and output projections left at fp16.- *- * Optional, and deliberately not in the same download as the decoder. It is 93 MB on top of- * 2.8 GB, a device that never sends a picture never needs it, and the assistant answers text- * perfectly well without it - see `Gemma4Engine.canSeeImages`.- */- const val GEMMA_VISION_FILE = "gemma4_vision.maml"- const val GEMMA_VISION_URL = "${MIRROR_BASE}gemma4_vision.maml"- const val GEMMA_VISION_SHA256 =- "4c53c0a8383f2ea99f8beed50bd5eac203565436313d0c2dd77b389ea1cf38e3"-- /**- * The audio tower: a 12-layer conformer at int4, with the three end projections, the two- * subsampling convolutions, the twelve depthwise convolutions and the twelve- * relative-position tables all left at fp16.- *- * Optional on the same terms as the vision tower. 166 MB, and a device that never sends a- * clip never needs it.- */- const val GEMMA_AUDIO_FILE = "gemma4_audio.maml"- const val GEMMA_AUDIO_URL = "${MIRROR_BASE}gemma4_audio.maml"- const val GEMMA_AUDIO_SHA256 =- "be3ac4f968835fa257291f0845be642750f71e63e197a6e199ad5210316cb4f2"-- val GEMMA_TEXT =- ModelDownloadItem(GEMMA_TEXT_URL, GEMMA_TEXT_FILE, "Model", GEMMA_TEXT_SHA256)- val GEMMA_EMBED =- ModelDownloadItem(GEMMA_EMBED_URL, GEMMA_EMBED_FILE, "Embeddings", GEMMA_EMBED_SHA256)- val GEMMA_TOKENIZER = ModelDownloadItem(- GEMMA_TOKENIZER_URL,- GEMMA_TOKENIZER_FILE,- "Tokenizer",- GEMMA_TOKENIZER_SHA256,- )- val GEMMA_VISION =- ModelDownloadItem(GEMMA_VISION_URL, GEMMA_VISION_FILE, "Vision", GEMMA_VISION_SHA256)- val GEMMA_AUDIO =- ModelDownloadItem(GEMMA_AUDIO_URL, GEMMA_AUDIO_FILE, "Audio", GEMMA_AUDIO_SHA256)-- /**- * Everything downloaded on OpenAssistant first launch.- *- * Smallest first, so a user on a slow connection sees progress early and so the two large- * files are the ones a resume is most likely to land in the middle of. The two encoders go- * after the tokenizer and before the two large ones: together they are 259 MB, they are what- * make the assistant able to answer about a photograph or a recording, and a resume that- * stalls in the decoder should not leave them unfetched.- */- val INITIAL = listOf(GEMMA_TOKENIZER, GEMMA_VISION, GEMMA_AUDIO, GEMMA_TEXT, GEMMA_EMBED)-- /**- * Files an earlier build downloaded and this one does not use.- *- * Deleted on startup rather than left to rot: the litertlm bundle alone was several- * gigabytes, and a user upgrading would otherwise carry both copies forever.- */- val OBSOLETE = listOf(- "gemma4-2b.litertlm",- "gemma-4-E2B-it.litertlm",- "gemma-4-E2B-it-gpu.litertlm",- "gemma4.litertlm",- "gemma4-4b.litertlm",- )+ // On-disk file names (also the mirror path for the SigLIP2 files).+ const val GEMMA_FILE = "gemma4-2b.litertlm"+ const val SIGLIP_VISION_FILE = "siglip2_vision_model_fp16.onnx"+ const val SIGLIP_TEXT_FILE = "siglip2_text_model_int8.onnx"+ const val SIGLIP_TOKENIZER_FILE = "siglip2_tokenizer.model"++ // Mirror download URLs.+ const val GEMMA_URL = "${MIRROR_BASE}gemma-4-E2B-it.litertlm"+ const val SIGLIP_VISION_URL = "${MIRROR_BASE}siglip2_vision_model_fp16.onnx"+ const val SIGLIP_TEXT_URL = "${MIRROR_BASE}siglip2_text_model_int8.onnx"+ const val SIGLIP_TOKENIZER_URL = "${MIRROR_BASE}siglip2_tokenizer.model"++ // SHA-256 integrity checks (verified against the files uploaded to the mirror).+ const val GEMMA_SHA256 = "181938105e0eefd105961417e8da75903eacda102c4fce9ce90f50b97139a63c"+ const val SIGLIP_VISION_SHA256 = "a1959f7bd3993a607e48839f6d01e25b876fe76afda301b028b78eef68aabd95"+ const val SIGLIP_TEXT_SHA256 = "3a0603d3a00c05a80a6ded4743c16aaac7b1e62cdcc7e362e7ce418659b96400"+ const val SIGLIP_TOKENIZER_SHA256 = "61a7b147390c64585d6c3543dd6fc636906c9af3865a5548f27f31aee1d4c8e2"++ val GEMMA = ModelDownloadItem(GEMMA_URL, GEMMA_FILE, "Model", GEMMA_SHA256)+ val SIGLIP_VISION = ModelDownloadItem(SIGLIP_VISION_URL, SIGLIP_VISION_FILE, "Vision Model", SIGLIP_VISION_SHA256)+ val SIGLIP_TEXT = ModelDownloadItem(SIGLIP_TEXT_URL, SIGLIP_TEXT_FILE, "Text Model", SIGLIP_TEXT_SHA256)+ val SIGLIP_TOKENIZER = ModelDownloadItem(SIGLIP_TOKENIZER_URL, SIGLIP_TOKENIZER_FILE, "Tokenizer", SIGLIP_TOKENIZER_SHA256)++ /** SigLIP2 semantic-search models fetched on demand by the photos app. */+ val SIGLIP = listOf(SIGLIP_VISION, SIGLIP_TEXT, SIGLIP_TOKENIZER)++ /** Everything downloaded on OpenAssistant first launch (Gemma + SigLIP2). */+ val INITIAL = listOf(GEMMA) + SIGLIP } /** A single model file fetched from the self-hosted mirror, with optional SHA-256. */
metadata_data/photos/openassistant/1.png
diff --git a/metadata_data/photos/openassistant/1.png b/metadata_data/photos/openassistant/1.pngindex e12a87288d..64ca050550 100644Binary files a/metadata_data/photos/openassistant/1.png and b/metadata_data/photos/openassistant/1.png differ
metadata_data/photos/openassistant/2.png
diff --git a/metadata_data/photos/openassistant/2.png b/metadata_data/photos/openassistant/2.pngindex 914dd8a1bd..ff31bb7e8e 100644Binary files a/metadata_data/photos/openassistant/2.png and b/metadata_data/photos/openassistant/2.png differ
metadata_data/photos/openassistant/3.png
diff --git a/metadata_data/photos/openassistant/3.png b/metadata_data/photos/openassistant/3.pngindex 95ca7d6deb..bc4450117e 100644Binary files a/metadata_data/photos/openassistant/3.png and b/metadata_data/photos/openassistant/3.png differ
metadata_data/photos/openassistant/4.png
diff --git a/metadata_data/photos/openassistant/4.png b/metadata_data/photos/openassistant/4.pngnew file mode 100644index 0000000000..6e441ee784Binary files /dev/null and b/metadata_data/photos/openassistant/4.png differ
openassistant/build.gradle.kts
diff --git a/openassistant/build.gradle.kts b/openassistant/build.gradle.ktsindex 4b6641583e..f03d057239 100644--- a/openassistant/build.gradle.kts+++ b/openassistant/build.gradle.kts@@ -15,6 +15,19 @@ android { applicationId = "com.vayunmathur.openassistant" } + androidResources {+ // SigLIP2 .onnx encoders are downloaded to external files at runtime,+ // but the SentencePiece tokenizer.model is downloaded too; keep .onnx+ // uncompressed for consistency with the ONNX Runtime memory-mapped read.+ noCompress += "onnx"+ }++ packaging {+ jniLibs {+ pickFirsts.add("**/libLiteRtTopKOpenClSampler.so")+ pickFirsts.add("**/libc++_shared.so")+ }+ } } dependencies {@@ -29,16 +42,14 @@ dependencies { // display images implementation(project(":library:image")) - // ai: this repo's own Vulkan runtime, which replaced com.google.ai.edge.litertlm and- // its 19.83 MB liblitertlm_jni.so. The weights are the same Gemma 4 E2B, converted to- // .maml by scripts/ml/maml_convert.py.- implementation(project(":library:ml"))- // ToolRegistry reflects over AssistantToolSet's @Tool methods. This used to arrive- // transitively through the litertlm AAR, so removing that dependency took it away.- implementation(libs.kotlin.reflect)- // Was pinned to 1.11.0 only because litertlm 0.14.0 needed close$default on SendChannel.- // Kept because other code in this module now uses it directly; drop it if that changes.+ // ai+ implementation(libs.litertlm.android)+ // litertlm 0.14.0 needs kotlinx-coroutines 1.11.0 (close$default on the+ // SendChannel interface); requesting it directly wins over the transitive 1.9.0. implementation(libs.kotlinx.coroutines.android)+ // SigLIP2 image/text embedding (semantic photo search served to the photos+ // app) runs on ONNX Runtime; litertlm stays for the chat LLM.+ implementation(libs.onnxruntime.android) implementation(project(":library:downloadservice"))-}\ No newline at end of file+}
openassistant/src/main/AndroidManifest.xml
diff --git a/openassistant/src/main/AndroidManifest.xml b/openassistant/src/main/AndroidManifest.xmlindex f624325794..93fc7c0bbd 100644--- a/openassistant/src/main/AndroidManifest.xml+++ b/openassistant/src/main/AndroidManifest.xml@@ -55,6 +55,9 @@ android:supportsRtl="true" android:theme="@style/Theme.General"> + <uses-native-library android:name="libvndksupport.so" android:required="false"/>+ <uses-native-library android:name="libOpenCL.so" android:required="false"/>+ <uses-native-library android:name="libcdsprpc.so" android:required="false"/> <activity android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"
openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.ktindex eea6b6b811..9af3fa0291 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt@@ -22,7 +22,7 @@ import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack import kotlinx.serialization.Serializable import com.vayunmathur.openassistant.data.OpenAssistantRepository-import com.vayunmathur.openassistant.ui.AssistantChatUi+import com.vayunmathur.openassistant.ui.LiteRTChatUi import com.vayunmathur.openassistant.ui.SettingsPage import com.vayunmathur.openassistant.util.AssistantViewModel @@ -94,7 +94,7 @@ fun Navigation(assistantViewModel: AssistantViewModel) { // The chat column is the list pane: its NavigationSuite drawer is permanent on // Expanded, and settings renders beside it as the detail pane. entry<Route.ConversationPage>(metadata = ListPage()) {- AssistantChatUi(backStack, it.id, assistantViewModel)+ LiteRTChatUi(backStack, it.id, assistantViewModel) } entry<Route.SettingsPage>(metadata = ListDetailPage()) { SettingsPage(backStack, assistantViewModel)
openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatBubble.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/AssistantChatBubble.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatBubble.ktsimilarity index 85%rename from openassistant/src/main/java/com/vayunmathur/openassistant/ui/AssistantChatBubble.ktrename to openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatBubble.ktindex e38caf17cd..396dab4dd8 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/AssistantChatBubble.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatBubble.kt@@ -7,7 +7,6 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size@@ -24,23 +23,33 @@ import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.ClipEntry import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.net.toUri import com.vayunmathur.library.image.ImageRequest import com.vayunmathur.library.image.compose.AsyncImage-import com.vayunmathur.library.ui.*+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconCopy+import com.vayunmathur.library.ui.IconInfo+import com.vayunmathur.library.ui.IconMic+import com.vayunmathur.library.ui.LocalTextStyle+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.parseMarkdown import com.vayunmathur.openassistant.R import com.vayunmathur.openassistant.data.Message import kotlinx.coroutines.launch /**- * Message bubble, extracted from [AssistantChatUi.kt] to keep that file under- * the length limit. Behavior identical — only moved.+ * One chat message bubble, split from LiteRTChatUi.kt to satisfy the+ * one-public-composable-per-file lint rule. Behavior identical — only moved. */+@OptIn(ExperimentalMaterial3Api::class) @Composable fun ChatBubble(message: Message) { val context = LocalContext.current@@ -64,8 +73,8 @@ fun ChatBubble(message: Message) { ) } if (message.hasAudio) Row(Modifier.padding(8.dp), verticalAlignment = Alignment.CenterVertically) {- Icon(painterResource(android.R.drawable.ic_btn_speak_now), null, tint = MaterialTheme.colorScheme.onPrimary, modifier = Modifier.size(16.dp))- Text(stringResource(R.string.voice_message), Modifier.padding(start = 8.dp), color = MaterialTheme.colorScheme.onPrimary, fontSize = 14.sp)+ IconMic(tint = MaterialTheme.colorScheme.onPrimary, modifier = Modifier.size(16.dp))+ Text(stringResource(R.string.voice_message), Modifier.padding(start = 8.dp), color = MaterialTheme.colorScheme.onPrimary, fontWeight = FontWeight.Normal, fontSize = 14.sp) } if (message.text.isNotBlank()) Text(message.text, Modifier.padding(8.dp, 4.dp), color = MaterialTheme.colorScheme.onPrimary, fontSize = 15.sp) }@@ -95,7 +104,7 @@ fun ChatBubble(message: Message) { if (match != null) { val url = match.groups[2]!!.value val label = match.groups[1]!!.value- Spacer(Modifier.height(8.dp))+ Spacer(Modifier.padding(top = 8.dp)) Button( onClick = { try {@@ -104,7 +113,7 @@ fun ChatBubble(message: Message) { } context.startActivity(intent) } catch (e: Exception) {- Log.w("AssistantChatUi", "Failed to open link: $url", e)+ Log.w("LiteRTChatUi", "Failed to open link: $url", e) } }, modifier = Modifier.align(Alignment.End)
openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatInput.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/AssistantChatInput.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatInput.ktsimilarity index 84%rename from openassistant/src/main/java/com/vayunmathur/openassistant/ui/AssistantChatInput.ktrename to openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatInput.ktindex f339a8f85d..d4ae272cb2 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/AssistantChatInput.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatInput.kt@@ -20,18 +20,30 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.library.image.ImageRequest import com.vayunmathur.library.image.compose.AsyncImage-import com.vayunmathur.library.ui.*+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CardDefaults+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconMic+import com.vayunmathur.library.ui.IconSend+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextField+import com.vayunmathur.library.ui.TextFieldDefaults import com.vayunmathur.openassistant.R /**- * Message composer row, extracted from [AssistantChatUi.kt] to keep that file- * under the length limit. Behavior identical — only moved.+ * Message composer row, split from LiteRTChatUi.kt to satisfy the+ * one-public-composable-per-file lint rule. Behavior identical — only moved. */+@OptIn(ExperimentalMaterial3Api::class) @Composable fun ChatInput( modifier: Modifier,@@ -81,7 +93,7 @@ fun ChatInput( Surface(tonalElevation = 3.dp, shape = RoundedCornerShape(28.dp), color = MaterialTheme.colorScheme.surfaceVariant) { Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(8.dp, 4.dp)) { IconButton(onAddImage) { IconAdd() }- IconButton(onRecord) { Icon(painterResource(android.R.drawable.ic_btn_speak_now), "Voice") }+ IconButton(onRecord) { IconMic() } TextField( value = inputText, onValueChange = onTextChange,
openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatScreen.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatScreen.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatScreen.ktnew file mode 100644index 0000000000..adf9f42cc5--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatScreen.kt@@ -0,0 +1,88 @@+package com.vayunmathur.openassistant.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.WindowInsets+import androidx.compose.foundation.layout.asPaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.navigationBars+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.text.selection.SelectionContainer+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppBarAlignment+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconMenu+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.ui.SnackbarHost+import com.vayunmathur.library.ui.SnackbarHostState+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.openassistant.R+import com.vayunmathur.openassistant.util.ChatActions+import com.vayunmathur.openassistant.util.ChatUiState++/**+ * The chat itself, with no dependency on the ViewModel so it can be rendered from a+ * `@Preview` — see `src/screenshotTest`, which is where the store listing images come from.+ * Split from LiteRTChatUi.kt to satisfy the one-public-composable-per-file lint rule.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun ChatScreen(+ state: ChatUiState,+ actions: ChatActions,+ snackbarHostState: SnackbarHostState = remember { SnackbarHostState() },+) {+ val listState = rememberLazyListState()++ LaunchedEffect(state.messages.size) {+ if (state.messages.isNotEmpty()) listState.animateScrollToItem(state.messages.size - 1)+ }++ AppScaffold(+ title = {+ val newConv = stringResource(R.string.new_conversation)+ Text(state.title ?: newConv, fontWeight = FontWeight.Bold)+ },+ alignment = AppBarAlignment.Center,+ actions = {+ IconButton({ actions.openSettings() }) { IconSettings() }+ if (state.showNewChatButton) IconButton({ actions.newConversation() }) { IconAdd() }+ },+ navigationIcon = { if (state.showConversationsButton) IconButton({ actions.openConversations() }) { IconMenu() } },+ snackbarHost = { SnackbarHost(snackbarHostState) },+ bottomBar = {+ ChatInput(+ Modifier.padding(bottom = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()),+ inputText = state.inputText,+ onTextChange = { actions.setInputText(it) },+ selectedImageUris = state.attachments,+ isRecording = state.isRecording,+ onAddImage = { actions.addImage() },+ onRecord = { actions.record() },+ onSend = { actions.send() },+ onCancelMedia = { actions.cancelMedia() },+ onRemoveImage = { actions.removeImage(it) }+ )+ },+ scrollBehavior = appBarScrollBehavior(),+ ) { padding ->+ SelectionContainer {+ LazyColumn(state = listState, modifier = Modifier.padding(padding).fillMaxSize(), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {+ items(state.messages, key = { it.id }) { ChatBubble(it) }+ }+ }+ }+}
openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatUi.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/AssistantChatUi.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatUi.ktsimilarity index 62%rename from openassistant/src/main/java/com/vayunmathur/openassistant/ui/AssistantChatUi.ktrename to openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatUi.ktindex 674fc2d490..72b899b753 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/AssistantChatUi.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/LiteRTChatUi.kt@@ -4,10 +4,6 @@ import android.net.Uri import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.*-import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items-import androidx.compose.foundation.lazy.rememberLazyListState-import androidx.compose.foundation.text.selection.SelectionContainer import com.vayunmathur.library.ui.* import com.vayunmathur.library.ui.currentWindowAdaptiveInfo import com.vayunmathur.library.ui.NavigationSuiteScaffold@@ -25,12 +21,9 @@ import com.vayunmathur.openassistant.data.Message import com.vayunmathur.openassistant.util.AssistantViewModel import com.vayunmathur.openassistant.util.ChatActions import com.vayunmathur.openassistant.util.ChatUiState-import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.vayunmathur.library.util.NavBackStack import androidx.window.core.layout.WindowSizeClass.Companion.WIDTH_DP_EXPANDED_LOWER_BOUND-import com.vayunmathur.library.ui.IconMenu-import com.vayunmathur.library.ui.IconSettings import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.openassistant.util.copyUriToFile import kotlinx.coroutines.Dispatchers@@ -45,7 +38,7 @@ import java.io.File */ @OptIn(ExperimentalMaterial3Api::class) @Composable-fun AssistantChatUi(+fun LiteRTChatUi( backStack: NavBackStack<Route>, conversationId: Long, assistantViewModel: AssistantViewModel,@@ -161,37 +154,18 @@ fun AssistantChatUi( } }) } }) {- // On Expanded the history list is already permanent in the NavigationSuite drawer- // above, and the hamburger is hidden, so the modal drawer would be unreachable —- // render the chat directly rather than wrapping it in a drawer that can never open.- if (navType == NavigationSuiteType.None) {- ModalNavigationDrawer({- ModalDrawerSheet {- allConversations.forEach { NavigationDrawerItem({ Text(it.title) }, it.id == conversationId, { backStack.reset(Route.ConversationPage(it.id)) }, Modifier.fillMaxWidth(), icon = {}, badge = {- IconButton({- assistantViewModel.deleteConversation(it)- if (it.id == conversationId) backStack.reset(Route.ConversationPage(0))- }, Modifier.offset(x=15.dp)) {- IconDelete()- }- }) }- }- }, drawerState = drawerState) {- ChatScreen(- state = ChatUiState(- title = activeConversation?.title,- messages = filteredMessages,- inputText = inputText,- attachments = selectedImageUris,- isRecording = isRecording,- showConversationsButton = allConversations.isNotEmpty(),- showNewChatButton = conversationId != 0L,- ),- actions = actions,- snackbarHostState = snackbarHostState,- )+ ModalNavigationDrawer({+ ModalDrawerSheet {+ allConversations.forEach { NavigationDrawerItem({ Text(it.title) }, it.id == conversationId, { backStack.reset(Route.ConversationPage(it.id)) }, Modifier.fillMaxWidth(), icon = {}, badge = {+ IconButton({+ assistantViewModel.deleteConversation(it)+ if (it.id == conversationId) backStack.reset(Route.ConversationPage(0))+ }, Modifier.offset(x=15.dp)) {+ IconDelete()+ }+ }) } }- } else {+ }, drawerState = drawerState) { ChatScreen( state = ChatUiState( title = activeConversation?.title,@@ -199,7 +173,7 @@ fun AssistantChatUi( inputText = inputText, attachments = selectedImageUris, isRecording = isRecording,- showConversationsButton = false,+ showConversationsButton = navType == NavigationSuiteType.None && allConversations.isNotEmpty(), showNewChatButton = conversationId != 0L, ), actions = actions,@@ -208,56 +182,3 @@ fun AssistantChatUi( } } }--/**- * The chat itself, with no dependency on the ViewModel so it can be rendered from a- * `@Preview` — see `src/screenshotTest`, which is where the store listing images come from.- */-@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun ChatScreen(- state: ChatUiState,- actions: ChatActions,- snackbarHostState: SnackbarHostState = remember { SnackbarHostState() },-) {- val listState = rememberLazyListState()-- LaunchedEffect(state.messages.size) {- if (state.messages.isNotEmpty()) listState.animateScrollToItem(state.messages.size - 1)- }-- AppScaffold(- title = {- val newConv = stringResource(R.string.new_conversation)- Text(state.title ?: newConv, fontWeight = FontWeight.Bold)- },- alignment = AppBarAlignment.Center,- actions = {- IconButton({ actions.openSettings() }) { IconSettings() }- if (state.showNewChatButton) IconButton({ actions.newConversation() }) { IconAdd() }- },- navigationIcon = { if (state.showConversationsButton) IconButton({ actions.openConversations() }) { IconMenu() } },- snackbarHost = { SnackbarHost(snackbarHostState) },- bottomBar = {- ChatInput(- Modifier.padding(bottom = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()),- inputText = state.inputText,- onTextChange = { actions.setInputText(it) },- selectedImageUris = state.attachments,- isRecording = state.isRecording,- onAddImage = { actions.addImage() },- onRecord = { actions.record() },- onSend = { actions.send() },- onCancelMedia = { actions.cancelMedia() },- onRemoveImage = { actions.removeImage(it) }- )- },- scrollBehavior = appBarScrollBehavior(),- ) { padding ->- SelectionContainer {- LazyColumn(state = listState, modifier = Modifier.padding(padding).fillMaxSize(), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {- items(state.messages, key = { it.id }) { ChatBubble(it) }- }- }- }-}
openassistant/src/main/java/com/vayunmathur/openassistant/ui/SettingsPage.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/SettingsPage.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/SettingsPage.ktindex 54b18ea061..002d240901 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/SettingsPage.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/SettingsPage.kt@@ -33,12 +33,31 @@ fun SettingsPage(backStack: NavBackStack<Route>, viewModel: AssistantViewModel) val scope = rememberCoroutineScope() val ds = remember(context) { DataStoreUtils.getInstance(context) } + var systemPrompt by remember {+ mutableStateOf(+ ds.getString(InferenceService.KEY_SYSTEM_PROMPT)+ ?: InferenceService.DEFAULT_SYSTEM_PROMPT+ )+ } SettingsScreen(- state = SettingsUiState(memories = memories),+ state = SettingsUiState(memories = memories, systemPrompt = systemPrompt), actions = object : SettingsActions { override fun back() = backStack.pop() override fun deleteMemory(memory: Memory) = viewModel.deleteMemory(memory)+ override fun setSystemPrompt(prompt: String) {+ systemPrompt = prompt+ scope.launch { ds.setString(InferenceService.KEY_SYSTEM_PROMPT, prompt) }+ }+ override fun resetSystemPrompt() {+ systemPrompt = InferenceService.DEFAULT_SYSTEM_PROMPT+ scope.launch {+ ds.setString(+ InferenceService.KEY_SYSTEM_PROMPT,+ InferenceService.DEFAULT_SYSTEM_PROMPT+ )+ }+ } }, // Passed in rather than built inside the screen: the backup buttons need the // database passphrase, which only exists on a real device.@@ -73,6 +92,37 @@ fun SettingsScreen( actions = backupButtons, scrollBehavior = appBarScrollBehavior(), ) {+ item {+ Text(+ text = stringResource(R.string.system_prompt),+ style = MaterialTheme.typography.titleLarge,+ fontWeight = FontWeight.Bold,+ modifier = Modifier.padding(bottom = 8.dp)+ )+ }+ item {+ OutlinedTextField(+ value = state.systemPrompt,+ onValueChange = { actions.setSystemPrompt(it) },+ modifier = Modifier.fillMaxWidth(),+ label = { Text(stringResource(R.string.system_prompt)) },+ minLines = 5,+ maxLines = 12,+ )+ }+ item {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.End+ ) {+ TextButton(+ onClick = { actions.resetSystemPrompt() },+ enabled = state.systemPrompt != InferenceService.DEFAULT_SYSTEM_PROMPT+ ) {+ Text(stringResource(R.string.reset_to_default))+ }+ }+ } item { Text( text = stringResource(R.string.memories),
openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolSet.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolSet.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolSet.ktindex 2626eaccb5..0e1b1f69d4 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolSet.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolSet.kt@@ -6,6 +6,9 @@ import android.content.pm.PackageManager import android.net.Uri import android.util.Log import androidx.core.net.toUri+import com.google.ai.edge.litertlm.Tool+import com.google.ai.edge.litertlm.ToolParam+import com.google.ai.edge.litertlm.ToolSet import com.vayunmathur.library.intents.calendar.EventData import com.vayunmathur.library.intents.clock.SetAlarmData import com.vayunmathur.library.intents.clock.SetTimerData
openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantUiContract.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantUiContract.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantUiContract.ktindex 27f04b5413..edf30d6072 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantUiContract.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantUiContract.kt@@ -53,14 +53,17 @@ interface ChatActions { data class SettingsUiState( val memories: List<Memory> = emptyList(), /** The chat system prompt; editable, defaults to the built-in prompt. */+ val systemPrompt: String = "", ) /** Settings callbacks. Same no-op-default arrangement as [ChatActions]. */ interface SettingsActions { fun back() {} fun deleteMemory(memory: Memory) {}+ fun setSystemPrompt(prompt: String) {} /** Restore the system prompt to the built-in default. */+ fun resetSystemPrompt() {} companion object { val Noop: SettingsActions = object : SettingsActions {}
openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.ktindex 53ba202b12..09748691bc 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt@@ -1,6 +1,5 @@ package com.vayunmathur.openassistant.util -import com.vayunmathur.library.downloadservice.ModelUrls import android.app.Application import android.content.Intent import android.util.Log@@ -12,6 +11,7 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.openassistant.data.Conversation import com.vayunmathur.openassistant.data.Memory import com.vayunmathur.openassistant.data.Message@@ -78,6 +78,7 @@ class AssistantViewModel( init { cleanupLegacyModelFile()+ cleanupStaleSiglipModels() // Pre-warm the inference engine so the first user prompt is responsive. val context = getApplication<Application>() context.startService(Intent(context, InferenceService::class.java))@@ -212,18 +213,7 @@ class AssistantViewModel( viewModelScope.launch(Dispatchers.IO) { try { val externalDir = context.getExternalFilesDir(null) ?: return@launch- // The siglip2_* files backed the SigLIP2 embedding provider, which is- // gone along with ONNX Runtime; they are ~450 MB on installs that used it.- // The siglip2_* files backed the SigLIP2 embedding provider, which is- // gone along with ONNX Runtime; they are ~450 MB on installs that used it.- // The .litertlm bundles are the whole previous model - several gigabytes -- // left behind when the assistant moved to :library:ml's .maml format, and by- // far the largest thing an upgrading install would otherwise keep forever.- val legacyModelFiles = ModelUrls.OBSOLETE + listOf(- "siglip2_vision_model_fp16.onnx",- "siglip2_text_model_int8.onnx",- "siglip2_tokenizer.model",- )+ val legacyModelFiles = listOf("gemma4.litertlm", "gemma4-4b.litertlm") for (name in legacyModelFiles) { if (File(externalDir, name).delete()) { Log.i(TAG, "Deleted legacy model file $name")@@ -240,6 +230,39 @@ class AssistantViewModel( audioRecorder = null } + /**+ * Version the on-demand SigLIP2 model files: if [SiglipEmbedder.MODEL_VERSION]+ * changed since we last downloaded them, delete the stale files and clear the+ * downloadservice `dlid_`/`progress_` keys so they re-download on the next+ * embedding request. Unlike the gemma path this never touches+ * `dbSetupComplete` — SigLIP2 is optional and fetched on demand.+ */+ private fun cleanupStaleSiglipModels() {+ val context = getApplication<Application>()+ viewModelScope.launch(Dispatchers.IO) {+ try {+ val ds = DataStoreUtils.getInstance(context)+ val stored = ds.getLong("siglip_model_version") ?: 0L+ if (stored == SiglipEmbedder.MODEL_VERSION.toLong()) return@launch++ val externalDir = context.getExternalFilesDir(null)+ val files = listOf(+ SiglipEmbedder.VISION_FILE,+ SiglipEmbedder.TEXT_FILE,+ SiglipEmbedder.TOKENIZER_FILE,+ )+ for (name in files) {+ externalDir?.let { File(it, name).takeIf { f -> f.exists() }?.delete() }+ ds.setLong("dlid_$name", 0L)+ ds.setDouble("progress_$name", 0.0)+ }+ ds.setLong("siglip_model_version", SiglipEmbedder.MODEL_VERSION.toLong())+ } catch (e: Exception) {+ Log.e(TAG, "Error cleaning up stale SigLIP2 model files", e)+ }+ }+ }+ companion object { private const val TAG = "AssistantViewModel" }
openassistant/src/main/java/com/vayunmathur/openassistant/util/Gemma4Engine.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/Gemma4Engine.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/Gemma4Engine.ktdeleted file mode 100644index fecfd615ad..0000000000--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/Gemma4Engine.kt+++ /dev/null@@ -1,356 +0,0 @@-package com.vayunmathur.openassistant.util--import android.graphics.BitmapFactory-import android.util.Log-import com.vayunmathur.library.ml.Gemma4AudioHandle-import com.vayunmathur.library.ml.Gemma4Handle-import com.vayunmathur.library.ml.Gemma4VisionHandle-import com.vayunmathur.library.ml.Sampling-import java.io.File-import java.nio.ByteBuffer-import java.nio.ByteOrder-import java.util.concurrent.locks.ReentrantLock-import kotlin.concurrent.withLock--/**- * A chat turn on Gemma 4, replacing `com.google.ai.edge.litertlm`'s `Conversation`.- *- * # What this owns that the SDK used to- *- * The tool loop. litertlm's `automaticToolCalling = true` hid a generate / parse / invoke /- * resume cycle; [ask] is that cycle, written out. Everything else the SDK did - the template,- * the tokenizer, sampling - lives in [Gemma4Handle] and native.- *- * # One conversation at a time- *- * [Gemma4Handle] holds a single KV cache, so two turns cannot run at once. The lock is held for a- * whole turn rather than per call, because a turn is many calls and interleaving them would mix- * two conversations into one cache. `InferenceService` already serialises through a queue; the- * lock is here so that a second caller blocks rather than corrupts.- */-class Gemma4Engine(private val directory: File) : AutoCloseable {-- private val lock = ReentrantLock()- private var handle: Gemma4Handle? = null-- /** Whether the baked prefix cache has been offered to this handle yet. */- private var seededPrefix = false- private var vision: Gemma4VisionHandle? = null- private var audio: Gemma4AudioHandle? = null-- /** Whether images can be read. False leaves the assistant answering text. */- val canSeeImages: Boolean- get() = lock.withLock { vision?.isAvailable == true }-- /** Whether audio can be heard. False leaves the assistant answering text. */- val canHearAudio: Boolean- get() = lock.withLock { audio?.isAvailable == true }-- /** Whether the model is loaded and usable. */- val isReady: Boolean- get() = lock.withLock { handle?.isAvailable == true }-- /**- * Load the model if it is not loaded. Returns whether it is usable afterwards.- *- * Idempotent, so `onCreate` can pre-warm and the first turn can call it again without cost.- * Loading is slow - gigabytes of weights stream to the GPU - so callers should pre-warm off- * the main thread.- */- fun ensureLoaded(): Boolean = lock.withLock {- val live = handle- if (live != null && live.isAvailable) return@withLock true- live?.close()- val opened = Gemma4Handle.inDirectory(directory)- if (!opened.isAvailable) {- Log.w(TAG, "gemma4 did not load from $directory")- opened.close()- handle = null- return@withLock false- }- handle = opened- seededPrefix = false- // One measurement at load, logged. See `Gemma4Handle.benchmark`.- opened.benchmark()- // The vision tower is optional and downloaded separately, so a device without it still- // gets a working assistant - `canSeeImages` is how the caller finds out.- if (vision?.isAvailable != true) {- vision?.close()- val tower = Gemma4VisionHandle.inDirectory(directory)- vision = if (tower.isAvailable) tower else { tower.close(); null }- }- // The audio tower is optional and downloaded separately in the same way, so a device- // without it still gets an assistant that answers text - `canHearAudio` is how the caller- // finds out.- if (audio?.isAvailable != true) {- audio?.close()- val tower = Gemma4AudioHandle.inDirectory(directory)- audio = if (tower.isAvailable) tower else { tower.close(); null }- }- true- }-- /**- * Soft tokens for each readable image in [paths], in order.- *- * Unreadable files and images the tower refuses are dropped rather than failing the turn:- * losing one attachment is better than losing the reply. The caller compares the count with- * what it passed to decide what to tell the model.- */- fun encodeImages(paths: List<String>): List<FloatArray> = lock.withLock {- val tower = vision ?: return@withLock emptyList()- paths.mapNotNull { path ->- val bitmap = runCatching { BitmapFactory.decodeFile(path) }.getOrNull()- if (bitmap == null) {- Log.w(TAG, "cannot decode $path")- return@mapNotNull null- }- val soft = tower.encode(bitmap)- bitmap.recycle()- if (soft == null) Log.w(TAG, "the vision tower refused $path")- soft- }- }-- /**- * Soft tokens for each readable clip in [paths], in order.- *- * Drops what it cannot use exactly as [encodeImages] does - a clip that will not parse, one- * the tower refuses for being shorter than its attention band, or every clip on a device- * without the tower. The caller compares the count with what it passed.- *- * Only the 16 kHz mono PCM WAV that `WavRecorder` writes is read; see [readWavMono16k].- */- fun encodeAudio(paths: List<String>): List<FloatArray> = lock.withLock {- val tower = audio ?: return@withLock emptyList()- paths.mapNotNull { path ->- val samples = readWavMono16k(path) ?: return@mapNotNull null- val soft = tower.encode(samples)- if (soft == null) Log.w(TAG, "the audio tower refused $path")- soft- }- }-- /**- * Positions the prompt for [conversation] would occupy, against [promptCeiling].- *- * For a caller dropping history before a turn: [Gemma4Handle.generate] refuses an over-long- * prompt outright, so somebody has to shrink it first, and only the caller knows which turns- * a user can afford to lose.- */- fun positionsFor(- conversation: List<Gemma4Handle.Turn>,- system: String?,- tools: ToolRegistry?,- limit: Int = Gemma4Handle.DEFAULT_REPLY,- ): Int = lock.withLock {- val live = handle ?: return@withLock 0- live.positionsFor(conversation, system, tools?.declarations ?: emptyList(), limit)- }-- /** What [positionsFor] must not exceed if the reply is to keep its [limit]. */- fun promptCeiling(limit: Int = Gemma4Handle.DEFAULT_REPLY): Int =- Gemma4Handle.promptCeiling(limit)-- /**- * Run a turn, resolving any tool calls, and stream the visible reply to [onPartial].- *- * [onPartial] returning false stops generation - cancellation, and the early-halt the- * structured-extraction path uses.- *- * [sampling] selects the next token: sampled chat turns pass [Sampling.Chat] for the top_k- * 64 / top_p 0.95 behaviour the previous runtime had; callers that must reproduce a reply- * exactly pass null and stay greedy. Tool hops after the first inherit the same config, so- * one turn never mixes two decoding regimes.- *- * Returns the reply with all tool syntax stripped, or null if the model is unavailable.- *- * # The loop- *- * The model may answer, or may ask for a tool. If it asks, the call is invoked and both the- * call and its result are appended to the model's own turn, then generation resumes from the- * extended prompt. [MAX_TOOL_HOPS] bounds it: a model that loops on a failing tool would- * otherwise never return.- */- fun ask(- conversation: List<Gemma4Handle.Turn>,- system: String?,- tools: ToolRegistry?,- limit: Int = Gemma4Handle.DEFAULT_REPLY,- sampling: Sampling? = Sampling.Chat,- onPartial: (String) -> Boolean = { true },- ): String? = lock.withLock {- val live = handle ?: return@withLock null- if (!live.isAvailable) return@withLock null- val declarations = tools?.declarations ?: emptyList()- // Once per load: seed the caches from the baked prefix so the ~1,870 positions of system- // block and tool declarations are never prefilled here. `loadPrefix` re-encodes the text- // and refuses unless its digest matches what was baked, so a prompt that has changed- // since costs a prefill rather than an answer to a question nobody asked.- if (!seededPrefix) {- seededPrefix = true- val prefix = "<bos><|turn>system\n" + system.orEmpty() +- Gemma4Handle.declareTools(declarations)- if (!live.loadPrefix(prefix)) {- Log.i(TAG, "no usable prefix cache; the prompt will be prefilled")- }- }-- // `pending` accumulates the model's own turn across tool hops: the call it made, the- // result it got, and finally the prose. It is fed back as part of the prompt so the model- // sees its own request when it resumes.- var pending = ""- var visible = ""- for (hop in 0..MAX_TOOL_HOPS) {- // `pending` is the model's own half-written turn - the call it made and the- // result it got - and it goes in as a *continuation* so it lands inside the open- // model turn. Appending it as another `Turn` closed that turn and opened a new one.- val history = conversation- var stopped = false- val reply = live.generate(history, system, declarations, limit, pending, sampling) { partial ->- // Tool syntax is machine chatter and must not reach the UI, so only the prose- // before any call marker is streamed.- val shown = visible + strip(partial)- if (onPartial(shown)) {- // A complete call means this hop is over; stop rather than let the model- // carry on writing past a request it is waiting on.- Gemma4Handle.parseToolCall(partial) == null- } else {- stopped = true- false- }- } ?: return@withLock null-- visible += strip(reply)- if (stopped) return@withLock visible- val call = Gemma4Handle.parseToolCall(reply)- if (call == null || tools == null) return@withLock visible- if (hop == MAX_TOOL_HOPS) {- Log.w(TAG, "stopping after $MAX_TOOL_HOPS tool hops")- return@withLock visible- }- val result = tools.invoke(call)- Log.d(TAG, "tool ${call.name}(${call.arguments}) -> ${result.take(120)}")- pending += reply.substringBefore("<tool_call|>") + "<tool_call|>" +- Gemma4Handle.renderToolResponse(call.name, result)- }- visible- }-- /** Discard the conversation state. Cheap - see [Gemma4Handle.reset]. */- fun reset() = lock.withLock { handle?.reset() }-- override fun close() = lock.withLock {- handle?.close()- handle = null- vision?.close()- vision = null- audio?.close()- audio = null- }-- companion object {- private const val TAG = "Gemma4Engine"-- /** The one `wFormatTag` [readWavMono16k] accepts: uncompressed integer PCM. */- private const val WAV_PCM = 1-- /**- * 16 kHz mono samples from a PCM WAV file, or null if it is not one.- *- * Only what `WavRecorder` writes is accepted. There is no resampler and no downmix here,- * so another rate, width or channel count is refused rather than converted: [encodeAudio]- * then drops the clip, which is better than handing the tower a waveform it reads as- * noise.- */- private fun readWavMono16k(path: String): FloatArray? {- val bytes = runCatching { File(path).readBytes() }.getOrElse {- Log.w(TAG, "cannot read $path: $it")- return null- }- if (bytes.size < 12 || chunkId(bytes, 0) != "RIFF" || chunkId(bytes, 8) != "WAVE") {- Log.w(TAG, "$path is not a WAV file")- return null- }- val wav = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)- var described = false- var dataAt = -1- var dataBytes = 0- var at = 12- while (at + 8 <= bytes.size) {- val size = wav.getInt(at + 4)- if (size < 0) break- val body = at + 8- when (chunkId(bytes, at)) {- "fmt " -> {- if (size < 16 || body + 16 > bytes.size) return null- val pcm = wav.getShort(body).toInt() == WAV_PCM- val mono = wav.getShort(body + 2).toInt() == 1- val rate = wav.getInt(body + 4)- val width = wav.getShort(body + 14).toInt()- if (!pcm || !mono || rate != Gemma4AudioHandle.SAMPLE_RATE || width != 16) {- Log.w(TAG, "$path is not 16 kHz mono 16-bit PCM")- return null- }- described = true- }-- "data" -> {- dataAt = body- dataBytes = minOf(size, bytes.size - body)- }- }- // Chunks are word-aligned, so an odd size is followed by a pad byte.- at = body + size + (size and 1)- }- if (!described || dataAt < 0) {- Log.w(TAG, "$path has no 16-bit PCM data")- return null- }- // Native truncates to `MAX_SAMPLES` regardless, so a long recording is cut here- // rather than widened to floats first.- val count = minOf(dataBytes / 2, Gemma4AudioHandle.MAX_SAMPLES)- val pcm = ByteBuffer.wrap(bytes, dataAt, dataBytes)- .order(ByteOrder.LITTLE_ENDIAN).asShortBuffer()- return FloatArray(count) { pcm.get(it) / 32768f }- }-- private fun chunkId(bytes: ByteArray, at: Int): String =- String(bytes, at, 4, Charsets.US_ASCII)-- /**- * Tool calls one turn may make before the loop gives up.- *- * Eight is generous for the 25 tools `AssistantToolSet` declares - a realistic turn makes- * one or two - and bounds the pathological case where a tool keeps failing and the model- * keeps retrying it.- */- const val MAX_TOOL_HOPS = 8-- /**- * The prose in a reply, with the tool markers and everything inside them removed.- *- * Streamed partials arrive mid-marker, so a half-written `<|tool_call>` must not flash up- * in the UI: anything from an opening marker onwards is dropped whether or not it has- * been closed yet.- */- fun strip(reply: String): String {- var out = reply- for (marker in listOf("<|tool_call>", "<|tool_response>", "<|tool>")) {- val at = out.indexOf(marker)- if (at >= 0) out = out.substring(0, at)- }- // A partial marker at the very end - `<|too` - is also not prose.- val open = out.lastIndexOf('<')- if (open >= 0 && out.length - open <= "<|tool_response>".length) {- val tail = out.substring(open)- if ("<|tool_call>".startsWith(tail) || "<|tool_response>".startsWith(tail) ||- "<|tool>".startsWith(tail) || "<turn|>".startsWith(tail)- ) {- out = out.substring(0, open)- }- }- return out- }- }-}
openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.ktindex e5535c84c7..734746cff2 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -13,9 +13,11 @@ import android.os.ResultReceiver import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.content.IntentCompat-import com.vayunmathur.library.ml.Gemma4Handle+import com.google.ai.edge.litertlm.* import com.vayunmathur.library.util.SecureResultReceiver import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.library.downloadservice.downloadModels+import com.vayunmathur.library.downloadservice.ModelUrls import kotlinx.coroutines.* import kotlinx.coroutines.flow.catch import java.io.File@@ -37,68 +39,7 @@ class InferenceService : Service() { var halt: Boolean = false /** DataStore key holding the user-editable chat system prompt. */-- /**- * Role for a message recording a failure rather than something the assistant said.- *- * Rendered exactly like an assistant message - `ChatBubble` only special-cases "user" and- * "tool" - so the user still sees what went wrong. Filtered out of the prompt by- * [setupConversation], because feeding a failure back has the model treat its own error as- * something it wrote, and because it lengthens the very prompt that overflowed: without- * this, each failure makes the next one likelier and the conversation cannot recover.- */- const val ROLE_ERROR = "error"-- /**- * Turns of history that eviction will not drop merely to seat a clip.- *- * Audio displaces old turns because a trimmed clip loses its TAIL, and the tail of a- * spoken request is usually the request - "I was thinking about the trip and wondering- * whether..." cut short is a different question, not a degraded one. A forgotten exchange- * from six turns ago is not load-bearing in the same way.- *- * But a thirty-second clip is 750 positions and would erase a whole conversation to seat- * itself, so the exchange the user is currently in the middle of stays. Past this floor- * the clip yields instead, and `Gemma4Handle` trims it.- *- * This is a floor on displacing history FOR AUDIO only. It does not apply to fitting at- * all: the second pass ignores it, because a turn that cannot be sent is worse than one- * that has forgotten something.- */- const val HISTORY_FLOOR = 2-- /**- * [history] with its oldest exchanges dropped until [fits] accepts what remains.- *- * Stops at [floor] turns even if [fits] still refuses, so a caller can bound what one- * turn's attachment is allowed to cost the conversation.- *- * Separated from the measurement so the policy can be tested without a model: [fits] is- * the only thing that needs one. Returns an empty list rather than looping forever when- * even nothing fits, which leaves `generate` to refuse exactly as it does today.- */- internal fun evict(- history: List<Gemma4Handle.Turn>,- floor: Int = 0,- fits: (List<Gemma4Handle.Turn>) -> Boolean,- ): List<Gemma4Handle.Turn> {- var kept = history- while (kept.size > floor && !fits(kept)) kept = kept.drop(oldestExchange(kept))- return kept- }-- /**- * Turns in the oldest exchange: a user/model pair, or one turn when it is not a pair.- *- * Pairs keep what survives a conversation rather than a reply whose question has gone.- * The single-turn case is what a leading model turn needs - the remains of a pair whose- * user half went in an earlier call.- */- private fun oldestExchange(history: List<Gemma4Handle.Turn>): Int =- if (history.size > 1 &&- history[0].role == Gemma4Handle.Role.USER &&- history[1].role == Gemma4Handle.Role.MODEL- ) 2 else 1+ const val KEY_SYSTEM_PROMPT = "system_prompt" /** The system prompt used when the user has not set a custom one. */ val DEFAULT_SYSTEM_PROMPT = """@@ -134,28 +75,32 @@ class InferenceService : Service() { val imagePaths: Array<String>, val audioPath: String? ) : InferenceJob()++ /**+ * A SigLIP2 embedding request from another app (photos). [mode] is+ * "text", "image", or "info". Runs on [SiglipEmbedder], independent of+ * the litertlm chat [Engine], so it can be served while the LLM is busy.+ */+ data class Embedding(+ val mode: String,+ val userText: String,+ val imagePath: String?,+ val receiver: ResultReceiver,+ ) : InferenceJob() } private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private val standardQueue = Channel<InferenceJob.Standard>(Channel.UNLIMITED) private val intentQueue = Channel<InferenceJob.Intent>(Channel.UNLIMITED)+ private val embeddingQueue = Channel<InferenceJob.Embedding>(Channel.UNLIMITED) - private var engine: Gemma4Engine? = null+ /** Guards the on-demand SigLIP2 model download so we start it at most once. */+ @Volatile private var downloadJob: Job? = null - /**- * The conversation whose history is loaded, -1 for none and -2 for an intent job.- *- * Still tracked even though [Gemma4Engine.ask] re-renders the whole prompt every turn:- * switching conversations has to reload history and rebuild the tools, which capture the id.- */+ private var engine: Engine? = null+ private var currentConversation: com.google.ai.edge.litertlm.Conversation? = null private var currentConversationId: Long = -1L - /** History for the conversation being served. */- private var currentHistory: List<Gemma4Handle.Turn> = emptyList()-- /** The tool table, rebuilt per conversation because the tools capture its id. */- private var currentTools: ToolRegistry? = null- private val repository by lazy { OpenAssistantRepository.get(applicationContext) } private val conversationDao get() = repository.conversationDaoRef private val messageDao get() = repository.messageDaoRef@@ -193,6 +138,23 @@ class InferenceService : Service() { } } }+ // Embeddings run on their own consumer so they don't wait behind the+ // (possibly long) chat/intent LLM jobs — they use SiglipEmbedder, not the+ // litertlm Engine.+ serviceScope.launch {+ for (job in embeddingQueue) {+ try {+ processEmbeddingJob(job)+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ Log.e("InferenceService", "Error processing embedding job", e)+ try {+ job.receiver.send(-1, Bundle().apply { putString("error", e.localizedMessage ?: "Embedding failed") })+ } catch (_: Exception) {}+ }+ }+ } } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {@@ -204,6 +166,7 @@ class InferenceService : Service() { val userText = intent.getStringExtra("user_text") ?: "" val audioPath = intent.getStringExtra("audio_path") val schema = intent.getStringExtra("schema")+ val embedMode = intent.getStringExtra("embed_mode") val receiver = IntentCompat.getParcelableExtra(intent, "RECEIVER", ResultReceiver::class.java) val imageUris = IntentCompat.getParcelableArrayListExtra(intent, "image_uris", Uri::class.java)@@ -216,7 +179,13 @@ class InferenceService : Service() { val imagePaths = staticImagePaths + imagePathsFromUris - if (receiver != null && schema != null) {+ if (embedMode != null && receiver != null) {+ // Embedding request from another app (photos): text/image/info.+ Log.i("InferenceService", "Queueing Embedding request mode=$embedMode")+ embeddingQueue.trySend(+ InferenceJob.Embedding(embedMode, userText, imagePaths.firstOrNull(), receiver)+ )+ } else if (receiver != null && schema != null) { Log.i("InferenceService", "Queueing Intent Inference request") intentQueue.trySend(InferenceJob.Intent(userText, imagePaths, schema, receiver)) } else if (conversationId != -1L) {@@ -260,8 +229,13 @@ class InferenceService : Service() { try { Log.d("InferenceService", "Executing Intent Inference") ensureEngineInitialized()- engine?.reset()- currentConversationId = -2L++ currentConversation?.close()+ currentConversation = null+ delay(100)++ setupIntentConversation(job.schema)+ withTimeout(45000) { runIntentInferenceLoop(job.userText, job.imagePaths, job.schema, job.receiver) }@@ -275,11 +249,9 @@ class InferenceService : Service() { Log.e("InferenceService", "Error during intent inference", e) job.receiver.send(-1, Bundle().apply { putString("error", e.localizedMessage ?: getString(R.string.error_ai_engine_failed)) }) } finally {- // The next standard turn must reload its own history: this job left the cache holding- // an extraction prompt, and -1 is what forces that.+ currentConversation?.close()+ currentConversation = null currentConversationId = -1L- currentHistory = emptyList()- currentTools = null } } @@ -292,7 +264,92 @@ class InferenceService : Service() { } } + // ---------- SigLIP2 embedding provider (served to the photos app) ----------++ private suspend fun processEmbeddingJob(job: InferenceJob.Embedding) {+ val context = applicationContext++ // Models are downloaded on demand; until all three files are present,+ // report "downloading" (code 2) with aggregate progress and retry later.+ if (!SiglipEmbedder.filesPresent(context)) {+ startModelDownloadIfNeeded()+ job.receiver.send(2, Bundle().apply {+ putString("status", "downloading")+ putDouble("progress", currentDownloadProgress())+ })+ return+ }++ if (!SiglipEmbedder.isAvailable(context)) {+ job.receiver.send(-1, Bundle().apply { putString("error", "Embedder failed to load") })+ return+ }++ val dim = SiglipEmbedder.dim(context)+ when (job.mode) {+ "info" -> job.receiver.send(0, Bundle().apply {+ putString("model_id", SiglipEmbedder.MODEL_ID)+ putInt("dim", dim)+ putString("status", "ready")+ })+ "text" -> {+ val t0 = System.currentTimeMillis()+ val emb = SiglipEmbedder.textEmbedding(context, job.userText)+ Log.i("InferenceService", "Text embed (${emb?.size ?: 0}d) in ${System.currentTimeMillis() - t0}ms ok=${emb != null}")+ sendEmbedding(job.receiver, emb)+ }+ "image" -> {+ val path = job.imagePath+ val t0 = System.currentTimeMillis()+ val emb = if (path != null) SiglipEmbedder.imageEmbedding(context, File(path)) else null+ Log.i("InferenceService", "Image embed (${emb?.size ?: 0}d) in ${System.currentTimeMillis() - t0}ms ok=${emb != null} path=$path")+ sendEmbedding(job.receiver, emb)+ // The temp copy from copyUriToFile is no longer needed.+ if (path != null) runCatching { File(path).delete() }+ }+ else -> job.receiver.send(-1, Bundle().apply { putString("error", "Unknown embed_mode ${job.mode}") })+ }+ }++ private fun sendEmbedding(receiver: ResultReceiver, emb: FloatArray?) {+ if (emb == null) {+ // Provider is up but this specific item couldn't be embedded; mark it+ // per_item so the client skips just this one rather than pausing.+ receiver.send(-1, Bundle().apply {+ putString("error", "Embedding failed")+ putBoolean("per_item", true)+ })+ } else {+ receiver.send(0, Bundle().apply {+ putByteArray("embedding", SiglipEmbedder.floatsToBytes(emb))+ putString("model_id", SiglipEmbedder.MODEL_ID)+ putInt("dim", emb.size)+ })+ }+ }++ private fun startModelDownloadIfNeeded() {+ if (downloadJob?.isActive == true) return+ downloadJob = serviceScope.launch {+ try {+ val ds = DataStoreUtils.getInstance(applicationContext)+ downloadModels(applicationContext, ds, ModelUrls.SIGLIP)+ } catch (e: Exception) {+ Log.e("InferenceService", "SigLIP2 model download failed", e)+ }+ }+ }++ private fun currentDownloadProgress(): Double {+ val ds = DataStoreUtils.getInstance(applicationContext)+ val files = listOf(SiglipEmbedder.VISION_FILE, SiglipEmbedder.TEXT_FILE, SiglipEmbedder.TOKENIZER_FILE)+ return files.sumOf { ds.getDouble("progress_$it") ?: 0.0 } / files.size+ }+ private suspend fun resetConversation(conversationId: Long, userText: String) {+ currentConversation?.close()+ currentConversation = null+ delay(100) val history = fetchHistoryFromDb(conversationId) .filter { it.text != userText || it.timestamp < Clock.System.now().toEpochMilliseconds() - 1000 } setupConversation(conversationId, history)@@ -301,7 +358,7 @@ class InferenceService : Service() { private suspend fun executeStandardInference(job: InferenceJob.Standard) { try { ensureEngineInitialized()- if (currentConversationId != job.conversationId) {+ if (currentConversationId != job.conversationId || currentConversation == null || !currentConversation!!.isAlive) { resetConversation(job.conversationId, job.userText) } runInferenceLoop(job.conversationId, job.userText, job.imagePaths, job.audioPath)@@ -310,6 +367,8 @@ class InferenceService : Service() { Log.i("InferenceService", "Standard inference halted successfully.") } catch (e: Exception) { Log.e("InferenceService", "Inference failed, resetting engine for retry", e)+ currentConversation?.close()+ currentConversation = null currentConversationId = -1L engine?.close() engine = null@@ -322,32 +381,37 @@ class InferenceService : Service() { upsertMessageToDb(Message( conversationId = job.conversationId, text = getString(R.string.error_prefix, retryError.localizedMessage ?: ""),- role = ROLE_ERROR,+ role = "assistant", timestamp = Clock.System.now().toEpochMilliseconds() )) } } } - /**- * The system prompt for a structured-extraction job.- *- * A plain string now rather than a `Conversation` with its own config: there is no engine- * object to configure, so the only thing that made the intent path special was this prompt- * and the absence of tools.- */- private fun intentSystemPrompt(schema: String): String = """- You are a highly specialized data extraction engine.- Your sole purpose is to analyze the provided text and output a SINGLE valid JSON object that adheres STRICTLY to the provided JSON schema.- EXTREMELY IMPORTANT:- 1. DO NOT respond with any conversational text.- 2. DO NOT include any preamble, explanation, or postscript.- 3. Output ONLY the raw JSON object.- 4. Ensure all keys and values are properly quoted.- SCHEMA:- $schema- Start extraction immediately.- """.trimIndent()+ private fun setupIntentConversation(schema: String) {+ val systemPrompt = """+ You are a highly specialized data extraction engine.+ Your sole purpose is to analyze the provided images/text and output a SINGLE valid JSON object that adheres STRICTLY to the provided JSON schema.++ EXTREMELY IMPORTANT:+ 1. DO NOT respond with any conversational text.+ 2. DO NOT include any preamble, explanation, or postscript.+ 3. Output ONLY the raw JSON object.+ 4. Ensure all keys and values are properly quoted.++ SCHEMA:+ $schema++ Start extraction immediately.+ """.trimIndent()++ currentConversation = engine?.createConversation(ConversationConfig(+ systemInstruction = Contents.of(systemPrompt),+ initialMessages = emptyList(),+ automaticToolCalling = false,+ ))+ currentConversationId = -2L // Special ID for intent inference+ } private suspend fun runIntentInferenceLoop( userText: String,@@ -355,43 +419,48 @@ class InferenceService : Service() { schema: String, receiver: ResultReceiver ) {- val live = engine ?: return- val images = live.encodeImages(imagePaths.toList())- val prompt = userText + attachmentNote(imagePaths.size - images.size, 0)- val turns = listOf(Gemma4Handle.Turn(Gemma4Handle.Role.USER, prompt, images))-- // The early halt is the whole point of streaming here: the moment a complete object that- // satisfies the schema has arrived, there is nothing to gain by letting the model write- // its closing remarks. Preserved from the litertlm path unchanged.- var sent = false- val reply = withContext(Dispatchers.IO) {- // Greedy, not sampled: a structured extraction must reproduce its answer, and a- // sampled draw that wanders costs a schema miss rather than buying variety.- live.ask(turns, intentSystemPrompt(schema), tools = null, sampling = null) { partial ->- val candidate = tryExtractLargestJson(partial)- if (candidate != null &&- JsonSchemaValidator.validateJsonAgainstSchema(candidate, schema) == null- ) {- Log.i("InferenceService", "Valid JSON extracted and verified. Halting.")- receiver.send(0, Bundle().apply { putString("json_result", candidate) })- sent = true- false- } else {- true+ val conv = currentConversation ?: return++ val initialContents = mutableListOf<Content>()+ imagePaths.forEach { path -> initialContents.add(Content.ImageFile(path)) }+ if (userText.isNotBlank()) { initialContents.add(Content.Text(userText)) }++ val nextMessage = com.google.ai.edge.litertlm.Message.user(Contents.of(initialContents))++ var fullResponseText = ""+ Log.d("InferenceService", "Sending intent inference request (Streaming mode for safe interruption)")++ val stream = conv.sendMessageAsync(nextMessage)++ stream.collect { chunk ->+ val chunkText = chunk.contents.contents.filterIsInstance<Content.Text>().joinToString("") { it.text }+ fullResponseText += chunkText++ // Try to extract JSON and check if it matches schema+ val jsonCandidate = tryExtractLargestJson(fullResponseText)+ if (jsonCandidate != null) {+ val validationError = JsonSchemaValidator.validateJsonAgainstSchema(jsonCandidate, schema)+ if (validationError == null) {+ Log.i("InferenceService", "Valid JSON extracted and verified against schema. Halting.")+ receiver.send(0, Bundle().apply { putString("json_result", jsonCandidate) })+ throw CancellationException("HALT") } } }- if (sent) return - val finalJson = reply?.let { tryExtractLargestJson(it) }- val error = finalJson?.let { JsonSchemaValidator.validateJsonAgainstSchema(it, schema) }- if (finalJson != null && error == null) {- receiver.send(0, Bundle().apply { putString("json_result", finalJson) })- } else {- receiver.send(-1, Bundle().apply {- putString("error", error ?: getString(R.string.error_ai_json_schema_mismatch))- })+ // If it finished without tryExtractLargestJson triggering HALT (e.g. at the very end)+ val finalJson = tryExtractLargestJson(fullResponseText)+ if (finalJson != null) {+ val validationError = JsonSchemaValidator.validateJsonAgainstSchema(finalJson, schema)+ if (validationError == null) {+ receiver.send(0, Bundle().apply { putString("json_result", finalJson) })+ Log.d("InferenceService", "AI produced output: $finalJson")+ return+ } }++ Log.e("InferenceService", "AI finished generation without providing a schema-matching JSON.")+ receiver.send(-1, Bundle().apply { putString("error", getString(R.string.error_ai_json_schema_mismatch)) }) } private fun tryExtractLargestJson(text: String): String? {@@ -432,156 +501,48 @@ class InferenceService : Service() { } private suspend fun ensureEngineInitialized() {- if (engine?.isReady == true) return+ if (engine != null) return - val directory = applicationContext.getExternalFilesDir(null)- ?: throw Exception("no external files directory")- for (name in Gemma4Handle.FILES) {- val file = File(directory, name)- if (!file.isFile) throw Exception("$name is missing from $directory")- }+ @OptIn(ExperimentalApi::class)+ ExperimentalFlags.enableSpeculativeDecoding = true - val started = Gemma4Engine(directory)- val loaded = withContext(Dispatchers.IO) { started.ensureLoaded() }- if (!loaded) {- started.close()- throw Exception("gemma4 could not start on this device")- }- engine?.close()- engine = started- dumpPrefix()- }+ val modelFile = File(applicationContext.getExternalFilesDir(null)!!, "gemma4-2b.litertlm")+ if (!modelFile.exists()) throw Exception("Model file missing at ${modelFile.absolutePath}") - /** The system prompt, from settings or the default. */- /**- * Write the fixed prompt prefix to disk, for `bake_gemma4_prefix` to precompute.- *- * The tool declarations are built by reflection over [AssistantToolSet], so the desktop- * baker cannot produce them - it has no Kotlin. Rather than transcribe them into the baker- * and let the two drift silently, the app emits exactly the text it would send and the baker- * consumes that. Drift then becomes impossible by construction.- *- * Costs one small file write per load. Nothing reads it on device; it is pulled off with- * `adb` when the cache is rebuilt, which happens when the prompt or the tools change.- */- private fun dumpPrefix() {- runCatching {- val declarations =- ToolRegistry(AssistantToolSet(applicationContext, memoryDao, messageDao, 0L))- .declarations- // Exactly `Gemma4Handle.render`'s opening, with no conversation and no generation- // prompt - the part that never changes.- val prefix = "<bos><|turn>system\n" + DEFAULT_SYSTEM_PROMPT +- Gemma4Handle.declareTools(declarations)- val directory = applicationContext.getExternalFilesDir(null) ?: return- File(directory, "prefix.txt").writeText(prefix)- Log.i("InferenceService", "wrote prefix.txt, ${prefix.length} chars, " +- "${declarations.size} tools")- }.onFailure { Log.w("InferenceService", "cannot write prefix.txt: $it") }- }+ val config = EngineConfig(+ modelPath = modelFile.absolutePath,+ backend = Backend.GPU(),+ visionBackend = Backend.GPU(),+ audioBackend = Backend.CPU(),+ cacheDir = applicationContext.cacheDir.absolutePath,+ ) - /// The system prompt, which is no longer configurable.- ///- /// It is baked into a precomputed KV cache served alongside the weights, so the ~1,870- /// positions of system block and tool declarations are never evaluated on device. That only- /// works if the text is fixed: a prompt the user could edit would invalidate the cache, and- /// silently - the model would attend over keys for a prompt it was not given.- private fun systemPrompt(): String = DEFAULT_SYSTEM_PROMPT-- /**- * A note appended to the user's text for attachments the model could not read.- *- * Both towers are optional downloads and both drop what they cannot encode, so this covers a- * file that would not decode, an attachment the tower refused, and a device that never- * fetched that tower - `Gemma4Engine.canSeeImages` and `canHearAudio` say which.- *- * The note exists rather than dropping the attachment silently because a model told nothing- * answers as though it had seen the picture. Saying plainly that it did not gets "I can't see- * that image" instead of a confident invention.- */- private fun attachmentNote(unreadImages: Int, unheardAudio: Int): String {- val parts = mutableListOf<String>()- if (unreadImages > 0) {- parts += "[$unreadImages image(s) attached that could not be read]"- }- if (unheardAudio > 0) {- parts += "[$unheardAudio audio clip(s) attached that could not be heard]"+ val newEngine = Engine(config)+ withContext(Dispatchers.IO) {+ newEngine.initialize() }- return if (parts.isEmpty()) "" else parts.joinToString("\n", prefix = "\n")+ engine = newEngine } private suspend fun setupConversation(id: Long, history: List<Message>) {- currentHistory = history- .filter { it.role != ROLE_ERROR }- .map { msg ->- val role =- if (msg.role == "assistant") Gemma4Handle.Role.MODEL else Gemma4Handle.Role.USER- Gemma4Handle.Turn(role, msg.text)+ val stored = DataStoreUtils.getInstance(applicationContext).getStringAwait(KEY_SYSTEM_PROMPT)+ val systemPrompt = if (stored.isNullOrBlank()) DEFAULT_SYSTEM_PROMPT else stored++ val initialMessages = history.map { msg ->+ when (msg.role) {+ "user" -> com.google.ai.edge.litertlm.Message.user(Contents.of(msg.text))+ "assistant" -> com.google.ai.edge.litertlm.Message.model(Contents.of(msg.text))+ else -> com.google.ai.edge.litertlm.Message.user(Contents.of(msg.text)) }- currentTools =- ToolRegistry(AssistantToolSet(applicationContext, memoryDao, messageDao, id))- currentConversationId = id- engine?.reset()- }-- /**- * A note appended to the user's text when the start of the conversation has been dropped.- *- * The same reasoning as [attachmentNote], for the same reason: a model told nothing answers- * as though it still remembers, and then contradicts something it said with no cause the user- * can see. Saying so plainly gets "I no longer have that earlier part of our conversation".- */- private fun historyNote(dropped: Int): String =- "\n[$dropped earlier message(s) in this conversation are no longer available to you]"-- /**- * [history] with its oldest exchanges dropped until [turn] can actually be sent.- *- * [Gemma4Handle.generate] refuses an over-long prompt rather than shortening it, and a- * refusal here is not one bad turn but a dead conversation: the failure is written back as a- * message, so without this the next prompt is longer still.- *- * # Two passes, and history yields to the clip before the clip yields to history- *- * The first pass measures the turn WITH its audio at full length, so old turns are dropped to- * seat the clip whole - down to [HISTORY_FLOOR]. Trimming a clip costs its tail, which is- * where a spoken request usually keeps its question; dropping a six-turn-old exchange costs- * much less. Past the floor the priority inverts and `Gemma4Handle` trims the clip instead.- *- * The second pass measures TEXT ONLY with no floor. It is what guarantees the turn is- * sendable, and it is unconditional: a turn that cannot be sent is worse than one that has- * forgotten something. When the fixed prefix alone exceeds the ceiling this empties history- * entirely, which is correct - keeping one exchange there would cost the reply far more than- * it costs to have forgotten it.- *- * Dropped in user+model pairs, so what survives is still a conversation rather than a reply- * whose question has gone. A leading model turn, which is what a split pair leaves behind,- * goes on its own.- */- private fun evictToFit(- live: Gemma4Engine,- history: List<Gemma4Handle.Turn>,- turn: Gemma4Handle.Turn,- system: String?,- ): List<Gemma4Handle.Turn> {- val bare = turn.copy(audio = emptyList())- val ceiling = live.promptCeiling()- // `positionsFor` trims audio into whatever the text leaves, so asking it about the whole- // turn would always answer "fits" and history would never yield. The clip is added at its- // full length instead, which is the question actually being asked: does it fit UNTRIMMED?- val clip = turn.audio.sumOf { it.size / Gemma4Handle.SOFT_TOKEN_WIDTH }- fun text(rest: List<Gemma4Handle.Turn>) =- live.positionsFor(rest + bare, system, currentTools)-- var kept = evict(history, HISTORY_FLOOR) { text(it) + clip <= ceiling }- kept = evict(kept) { text(it) <= ceiling }- if (kept.size < history.size) {- Log.w(- "InferenceService",- "dropped ${history.size - kept.size} of ${history.size} turns to fit $ceiling",- ) }- return kept++ currentConversation = engine?.createConversation(ConversationConfig(+ systemInstruction = Contents.of(systemPrompt),+ initialMessages = initialMessages,+ tools = listOf(tool(AssistantToolSet(applicationContext, memoryDao, messageDao, id))),+ automaticToolCalling = true,+ ))+ currentConversationId = id } private suspend fun runInferenceLoop(@@ -590,7 +551,8 @@ class InferenceService : Service() { imagePaths: Array<String>, audioPath: String? ) {- val live = engine ?: return+ val conv = currentConversation ?: return+ val aiMsgId = upsertMessageToDb(Message( conversationId = conversationId, text = "...",@@ -598,80 +560,40 @@ class InferenceService : Service() { timestamp = Clock.System.now().toEpochMilliseconds() )) - val images = live.encodeImages(imagePaths.toList())- val unread = imagePaths.size - images.size- // A path whose file is not there is still an attachment the user made, and it is counted- // as unheard rather than discarded. Dropping it silently is how a recorder that never- // wrote its file, a revoked permission or a cleared cache all present as "audio is simply- // not supported" - the user attached something, the model was told nothing, and no error- // exists anywhere to explain it.- val attached = listOfNotNull(audioPath)- val present = attached.filter { File(it).exists() }- if (present.size < attached.size) {- Log.w("InferenceService", "audio was attached but no file is on disk: $audioPath")- }- val audio = live.encodeAudio(present)- val system = systemPrompt()- val attachments = attachmentNote(unread, attached.size - audio.size)- fun turnOf(note: String) = Gemma4Handle.Turn(- Gemma4Handle.Role.USER, userText + attachments + note, images, audio,- )-- // Fitted at most twice: the note telling the model it has forgotten something costs- // positions of its own, so once anything has been dropped the prompt is measured again- // with the note in place. The second pass may drop one more exchange; the count in the- // note is taken from the final result, and a one-digit change does not alter its length.- var kept = evictToFit(live, currentHistory, turnOf(""), system)- if (kept.size < currentHistory.size) {- kept = evictToFit(- live, currentHistory, turnOf(historyNote(currentHistory.size - kept.size)), system,- )- }- val dropped = currentHistory.size - kept.size- val turns = kept + turnOf(if (dropped > 0) historyNote(dropped) else "")-- // Streaming is a callback rather than a Flow now, and Room is still the channel the UI- // watches - so each partial is written straight through, exactly as before.- var stopped = false- val reply = withContext(Dispatchers.IO) {- live.ask(turns, system, currentTools) { partial ->- if (halt) {- halt = false- stopped = true- return@ask false- }- if (partial.isNotBlank()) {- runBlocking { updateMessageInDb(aiMsgId, partial) }- }- true+ var fullResponseText = ""+ val contents = mutableListOf<Content>()+ imagePaths.forEach { path -> contents.add(Content.ImageFile(path)) }+ audioPath?.let { if (File(it).exists()) contents.add(Content.AudioFile(it)) }+ if (userText.isNotBlank()) contents.add(Content.Text(userText))++ val stream = conv.sendMessageAsync(com.google.ai.edge.litertlm.Message.user(Contents.of(contents)))++ stream.catch { e ->+ Log.d("InferenceService", "Caught inference error: ${e::class.simpleName}", e)+ if (e is MissingAppException || e is StopInferenceException || e.cause is StopInferenceException || halt) {+ halt = false+ messageDao.deleteById(aiMsgId)+ } else {+ messageDao.deleteById(aiMsgId)+ throw e }- }-- if (stopped) {- messageDao.deleteById(aiMsgId)- throw CancellationException("HALT")- }- if (reply == null) {- messageDao.deleteById(aiMsgId)- // Native logs the reason under the `ModelRunner` tag before returning failure - a- // timed-out fence, a full context, a bad token. This layer only sees the null, so it- // says where the reason is rather than inventing one. "Produced nothing" on its own- // sent a real `wait_for_fences TIMEOUT` to the user as a blank reply.- throw Exception("the assistant failed; see the ModelRunner log for the reason")- }+ }.collect { chunk ->+ if (halt) {+ halt = false+ messageDao.deleteById(aiMsgId)+ throw CancellationException("HALT")+ }+ val chunkText = chunk.contents.contents.filterIsInstance<Content.Text>().joinToString("") { it.text }+ fullResponseText += chunkText - // `set_conversation_title` writes to a static rather than returning, so it is drained- // after the turn rather than inside the stream.- newTitle?.let {- updateTitleInDb(conversationId, it)- newTitle = null- }+ if(newTitle != null) {+ updateTitleInDb(conversationId, newTitle!!)+ newTitle = null+ } - if (reply.isBlank()) {- messageDao.deleteById(aiMsgId)- } else {- updateMessageInDb(aiMsgId, reply)- currentHistory = turns + Gemma4Handle.Turn(Gemma4Handle.Role.MODEL, reply)+ if (fullResponseText.isNotBlank()) {+ updateMessageInDb(aiMsgId, fullResponseText)+ } } } @@ -690,8 +612,8 @@ class InferenceService : Service() { override fun onDestroy() { serviceScope.cancel()+ currentConversation?.close() engine?.close()- engine = null super.onDestroy() } }
openassistant/src/main/java/com/vayunmathur/openassistant/util/SentencePieceTokenizer.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/SentencePieceTokenizer.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/SentencePieceTokenizer.ktnew file mode 100644index 0000000000..0d3088f88e--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/SentencePieceTokenizer.kt@@ -0,0 +1,303 @@+package com.vayunmathur.openassistant.util++import android.util.Log+import java.io.File+import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.text.Normalizer+import kotlin.math.min++/**+ * Minimal, dependency-free **SentencePiece Unigram** tokenizer for the Gemma+ * SentencePiece model (`tokenizer.model`, ~4 MB, 256k vocab) that SigLIP2 uses+ * for its text tower.+ *+ * We need raw token ids to feed SigLIP2's text ONNX model, and litertlm's Gemma+ * engine does not expose them, so this is a standalone re-implementation of the+ * two pieces we actually need:+ *+ * 1. **Model parsing** ([load]): the `.model` file is a serialized+ * `sentencepiece.ModelProto`. We hand-parse just the repeated `pieces`+ * (field 1) — each a `SentencePiece{ piece=1:string, score=2:float,+ * type=3:enum }` — because pulling in a protobuf runtime for three fields is+ * overkill. Piece **index == token id**.+ * 2. **Encoding** ([encode]): Viterbi best-path Unigram segmentation over the+ * normalized text, with **byte fallback** (Gemma enables it and ships all+ * 256 `<0xNN>` byte pieces) so every input is representable.+ *+ * ## SigLIP2 text preprocessing (flagged review risk)+ *+ * The exact normalization SigLIP2 applies is the highest-uncertainty part of the+ * photos→OpenAssistant embedding move (see the plan's "Key risks"). We apply the+ * documented SigLIP convention — lowercase, NFKC, whitespace-collapse, a+ * SentencePiece dummy-prefix space, and pad/truncate to [SEQ_LEN] with the pad+ * id — and keep every knob a named constant so it is easy to retune against the+ * reference `transformers` `Siglip2Processor` output. Image and text vectors+ * only line up if this matches, so this is the first thing to verify.+ */+class SentencePieceTokenizer private constructor(+ private val pieceToId: HashMap<String, Int>,+ private val scores: FloatArray,+ private val byteToId: IntArray, // 256 entries, -1 if absent+ private val maxPieceLen: Int,+ val unkId: Int,+ val padId: Int,+) {++ companion object {+ private const val TAG = "SentencePieceTokenizer"++ /** SentencePiece meta symbol standing in for a space (U+2581, "▁"). */+ private const val SPACE = '\u2581'++ /** SigLIP2 text tower fixed context length (padded/truncated). */+ const val SEQ_LEN = 64++ // SentencePiece piece types (sentencepiece_model.proto).+ private const val TYPE_NORMAL = 1+ private const val TYPE_UNKNOWN = 2+ private const val TYPE_CONTROL = 3+ private const val TYPE_USER_DEFINED = 4+ private const val TYPE_BYTE = 6++ /**+ * Parse a Gemma `tokenizer.model` file, or null if it can't be read.+ * `padId`/`unkId` default to the Gemma special-token ids and are refined+ * from the parsed pieces where possible.+ */+ fun load(modelFile: File): SentencePieceTokenizer? {+ return try {+ val bytes = modelFile.readBytes()+ parse(bytes)+ } catch (e: Exception) {+ Log.e(TAG, "Failed to load SentencePiece model ${modelFile.absolutePath}", e)+ null+ }+ }++ private fun parse(data: ByteArray): SentencePieceTokenizer {+ val pieces = ArrayList<String>(256_000)+ val scoreList = ArrayList<Float>(256_000)+ val types = ArrayList<Int>(256_000)++ var pos = 0+ val end = data.size+ while (pos < end) {+ val (tag, p1) = readVarint(data, pos)+ pos = p1+ val field = (tag ushr 3).toInt()+ val wire = (tag and 0x7).toInt()+ if (field == 1 && wire == 2) {+ // pieces: length-delimited SentencePiece message.+ val (len, p2) = readVarint(data, pos)+ pos = p2+ val msgEnd = pos + len.toInt()+ parsePiece(data, pos, msgEnd, pieces, scoreList, types)+ pos = msgEnd+ } else {+ pos = skipField(data, pos, wire)+ }+ }++ val n = pieces.size+ val scoresArr = FloatArray(n) { scoreList[it] }+ val pieceToId = HashMap<String, Int>(n * 2)+ val byteToId = IntArray(256) { -1 }+ var unkId = 3 // Gemma default <unk>+ var padId = 0 // Gemma default <pad>+ var maxLen = 1++ for (id in 0 until n) {+ val piece = pieces[id]+ when (types[id]) {+ TYPE_UNKNOWN -> unkId = id+ TYPE_BYTE -> {+ val b = parseBytePiece(piece)+ if (b in 0..255) byteToId[b] = id+ }+ TYPE_CONTROL -> {+ if (piece == "<pad>") padId = id+ }+ TYPE_NORMAL, TYPE_USER_DEFINED -> {+ pieceToId[piece] = id+ val cpLen = piece.codePointCount(0, piece.length)+ if (cpLen > maxLen) maxLen = cpLen+ }+ }+ }+ // Cap the DP window; real Gemma pieces are short subwords.+ maxLen = min(maxLen, 48)+ Log.i(TAG, "Loaded SentencePiece: $n pieces, unkId=$unkId, padId=$padId, maxPieceLen=$maxLen")+ return SentencePieceTokenizer(pieceToId, scoresArr, byteToId, maxLen, unkId, padId)+ }++ private fun parsePiece(+ data: ByteArray,+ start: Int,+ end: Int,+ pieces: ArrayList<String>,+ scores: ArrayList<Float>,+ types: ArrayList<Int>,+ ) {+ var pos = start+ var piece = ""+ var score = 0f+ var type = TYPE_NORMAL+ while (pos < end) {+ val (tag, p1) = readVarint(data, pos)+ pos = p1+ val field = (tag ushr 3).toInt()+ val wire = (tag and 0x7).toInt()+ when {+ field == 1 && wire == 2 -> {+ val (len, p2) = readVarint(data, pos)+ pos = p2+ val l = len.toInt()+ piece = String(data, pos, l, Charsets.UTF_8)+ pos += l+ }+ field == 2 && wire == 5 -> {+ score = ByteBuffer.wrap(data, pos, 4).order(ByteOrder.LITTLE_ENDIAN).float+ pos += 4+ }+ field == 3 && wire == 0 -> {+ val (t, p2) = readVarint(data, pos)+ pos = p2+ type = t.toInt()+ }+ else -> pos = skipField(data, pos, wire)+ }+ }+ pieces.add(piece)+ scores.add(score)+ types.add(type)+ }++ /** "<0x1F>" -> 31, else -1. */+ private fun parseBytePiece(piece: String): Int {+ if (piece.length == 6 && piece.startsWith("<0x") && piece.endsWith(">")) {+ return piece.substring(3, 5).toIntOrNull(16) ?: -1+ }+ return -1+ }++ private fun readVarint(data: ByteArray, start: Int): Pair<Long, Int> {+ var result = 0L+ var shift = 0+ var pos = start+ while (true) {+ val b = data[pos].toInt() and 0xFF+ pos+++ result = result or ((b and 0x7F).toLong() shl shift)+ if (b and 0x80 == 0) break+ shift += 7+ }+ return result to pos+ }++ private fun skipField(data: ByteArray, start: Int, wire: Int): Int {+ var pos = start+ when (wire) {+ 0 -> pos = readVarint(data, pos).second+ 1 -> pos += 8+ 2 -> {+ val (len, p) = readVarint(data, pos)+ pos = p + len.toInt()+ }+ 5 -> pos += 4+ else -> throw IllegalStateException("Unsupported wire type $wire")+ }+ return pos+ }+ }++ /**+ * Encode [text] into a fixed [SEQ_LEN]-long id array (SigLIP2 text input),+ * padded with [padId] and truncated as needed.+ */+ fun encode(text: String): IntArray {+ val ids = encodeVariable(text)+ val out = IntArray(SEQ_LEN) { padId }+ val take = min(ids.size, SEQ_LEN)+ for (i in 0 until take) out[i] = ids[i]+ return out+ }++ /** Viterbi Unigram segmentation of the normalized text (no padding). */+ private fun encodeVariable(text: String): IntArray {+ val normalized = normalize(text)+ if (normalized.isEmpty()) return IntArray(0)++ // Work over Unicode code points so multi-byte chars index cleanly.+ val cps = normalized.codePoints().toArray()+ val n = cps.size+ val bestScore = DoubleArray(n + 1) { Double.NEGATIVE_INFINITY }+ bestScore[0] = 0.0+ val prev = IntArray(n + 1) { -1 }+ val stepIds = arrayOfNulls<IntArray>(n + 1)++ for (i in 0 until n) {+ if (bestScore[i] == Double.NEGATIVE_INFINITY) continue+ // (a) Try every vocab piece starting at i.+ val maxL = min(maxPieceLen, n - i)+ val sb = StringBuilder()+ for (l in 1..maxL) {+ sb.appendCodePoint(cps[i + l - 1])+ val id = pieceToId[sb.toString()] ?: continue+ val sc = bestScore[i] + scores[id]+ if (sc > bestScore[i + l]) {+ bestScore[i + l] = sc+ prev[i + l] = i+ stepIds[i + l] = intArrayOf(id)+ }+ }+ // (b) Byte fallback for the single code point at i, so every+ // position stays reachable even with no matching piece.+ val ch = String(Character.toChars(cps[i]))+ val chBytes = ch.toByteArray(Charsets.UTF_8)+ val fallbackIds = IntArray(chBytes.size)+ var ok = true+ var fbScore = bestScore[i]+ for (k in chBytes.indices) {+ val bid = byteToId[chBytes[k].toInt() and 0xFF]+ if (bid < 0) { ok = false; break }+ fallbackIds[k] = bid+ fbScore += scores[bid]+ }+ if (ok && fbScore > bestScore[i + 1]) {+ bestScore[i + 1] = fbScore+ prev[i + 1] = i+ stepIds[i + 1] = fallbackIds+ }+ }++ if (bestScore[n] == Double.NEGATIVE_INFINITY) {+ // Should not happen with byte fallback; degrade to a single unk.+ return intArrayOf(unkId)+ }++ // Backtrack, collecting ids, then reverse.+ val rev = ArrayList<Int>()+ var pos = n+ while (pos > 0) {+ val ids = stepIds[pos] ?: intArrayOf(unkId)+ for (k in ids.indices.reversed()) rev.add(ids[k])+ pos = prev[pos]+ }+ rev.reverse()+ return rev.toIntArray()+ }++ /**+ * SigLIP text normalization: lowercase, NFKC, collapse whitespace, then the+ * SentencePiece dummy-prefix space with spaces mapped to [SPACE] (▁).+ */+ private fun normalize(text: String): String {+ val lowered = text.lowercase()+ val nfkc = Normalizer.normalize(lowered, Normalizer.Form.NFKC)+ val collapsed = nfkc.trim().replace(Regex("\\s+"), " ")+ if (collapsed.isEmpty()) return ""+ // Dummy prefix + space→▁ (SentencePiece convention).+ return (" $collapsed").replace(' ', SPACE)+ }+}
openassistant/src/main/java/com/vayunmathur/openassistant/util/SiglipEmbedder.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/SiglipEmbedder.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/SiglipEmbedder.ktnew file mode 100644index 0000000000..f65aaca127--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/SiglipEmbedder.kt@@ -0,0 +1,319 @@+package com.vayunmathur.openassistant.util++import ai.onnxruntime.OnnxTensor+import ai.onnxruntime.OrtEnvironment+import ai.onnxruntime.OrtSession+import android.content.Context+import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.util.Log+import com.vayunmathur.library.downloadservice.ModelUrls+import java.io.File+import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.nio.FloatBuffer+import java.nio.LongBuffer+import kotlin.math.sqrt++/**+ * On-device **SigLIP2-base** image/text embedder on ONNX Runtime, the semantic+ * search provider OpenAssistant serves to the photos app over [InferenceService].+ *+ * SigLIP puts images and text in one shared space: the image encoder turns a+ * photo into a vector, the text encoder turns a query into a vector, and their+ * cosine similarity says how well the phrase describes the photo. photos stores+ * the returned vectors and does cosine locally.+ *+ * Mirrors the old on-device `photos/.../ClipEmbedder.kt` (lazy single-threaded+ * [OrtSession]s, [OnnxTensor] + `run`, L2-normalize, [floatsToBytes]) but with+ * SigLIP2 preprocessing and the Gemma [SentencePieceTokenizer]:+ * - **Vision** ([VISION_FILE]): resize **directly** to [IMAGE_SIZE]² (square,+ * no shortest-side + center-crop), rescale 1/255, normalize mean/std 0.5 →+ * `(px-127.5)/127.5`, packed NCHW `[1,3,224,224]`.+ * - **Text** ([TEXT_FILE]): tokenize with [SentencePieceTokenizer] to a fixed+ * [SentencePieceTokenizer.SEQ_LEN] and run the text tower.+ *+ * The embedding [dim] is read from the model at run time (SigLIP2-base = 768)+ * and flows back to photos via the IPC `dim` key, so nothing hardcodes it.+ *+ * The three model files are downloaded on demand to `getExternalFilesDir(null)`+ * (see [InferenceService]); if any is missing [filesPresent] is false and the+ * caller triggers the download instead.+ */+object SiglipEmbedder {+ /** HuggingFace source, also the model id photos uses for change-detection. */+ const val MODEL_ID = "onnx-community/siglip2-base-patch16-224-ONNX"++ /**+ * Bump when the downloaded SigLIP2 files or preprocessing change, so+ * [com.vayunmathur.openassistant.util.AssistantViewModel] deletes the stale+ * on-disk files and they re-download on the next embedding request.+ */+ const val MODEL_VERSION = 1++ // On-disk names shared with the mirror-first downloader (single source of+ // truth in ModelUrls) so file-presence gating and the fetch always agree.+ const val VISION_FILE = ModelUrls.SIGLIP_VISION_FILE+ const val TEXT_FILE = ModelUrls.SIGLIP_TEXT_FILE+ const val TOKENIZER_FILE = ModelUrls.SIGLIP_TOKENIZER_FILE++ /** Square RGB input side the SigLIP2 image encoder expects. */+ const val IMAGE_SIZE = 224++ private const val TAG = "SiglipEmbedder"++ private val env: OrtEnvironment by lazy { OrtEnvironment.getEnvironment() }+ private val lock = Any()++ @Volatile private var visionSession: OrtSession? = null+ @Volatile private var textSession: OrtSession? = null+ @Volatile private var tokenizer: SentencePieceTokenizer? = null+ @Volatile private var visionOutputName: String? = null+ @Volatile private var textOutputName: String? = null+ @Volatile private var initTried = false+ @Volatile private var initOk = false++ /** True only if all three model files are present on disk. */+ fun filesPresent(context: Context): Boolean =+ modelFile(context, VISION_FILE).exists() &&+ modelFile(context, TEXT_FILE).exists() &&+ modelFile(context, TOKENIZER_FILE).exists()++ /** True if both encoders + tokenizer are loaded and ready. */+ fun isAvailable(context: Context): Boolean = ensureInit(context)++ /** Embedding dimension read from the vision model, or 0 if not initialised. */+ fun dim(context: Context): Int {+ if (!ensureInit(context)) return 0+ return cachedDim+ }++ @Volatile private var cachedDim = 0++ private fun modelFile(context: Context, name: String): File =+ File(context.applicationContext.getExternalFilesDir(null), name)++ private fun ensureInit(context: Context): Boolean {+ if (initOk) return true+ synchronized(lock) {+ if (initOk) return true+ if (initTried) return false+ initTried = true+ return try {+ val app = context.applicationContext+ if (!filesPresent(app)) {+ Log.w(TAG, "SigLIP2 model files missing; embedder unavailable")+ initTried = false // allow a retry once files are downloaded+ return false+ }+ val tok = SentencePieceTokenizer.load(modelFile(app, TOKENIZER_FILE)) ?: run {+ Log.w(TAG, "Failed to load SentencePiece tokenizer")+ return false+ }+ val opts = OrtSession.SessionOptions().apply {+ // Single-threaded keeps sustained CPU/battery use low.+ setIntraOpNumThreads(1)+ setInterOpNumThreads(1)+ }+ visionSession = env.createSession(modelFile(app, VISION_FILE).absolutePath, opts)+ textSession = env.createSession(modelFile(app, TEXT_FILE).absolutePath, opts)+ tokenizer = tok+ // These sub-model exports emit BOTH `last_hidden_state` and the+ // pooled embedding (`pooler_output`); we must read the pooled one,+ // not output index 0, or the vectors are meaningless.+ visionOutputName = bestOutputName(visionSession!!)+ textOutputName = bestOutputName(textSession!!)+ cachedDim = visionSession?.let { readOutputDim(it, visionOutputName!!) } ?: 0+ initOk = true+ Log.i(TAG, "SigLIP2 embedder ready (dim=$cachedDim, visionOut=$visionOutputName, textOut=$textOutputName)")+ true+ } catch (e: Throwable) {+ Log.e(TAG, "Failed to initialise SigLIP2 embedder", e)+ closeLocked()+ false+ }+ }+ }++ /**+ * Pick the output that holds the pooled embedding. SigLIP2's vision/text+ * sub-model exports emit `last_hidden_state` (rank-3) plus the pooled+ * `pooler_output` (rank-2 `[1, dim]`) — the latter is the retrieval vector.+ * Prefer a name hinting "pool"/"embed", else the first rank-2 output, else+ * output 0.+ */+ private fun bestOutputName(session: OrtSession): String {+ val info = session.outputInfo+ info.keys.firstOrNull { it.contains("pool", ignoreCase = true) }?.let { return it }+ info.keys.firstOrNull { it.contains("embed", ignoreCase = true) }?.let { return it }+ info.entries.firstOrNull { (it.value.info as? ai.onnxruntime.TensorInfo)?.shape?.size == 2 }+ ?.let { return it.key }+ return info.keys.first()+ }++ private fun readOutputDim(session: OrtSession, outputName: String): Int {+ return try {+ val info = session.outputInfo[outputName]!!.info as ai.onnxruntime.TensorInfo+ info.shape.last().toInt()+ } catch (_: Exception) {+ 0+ }+ }++ /**+ * Embed the image at [file] into an L2-normalised vector, or null on+ * failure. The file is a decoded copy handed over by [InferenceService].+ */+ fun imageEmbedding(context: Context, file: File): FloatArray? {+ if (!ensureInit(context)) return null+ val session = visionSession ?: return null+ val bitmap = try {+ BitmapFactory.decodeFile(file.absolutePath)+ } catch (e: Exception) {+ Log.e(TAG, "Failed to decode image ${file.absolutePath}", e)+ null+ } ?: return null+ val input = try {+ preprocess(bitmap)+ } finally {+ bitmap.recycle()+ }+ return try {+ synchronized(lock) {+ val inputName = session.inputNames.iterator().next()+ val outName = visionOutputName ?: bestOutputName(session)+ OnnxTensor.createTensor(+ env,+ FloatBuffer.wrap(input),+ longArrayOf(1, 3, IMAGE_SIZE.toLong(), IMAGE_SIZE.toLong()),+ ).use { tensor ->+ session.run(mapOf(inputName to tensor)).use { result ->+ val out = result.get(outName).get() as OnnxTensor+ val vec = FloatArray(out.info.shape.last().toInt())+ out.floatBuffer.get(vec)+ l2Normalize(vec)+ }+ }+ }+ } catch (e: Exception) {+ Log.e(TAG, "Image embedding failed", e)+ null+ }+ }++ /**+ * Embed [text] into an L2-normalised vector in the SAME space as+ * [imageEmbedding], or null on failure.+ */+ fun textEmbedding(context: Context, text: String): FloatArray? {+ if (!ensureInit(context)) return null+ val session = textSession ?: return null+ val tok = tokenizer ?: return null+ val ids = tok.encode(text)+ val longIds = LongArray(ids.size) { ids[it].toLong() }+ return try {+ synchronized(lock) {+ val tensors = HashMap<String, OnnxTensor>()+ try {+ for (name in session.inputNames) {+ val lname = name.lowercase()+ when {+ lname.contains("mask") -> {+ // SigLIP attends over the full padded sequence; all-ones.+ val mask = LongArray(ids.size) { 1L }+ tensors[name] = OnnxTensor.createTensor(+ env, LongBuffer.wrap(mask), longArrayOf(1, ids.size.toLong())+ )+ }+ lname.contains("position") -> {+ // Sequential positions 0..seqLen-1.+ val pos = LongArray(ids.size) { it.toLong() }+ tensors[name] = OnnxTensor.createTensor(+ env, LongBuffer.wrap(pos), longArrayOf(1, ids.size.toLong())+ )+ }+ else -> {+ // input_ids+ tensors[name] = OnnxTensor.createTensor(+ env, LongBuffer.wrap(longIds), longArrayOf(1, ids.size.toLong())+ )+ }+ }+ }+ session.run(tensors).use { result ->+ val outName = textOutputName ?: bestOutputName(session)+ val out = result.get(outName).get() as OnnxTensor+ val vec = FloatArray(out.info.shape.last().toInt())+ out.floatBuffer.get(vec)+ l2Normalize(vec)+ }+ } finally {+ tensors.values.forEach { it.close() }+ }+ }+ } catch (e: Exception) {+ Log.e(TAG, "Text embedding failed", e)+ null+ }+ }++ fun close() {+ synchronized(lock) { closeLocked() }+ }++ private fun closeLocked() {+ try { visionSession?.close() } catch (_: Exception) {}+ try { textSession?.close() } catch (_: Exception) {}+ visionSession = null+ textSession = null+ tokenizer = null+ visionOutputName = null+ textOutputName = null+ cachedDim = 0+ initOk = false+ initTried = false+ }++ /**+ * SigLIP preprocessing: resize [src] **directly** to [IMAGE_SIZE]² (no+ * center-crop), rescale to [0,1], normalize mean/std 0.5 → (px-127.5)/127.5,+ * packed NCHW (RGB).+ */+ private fun preprocess(src: Bitmap): FloatArray {+ val safe = if (src.config == Bitmap.Config.HARDWARE || src.config == null) {+ src.copy(Bitmap.Config.ARGB_8888, false)+ } else src++ val scaled = Bitmap.createScaledBitmap(safe, IMAGE_SIZE, IMAGE_SIZE, true)+ val px = IntArray(IMAGE_SIZE * IMAGE_SIZE)+ scaled.getPixels(px, 0, IMAGE_SIZE, 0, 0, IMAGE_SIZE, IMAGE_SIZE)+ if (scaled != safe) scaled.recycle()+ if (safe != src) safe.recycle()++ val area = IMAGE_SIZE * IMAGE_SIZE+ val out = FloatArray(3 * area)+ for (i in 0 until area) {+ val p = px[i]+ out[i] = (((p shr 16) and 0xFF) - 127.5f) / 127.5f // R plane+ out[area + i] = (((p shr 8) and 0xFF) - 127.5f) / 127.5f // G plane+ out[2 * area + i] = ((p and 0xFF) - 127.5f) / 127.5f // B plane+ }+ return out+ }++ // ---- Shared math + serialisation helpers ----++ fun l2Normalize(values: FloatArray): FloatArray {+ var norm = 0f+ for (v in values) norm += v * v+ norm = sqrt(norm)+ if (norm == 0f) return values+ return FloatArray(values.size) { values[it] / norm }+ }++ fun floatsToBytes(values: FloatArray): ByteArray {+ val buffer = ByteBuffer.allocate(values.size * 4).order(ByteOrder.LITTLE_ENDIAN)+ for (v in values) buffer.putFloat(v)+ return buffer.array()+ }+}
openassistant/src/main/java/com/vayunmathur/openassistant/util/Tools.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/Tools.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/Tools.ktdeleted file mode 100644index 7b1318c9e2..0000000000--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/Tools.kt+++ /dev/null@@ -1,161 +0,0 @@-package com.vayunmathur.openassistant.util--import com.vayunmathur.library.ml.Gemma4Handle-import kotlin.reflect.KFunction-import kotlin.reflect.KParameter-import kotlin.reflect.full.declaredMemberFunctions-import kotlin.reflect.full.findAnnotation-import kotlin.reflect.jvm.isAccessible--/**- * Tool declaration and dispatch, replacing `com.google.ai.edge.litertlm`'s.- *- * litertlm supplied `@Tool` / `@ToolParam` / `ToolSet` and did the reflection, the prompt- * serialisation and the call parsing behind `automaticToolCalling = true`. None of that was- * visible from this repo, so removing the SDK meant writing all three. The annotations keep the- * same names and shape so `AssistantToolSet` needed no restructuring - only its import changed.- *- * # Everything is a Double, still- *- * litertlm passed every JSON number as a `Double`, and `AssistantToolSet` has `.toLong()` /- * `.toInt()` at every call site to match. That convention is preserved rather than fixed: the- * tool bodies are long and the conversion sites are load-bearing, so changing it would be a- * large diff for no behavioural gain. [invoke] coerces to whatever the parameter actually is.- */-annotation class Tool(val description: String)--/** One argument of a [Tool]. */-annotation class ToolParam(val description: String)--/** A class whose [Tool]-annotated methods the model may call. */-interface ToolSet--/**- * The declarations and dispatch table for a [ToolSet], built once by reflection.- *- * Reflection happens at construction rather than per turn: `AssistantToolSet` has 25 tools, and- * resolving them on every message would put Kotlin reflection on the latency path of a chat.- */-class ToolRegistry(private val target: ToolSet) {-- private val byName: Map<String, KFunction<*>> =- target::class.declaredMemberFunctions- .filter { it.findAnnotation<Tool>() != null }- .associateBy { it.name }-- /**- * What the model is told it may call. Every tool, every turn, in a fixed order.- *- * # Fixed on purpose- *- * Per-turn relevance ranking was tried and reverted: it spends less context, but it also- * makes the prompt prefix **different on every turn**, and that prefix is the expensive- * thing - ~1,870 positions before the conversation even starts. A prefix that changes cannot- * be reused between turns and cannot be precomputed at all, so the model paid to rebuild it- * whenever the topic moved - about seven seconds on a Tensor G4.- *- * Declaring the same set every time costs context and buys two things back: the KV cache for- * the whole prefix survives from turn to turn, and it can be baked once by- * `bake_gemma4_prefix` and shipped, so no device ever computes it.- *- * The order must be stable too, not merely the membership - two orderings of the same tools- * are two different token sequences and share only their common head.- */- val declarations: List<Gemma4Handle.ToolDeclaration> = byName.map { (name, function) ->- Gemma4Handle.ToolDeclaration(- name = name,- description = function.findAnnotation<Tool>()?.description.orEmpty(),- parameters = function.parameters- .filter { it.kind == KParameter.Kind.VALUE }
Diff truncated.