Modern Apps git

← Modern-Apps.git

openassistant: more improvements to model usage

Commit
e788eba5bd629da9cf4f18ec77278f291cdf0c23
Author
Vayun Mathur <[email protected]>
When
2026-03-16 05:08 UTC (8 months ago)
Parents
69d3434

Diff

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 7219d987e1..589fef3af1 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt@@ -26,36 +26,51 @@ import com.vayunmathur.openassistant.ui.ConversationListScreen import com.vayunmathur.openassistant.ui.ConversationScreen import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.map+import kotlinx.coroutines.runBlocking import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import org.pytorch.executorch.extension.llm.LlmCallback import org.pytorch.executorch.extension.llm.LlmModule+import org.pytorch.executorch.extension.llm.LlmModuleConfig import java.io.File - class LLamaAPI(context: Context) { -    val llmModule = LlmModule(File(context.getExternalFilesDir(null)!!, "model.pte").absolutePath, File(context.getExternalFilesDir(null)!!, "model.bin").absolutePath, 0.8f)--    init {-        llmModule.load()+    enum class LLMState {+        READY,+        THINKING,+        GENERATING     } +    val llmModule = LlmModule(File(context.getExternalFilesDir(null)!!, "model.pte").absolutePath, File(context.getExternalFilesDir(null)!!, "tokenizer.json").absolutePath, 0.8f)+     fun run(content: String) = callbackFlow {+        _isAvailable.value = LLMState.THINKING         llmModule.generate(content, 32768, object : LlmCallback {             override fun onResult(result: String) {+                _isAvailable.value = LLMState.GENERATING                 trySend(result)+                if(result.contains("<|im_end|>")) {+                    llmModule.stop()+                }             }             override fun onStats(stats: String) {                 println(stats)                 close()             }         }, false)-        awaitClose { }+        awaitClose {+            _isAvailable.value = LLMState.READY+        }     } +    private var _isAvailable = MutableStateFlow(LLMState.READY)+    val isAvailable: StateFlow<LLMState> = _isAvailable+     val toolCallRegex = Regex("""<tool_call>\s*(.*?)\s*</tool_call>""", RegexOption.DOT_MATCHES_ALL)      fun getResponse(content: String, initialAssistantMessage: Message): Flow<Message> {@@ -63,18 +78,15 @@ class LLamaAPI(context: Context) {         var fullResponse = ""         return run(content).map { chunk ->             fullResponse += chunk-            println(fullResponse)              // Extract all current tool calls from the accumulating response             val matches = toolCallRegex.findAll(fullResponse)-            println(matches)             val toolCalls = matches.mapNotNull { match ->                 val jsonString = match.groupValues[1]                 runCatching {                     Json.decodeFromString<ToolCall>(jsonString)                 }.getOrNull()             }.toList()-            println(toolCalls)              // Update message with parsed tool calls and clean text             updatedMessage = updatedMessage.copy(@@ -110,13 +122,13 @@ class MainActivity : ComponentActivity() {         setContent {             DynamicTheme {                 InitialDownloadChecker(ds, listOf(-                    Triple("https://huggingface.co/software-mansion/react-native-executorch-qwen-3/resolve/main/qwen-3-1.7B/quantized/qwen3_1_7b_8da4w.pte", "model.pte", "Model"),-                    Triple("https://huggingface.co/software-mansion/react-native-executorch-qwen-3/resolve/main/tokenizer.json", "model.bin", "Weights")+                    Triple("https://data.vayunmathur.com/ai/model.pte", "model.pte", "Model"),+                    Triple("https://data.vayunmathur.com/ai/tokenizer.json", "tokenizer.json", "Tokenizer")                 )) {                     LaunchedEffect(Unit) {                         LLamaAPI.getInstance(this@MainActivity)                     }-                    Navigation(viewModel, ds)+                    Navigation(viewModel)                 }             }         }@@ -134,12 +146,12 @@ sealed interface Route: NavKey { }  @Composable-fun Navigation(viewModel: DatabaseViewModel, ds: DataStoreUtils) {+fun Navigation(viewModel: DatabaseViewModel) {     val backStack = rememberNavBackStack(Route.ConversationList, Route.Conversation(0))     MainNavigation(backStack) {         entry<Route.ConversationList>(metadata = ListPage{-            ConversationScreen(backStack, viewModel, ds, 0)+            ConversationScreen(backStack, viewModel, 0)         }) { ConversationListScreen(backStack, viewModel) }-        entry<Route.Conversation>(metadata = ListDetailPage()) { ConversationScreen(backStack, viewModel, ds, it.conversationID) }+        entry<Route.Conversation>(metadata = ListDetailPage()) { ConversationScreen(backStack, viewModel, it.conversationID) }     } }\ No newline at end of file
openassistant/src/main/java/com/vayunmathur/openassistant/data/Message.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/data/Message.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/data/Message.ktindex b6576ff486..90cfa1a78b 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/data/Message.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/data/Message.kt@@ -50,7 +50,7 @@ fun List<Message>.toStreamedText(tools: List<ToolSimple> = Tools.ALL_TOOLS): Str         If none of the function can be used, point it out. If the given question lacks the parameters required by the function,         also point it out. You should only return the function call in tools call sections. -        If you decide to invoke any of the function(s), you MUST put it in the format:+        If you decide to invoke any of the function(s), you MUST put it in the format, surrounded by <tool_call></tool_call>:         <tool_call>         {"name": "function_name", "arguments": {"key": "value"}}         </tool_call>
openassistant/src/main/java/com/vayunmathur/openassistant/ui/ConversationScreen.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/ConversationScreen.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/ConversationScreen.ktindex 4144c0ea59..a00157ea70 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/ConversationScreen.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/ConversationScreen.kt@@ -5,7 +5,6 @@ import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.util.Base64-import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.Image@@ -49,7 +48,6 @@ import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember-import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier@@ -69,8 +67,6 @@ import androidx.work.WorkerParameters import com.vayunmathur.library.ui.IconAdd import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.IconNavigation-import com.vayunmathur.library.ui.IconSettings-import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.DatabaseViewModel import com.vayunmathur.library.util.buildDatabase import com.vayunmathur.library.util.pop@@ -80,19 +76,12 @@ import com.vayunmathur.openassistant.R import com.vayunmathur.openassistant.Route import com.vayunmathur.openassistant.data.Conversation import com.vayunmathur.openassistant.data.Message-import com.vayunmathur.openassistant.data.ToolCall import com.vayunmathur.openassistant.data.Tools import com.vayunmathur.openassistant.data.database.MessageDao import com.vayunmathur.openassistant.data.database.MessageDatabase import com.vayunmathur.openassistant.data.toStreamedText import dev.jeziellago.compose.markdowntext.MarkdownText-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay-import kotlinx.coroutines.launch-import kotlinx.serialization.decodeFromString-import kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonObject import okio.Buffer import kotlin.random.Random import kotlin.random.nextUInt@@ -103,12 +92,9 @@ class ConversationWorker(appContext: Context, workerParams: WorkerParameters): C         val conversationID = inputData.getLong("conv_id", 0)         val userMessage = inputData.getString("userMessage")!!         val uris = inputData.getStringArray("uris")!!.map { it.toUri() }-        val ds = DataStoreUtils.getInstance(applicationContext)-        ds.setBoolean("isThinking", true)         val db = applicationContext.buildDatabase<MessageDatabase>()         val viewModel = DatabaseViewModel(db,Message::class to db.messageDao(), Conversation::class to db.conversationDao())         send(viewModel, db.messageDao(), conversationID, userMessage, uris)-        ds.setBoolean("isThinking", false)         return Result.success()     } @@ -214,43 +200,16 @@ class ConversationWorker(appContext: Context, workerParams: WorkerParameters): C     } } -fun parseToolCall(input: String): List<ToolCall> {-    return Json{-        isLenient = true-    }.decodeFromString(input);-    // Regex to find: func_name(key=value, key=value)-//    val functionRegex = Regex("""(\w+)\(([^)]+)\)""")-//    // Regex to find: key=value-//    val paramRegex = Regex("""(\w+)=([^,]+)""")-//-//    return functionRegex.findAll(input).map { match ->-//        val name = match.groupValues[1]-//        val paramsString = match.groupValues[2]-//-//        val parameters = paramRegex.findAll(paramsString).associate { paramMatch ->-//            val key = paramMatch.groupValues[1].trim()-//            val value = paramMatch.groupValues[2].trim()-//-//            // Convert the string value to the appropriate JsonElement-//            key to Json.parseToJsonElement(value)-//        }-//-//        ToolCall(name, parameters)-//    }.toList()-}- @OptIn(ExperimentalMaterial3Api::class) @Composable fun ConversationScreen(     backStack: NavBackStack<Route>,     viewModel: DatabaseViewModel,-    ds: DataStoreUtils,     conversationID: Long ) {-    val isThinking by ds.booleanFlow("isThinking").collectAsState(false)-     val context = LocalContext.current-    val coroutineScope = rememberCoroutineScope()+    val llmAPI = remember { LLamaAPI.getInstance(context) }+    val llmState by llmAPI.isAvailable.collectAsState()      val conversation by viewModel.getNullable<Conversation>(conversationID) @@ -264,7 +223,6 @@ fun ConversationScreen(     }      var userInput by remember { mutableStateOf("") }-    var showApiKeyDialog by remember { mutableStateOf(false) }     var selectedImageUris by remember { mutableStateOf<List<Uri>>(emptyList()) }     val imageLauncher = rememberLauncherForActivityResult(         contract = ActivityResultContracts.GetMultipleContents()@@ -327,18 +285,6 @@ fun ConversationScreen(             }         }     }--    if (showApiKeyDialog) {-        ApiKeyDialog(-            onDismiss = { showApiKeyDialog = false },-            onSave = { apiKey ->-                coroutineScope.launch {-                    ds.setString("api_key", apiKey)-                    showApiKeyDialog = false-                }-            }-        )-    }     Scaffold(         topBar = {             TopAppBar(@@ -357,9 +303,6 @@ fun ConversationScreen(                             IconDelete()                         }                     }-                    IconButton(onClick = { showApiKeyDialog = true }) {-                        IconSettings()-                    }                 }             )         },@@ -400,7 +343,7 @@ fun ConversationScreen(                 .fillMaxSize()                 .padding(innerPadding)         ) {-            if (visibleMessages.isEmpty() && !isThinking) {+            if (visibleMessages.isEmpty() && llmState == LLamaAPI.LLMState.READY) {                 Box(                     modifier = Modifier.fillMaxSize(),                     contentAlignment = Alignment.Center@@ -494,7 +437,7 @@ fun ConversationScreen(                             }                         }                     }-                    if (isThinking) {+                    if (llmState == LLamaAPI.LLMState.THINKING) {                         item {                             Row(                                 modifier = Modifier