openassistant: use executorch
- Commit
4b5606684cdcfcbc632a0972b9a3847221c89fd5- Author
- Vayun Mathur <[email protected]>
- When
- 2026-03-13 05:04 UTC (8 months ago)
- Parents
c94d00b
Diff
.idea/vcs.xml
diff --git a/.idea/vcs.xml b/.idea/vcs.xmlindex 94a25f7f4c..91ce7ba2db 100644--- a/.idea/vcs.xml+++ b/.idea/vcs.xml@@ -2,5 +2,6 @@ <project version="4"> <component name="VcsDirectoryMappings"> <mapping directory="$PROJECT_DIR$" vcs="Git" />+ <mapping directory="$PROJECT_DIR$/openassistant/src/main/cpp/llama.cpp" vcs="Git" /> </component> </project>\ No newline at end of file
openassistant/build.gradle.kts
diff --git a/openassistant/build.gradle.kts b/openassistant/build.gradle.ktsindex e17de500c6..8708244024 100644--- a/openassistant/build.gradle.kts+++ b/openassistant/build.gradle.kts@@ -21,8 +21,7 @@ dependencies { implementation(libs.androidx.navigation3.runtime) implementation(libs.androidx.work.runtime.ktx) ksp(libs.androidx.room.compiler)-- implementation("org.codeshipping:llama-kotlin-android:0.1.3")+ implementation("org.pytorch:executorch-android:1.1.0") // markdown implementation(libs.compose.markdown)
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 f078fc3981..947a4552f4 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt@@ -23,21 +23,38 @@ 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.codeshipping.llamakotlin.LlamaModel+import org.pytorch.executorch.extension.llm.LlmCallback+import org.pytorch.executorch.extension.llm.LlmModule import java.io.File class LLamaAPI(context: Context) {- var model: LlamaModel?++ val llmModule = LlmModule(File(context.getExternalFilesDir(null)!!, "model.pte").absolutePath, File(context.getExternalFilesDir(null)!!, "model.bin").absolutePath, 0.8f) init {- runBlocking {- model = LlamaModel.load(File(context.getExternalFilesDir(null), "model.gguf").absolutePath) {- gpuLayers = 1+ llmModule.load()+ }++ fun run(content: String) = callbackFlow {+ llmModule.generate(content, 2048, object : LlmCallback {+ override fun onResult(result: String) {+ trySend(result) }- }+ override fun onStats(stats: String) {+ println(stats)+ close()+ }+ }, false)+ awaitClose { } } companion object {@@ -65,10 +82,12 @@ class MainActivity : ComponentActivity() { setContent { DynamicTheme { InitialDownloadChecker(ds, listOf(- Triple("https://huggingface.co/unsloth/gemma-3n-E2B-it-GGUF/resolve/main/gemma-3n-E2B-it-Q4_K_M.gguf", "model.gguf", "Model Weights")+ 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") )) { LaunchedEffect(Unit) {- LLamaAPI.getInstance(this@MainActivity)+ val api = LLamaAPI.getInstance(this@MainActivity)+// println(api.generateText(File(getExternalFilesDir(null)!!, "model.gguf").absolutePath, "The most important issues facing the world are")) } Navigation(viewModel, ds) }
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 0d35216f71..9f70a1200f 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/data/Message.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/data/Message.kt@@ -40,57 +40,52 @@ data class Message( fun List<Message>.toStreamedText(): String { val builder = StringBuilder()- builder.append("<bos>") - // Define the system instruction for tool use+ // Llama 3.1 start token+ builder.append("<|begin_of_text|>")++ // 1. Updated System Prompt to match your specific instructions val toolSystemPrompt = """- You have access to the following functions:- ${Tools.ALL_TOOLS.joinToString("\n") { it.systemDescription() }}- If you decide to invoke any of the function(s),- you MUST put it in the format of- {"name": function name, "parameters": {dictionary of argument name and its value}}- Even if there are no parameters, it must be an empty object- You must include nothing else in your response, including any formatting or markdown.- You also may only call one function at a time+ 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}}]+ 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. """.trimIndent() - // 1. Explicit System Turn- builder.append("<start_of_turn>system\n")+ builder.append("<|start_header_id|>system<|end_header_id|>\n\n") builder.append(toolSystemPrompt)- builder.append("<end_of_turn>\n")+ builder.append("<|eot_id|>") this.forEach { message ->- if(message.role == "tool") {- builder.append("<start_of_turn>user\n")- } else {- builder.append("<start_of_turn>${message.role}\n")- }-- // Handle Images- message.images.forEach { _ ->- builder.append("<image_soft_token>")- }+ val role = message.role+ builder.append("<|start_header_id|>$role<|end_header_id|>\n\n") - // Handle Tool Calls+ // Handle Tool Calls (Formatting as [name(args)]) if (message.toolCalls.isNotEmpty()) {- message.toolCalls.forEach { call ->- // Outputting the JSON format we told the model to use- builder.append(Json.encodeToString(call))- builder.append("\n")+ val calls = message.toolCalls.joinToString(", ") { call ->+ val params = call.parameters.entries.joinToString(", ") { "${it.key}=${it.value}" }+ "${call.name}($params)" }- } else {+ builder.append("[$calls]")+ }+ // Handle Tool Outputs or Text Content+ else { builder.append(message.textContent.trim()) } - builder.append("<end_of_turn>\n")+ builder.append("<|eot_id|>") } // Preparation for the model's next response- if (this.lastOrNull()?.role != "model") {- builder.append("<start_of_turn>model\n")+ if (this.lastOrNull()?.role != "assistant") {+ builder.append("<|start_header_id|>assistant<|end_header_id|>\n\n") } - println(builder.toString())- return builder.toString() }\ No newline at end of file
openassistant/src/main/java/com/vayunmathur/openassistant/data/Tool.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/data/Tool.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/data/Tool.ktindex ddd418e22e..176f7ecdcb 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/data/Tool.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/data/Tool.kt@@ -10,19 +10,6 @@ import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonArray import kotlinx.serialization.json.putJsonObject -@Serializable-data class Tool(- val type: String,- val function: FunctionSpec-)--@Serializable-data class FunctionSpec(- val name: String,- val description: String? = null,- val parameters: JsonObject-)- @Serializable data class ToolResult(val llmResponse: String, val userResponse: String) @@ -42,31 +29,6 @@ data class ToolSimple( val required: Boolean, ) - fun toTool(): Tool {- return Tool(- type = "function",- function = FunctionSpec(- name = name,- description = description,- parameters = buildJsonObject {- putJsonObject("properties") {- params.forEach {- putJsonObject(it.name) {- put("type", it.type)- put("description", it.description)- }- }- }- putJsonArray("required") {- params.filter { it.required }.forEach {- add(it.name)- }- }- }- )- )- }- fun systemDescription(): String { return Json.encodeToString(this) }
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 5532e43a62..e61a405fab 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/ui/ConversationScreen.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/ui/ConversationScreen.kt@@ -90,6 +90,7 @@ 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@@ -134,26 +135,39 @@ class ConversationWorker(appContext: Context, workerParams: WorkerParameters): C var fullResponse = "" var usedTools = false - llamaAPI.model!!.generateStream(messagesForModel.toStreamedText()).collect {+ llamaAPI.run(messagesForModel.toStreamedText()).collect { println("NEW CONTENT: $it") fullResponse += it- if(!fullResponse.startsWith("{")) {+ if(!fullResponse.startsWith("[")) { assistantMessage = assistantMessage.copy(textContent = fullResponse) messageDao.upsert(assistantMessage) } }- if(fullResponse.startsWith("{")) {+ println("FULL RESPONSE: $fullResponse")+ if(fullResponse.startsWith("[")) { usedTools = true- val toolCall = Json.decodeFromString<ToolCall>(fullResponse)- 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())- )++ 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()+ )+ )+ } } } @@ -182,6 +196,31 @@ 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(@@ -313,7 +352,7 @@ fun ConversationScreen( userInput, { userInput = it }, Modifier.fillMaxWidth(),- label = { Text("Ask Grok...") },+ label = { Text("Prompt...") }, singleLine = true, keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send), keyboardActions = KeyboardActions(onSend = { send() }),