Modern Apps git

← Modern-Apps.git

openassistant: improve executorch

Commit
ea7280934f1e81b9c7399612445bf2847fc9984b
Author
Vayun Mathur <[email protected]>
When
2026-03-13 16:24 UTC (8 months ago)
Parents
4b56066

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 947a4552f4..d600bc39bb 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt@@ -23,13 +23,8 @@ import com.vayunmathur.openassistant.data.Message import com.vayunmathur.openassistant.data.database.MessageDatabase import com.vayunmathur.openassistant.ui.ConversationListScreen import com.vayunmathur.openassistant.ui.ConversationScreen-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.callbackFlow-import kotlinx.coroutines.flow.flow-import kotlinx.coroutines.launch-import kotlinx.coroutines.runBlocking import kotlinx.serialization.Serializable import org.pytorch.executorch.extension.llm.LlmCallback import org.pytorch.executorch.extension.llm.LlmModule@@ -82,8 +77,8 @@ class MainActivity : ComponentActivity() {         setContent {             DynamicTheme {                 InitialDownloadChecker(ds, listOf(-                    Triple("https://huggingface.co/executorch-community/Llama-3.2-1B-Instruct-QLORA_INT4_EO8-ET/resolve/main/Llama-3.2-1B-Instruct-QLORA_INT4_EO8.pte", "model.pte", "Model"),-                    Triple("https://huggingface.co/executorch-community/Llama-3.2-1B-Instruct-QLORA_INT4_EO8-ET/resolve/main/tokenizer.model", "model.bin", "Weights")+                    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")                 )) {                     LaunchedEffect(Unit) {                         val api = LLamaAPI.getInstance(this@MainActivity)
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 9f70a1200f..7353b49962 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/data/Message.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/data/Message.kt@@ -41,50 +41,48 @@ data class Message( fun List<Message>.toStreamedText(): String {     val builder = StringBuilder() -    // Llama 3.1 start token-    builder.append("<|begin_of_text|>")+    // Qwen uses ChatML format+    // Note: Qwen typically doesn't use a "begin_of_text" string like Llama's 128000 token -    // 1. Updated System Prompt to match your specific instructions+    // 1. System Prompt     val toolSystemPrompt = """         You are an expert in composing functions. You are given a question and a set of possible functions.          Based on the question, you will need to make one or more function/tool calls to achieve the purpose. -        If none of the functions 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 of [{name: "get_weather", parameters: {latitude: 40.7128, longitude: -74.0060}}]+        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 of [{"name": "function_name", "parameters": {"key": "value"}}] an array of json objects, each representing one function call\n         You SHOULD NOT include any other text in the response.-        Here is a description of the functions in JSON format that you can invoke.-        [-            ${Tools.ALL_TOOLS.joinToString(",\n") { it.systemDescription() }}-        ]-        DO NOT call functions unless ABSOLUTELY NECESSARY. You should usually just respond in natural language to the user.++        Here is a list of functions in JSON format that you can invoke.+        ${Tools.ALL_TOOLS.joinToString("\n") { it.systemDescription() }}     """.trimIndent() -    builder.append("<|start_header_id|>system<|end_header_id|>\n\n")+    builder.append("<|im_start|>system\n")     builder.append(toolSystemPrompt)-    builder.append("<|eot_id|>")+    builder.append("<|im_end|>\n")      this.forEach { message ->-        val role = message.role-        builder.append("<|start_header_id|>$role<|end_header_id|>\n\n")+        val role = message.role // e.g., "user" or "assistant"+        builder.append("<|im_start|>$role\n") -        // Handle Tool Calls (Formatting as [name(args)])         if (message.toolCalls.isNotEmpty()) {-            val calls = message.toolCalls.joinToString(", ") { call ->-                val params = call.parameters.entries.joinToString(", ") { "${it.key}=${it.value}" }-                "${call.name}($params)"+            // Qwen 2.5/3 performs better with pure JSON objects for tool calls+            val calls = message.toolCalls.joinToString("\n") { call ->+                // Constructing a simple JSON string manually or via a serializer+                """{"name": "${call.name}", "parameters": ${call.parameters}}"""             }-            builder.append("[$calls]")-        }-        // Handle Tool Outputs or Text Content-        else {+            builder.append(calls)+        } else {             builder.append(message.textContent.trim())         } -        builder.append("<|eot_id|>")+        builder.append("<|im_end|>\n")     } -    // Preparation for the model's next response+    // Trigger the assistant's turn     if (this.lastOrNull()?.role != "assistant") {-        builder.append("<|start_header_id|>assistant<|end_header_id|>\n\n")+        builder.append("<|im_start|>assistant\n")     }      return builder.toString()
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 e61a405fab..73c95c564a 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/ConversationScreen.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/ConversationScreen.kt@@ -133,13 +133,19 @@ class ConversationWorker(appContext: Context, workerParams: WorkerParameters): C         messageDao.upsert(assistantMessage)          var fullResponse = ""+        var thinkContent = ""         var usedTools = false +        println(messagesForModel)         llamaAPI.run(messagesForModel.toStreamedText()).collect {             println("NEW CONTENT: $it")             fullResponse += it+            if(fullResponse.endsWith("</think>\n\n")) {+                thinkContent = fullResponse+                fullResponse = ""+            }             if(!fullResponse.startsWith("[")) {-                assistantMessage = assistantMessage.copy(textContent = fullResponse)+                assistantMessage = assistantMessage.copy(textContent = thinkContent + fullResponse)                 messageDao.upsert(assistantMessage)             }         }@@ -147,27 +153,51 @@ class ConversationWorker(appContext: Context, workerParams: WorkerParameters): C         if(fullResponse.startsWith("[")) {             usedTools = true -            val toolCalls = parseToolCall(fullResponse.take(fullResponse.lastIndexOf(']')+1))-            println(toolCalls)-            for(toolCall in toolCalls) {-                val tool = Tools.ALL_TOOLS.find { it.name == toolCall.name }-                if (tool != null) {-                    assistantMessage =-                        assistantMessage.copy(toolCalls = assistantMessage.toolCalls + toolCall)-                    messageDao.upsert(assistantMessage)-                    val action = tool.action-                    val result = action(toolCall.parameters, applicationContext)-                    messageDao.upsert(-                        Message(-                            Random.nextLong(),-                            conversationID,-                            "tool",-                            result.llmResponse,-                            result.userResponse,-                            emptyList()+            try {+                val toolCalls = parseToolCall(fullResponse.take(fullResponse.lastIndexOf(']') + 1))+                println(toolCalls)+                for (toolCall in toolCalls) {+                    val tool = Tools.ALL_TOOLS.find { it.name == toolCall.name }+                    if (tool != null) {+                        assistantMessage =+                            assistantMessage.copy(toolCalls = assistantMessage.toolCalls + toolCall)+                        messageDao.upsert(assistantMessage)+                        val action = tool.action+                        val result = action(toolCall.parameters, applicationContext)+                        messageDao.upsert(+                            Message(+                                0,+                                conversationID,+                                "tool",+                                result.llmResponse,+                                result.userResponse,+                                emptyList()+                            )                         )-                    )+                    } else {+                        messageDao.upsert(+                            Message(+                                0,+                                conversationID,+                                "tool",+                                "Incorrect function name",+                                null,+                                emptyList()+                            )+                        )+                    }                 }+            } catch(e: Exception) {+                messageDao.upsert(+                    Message(+                        0,+                        conversationID,+                        "tool",+                        "Invalid formatting for tool call: ${e.message}",+                        null,+                        emptyList()+                    )+                )             }         }