openassistant: fix tool calling
- Commit
7fc10f3c587b3ee6523ea51795e40caef87c6bfb- Author
- Vayun Mathur <[email protected]>
- When
- 2026-04-12 00:09 UTC (7 months ago)
- Parents
5f8f6c1
Diff
.idea/deploymentTargetSelector.xml
diff --git a/.idea/deploymentTargetSelector.xml b/.idea/deploymentTargetSelector.xmlindex 10a75ff35d..255bac6f54 100644--- a/.idea/deploymentTargetSelector.xml+++ b/.idea/deploymentTargetSelector.xml@@ -25,6 +25,7 @@ </SelectionState> <SelectionState runConfigName="openassistant"> <option name="selectionMode" value="DROPDOWN" />+ <DialogSelection /> </SelectionState> <SelectionState runConfigName="passwords"> <option name="selectionMode" value="DROPDOWN" />
openassistant/src/main/java/com/vayunmathur/openassistant/AssistantToolSet.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/AssistantToolSet.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/AssistantToolSet.ktindex 3c13c29d77..47e286326c 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/AssistantToolSet.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/AssistantToolSet.kt@@ -14,7 +14,7 @@ import kotlin.time.Clock class AssistantToolSet(private val context: Context) : ToolSet { @Tool(description = "Get the current date and time in the local timezone")- fun getLocalCurrentDateTime(): String {+ fun get_local_current_date_time(): String { val now = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()) val tzId = TimeZone.currentSystemDefault().id return "$tzId: $now"@@ -22,14 +22,14 @@ class AssistantToolSet(private val context: Context) : ToolSet { @SuppressLint("QueryPermissionsNeeded") @Tool(description = "Get a list of installed apps on the device")- fun getListOfApps(): String {+ fun get_app_list(): String { val pm = context.packageManager val apps = pm.getInstalledApplications(PackageManager.GET_META_DATA) return apps.map { it.loadLabel(pm).toString() }.toString() } @Tool(description = "Open an app given its package id")- fun openApp(@ToolParam(description = "package id") packageId: String): String {+ fun open_app(@ToolParam(description = "package id") packageId: String): String { val intent = context.packageManager.getLaunchIntentForPackage(packageId) return if (intent != null) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)@@ -39,7 +39,7 @@ class AssistantToolSet(private val context: Context) : ToolSet { } @Tool(description = "Send a message")- fun sendMessage(recipient: String, message: String): String {+ fun send_message(recipient: String, message: String): String { return try { val intent = Intent(Intent.ACTION_SENDTO).apply { data = "smsto:$recipient".toUri()@@ -52,7 +52,7 @@ class AssistantToolSet(private val context: Context) : ToolSet { } @Tool(description = "Make a phone call")- fun makePhoneCall(recipient: String): String {+ fun make_phone_call(recipient: String): String { return try { val intent = Intent(Intent.ACTION_DIAL).apply { data = "tel:$recipient".toUri()@@ -64,5 +64,5 @@ class AssistantToolSet(private val context: Context) : ToolSet { } @Tool(description = "Get weather")- fun getWeather(latitude: Double, longitude: Double): String = "Weather: 22°C, Sunny."+ fun get_weather(latitude: Double, longitude: Double): String = "Weather: 22°C, Sunny." }\ No newline at end of file
openassistant/src/main/java/com/vayunmathur/openassistant/InferenceService.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/InferenceService.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/InferenceService.ktindex 99d9c83b11..b09f361dc5 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/InferenceService.kt@@ -100,14 +100,7 @@ class InferenceService : Service() { } private fun setupConversation(id: Long, history: List<Message>) {- val systemPrompt = """- You are a helpful Android assistant. Use tool calls:- <start_function_call>tool_name(arg1="val1")<end_function_call>- Interpret tool results conversationally.- - MANDATORY: You must identify the conversation topic based on the user's first input and provide a short summary title (3-5 words). - Your very first response in this conversation MUST start exactly with <title_start>Your Summary Title<title_end>.- """.trimIndent()+ val systemPrompt = """You are a helpful Android assistant.""".trimIndent() val initialMessages = history.map { msg -> when (msg.role) {@@ -121,7 +114,7 @@ class InferenceService : Service() { systemInstruction = Contents.of(systemPrompt), initialMessages = initialMessages, tools = listOf(tool(AssistantToolSet(applicationContext))),- automaticToolCalling = false+ automaticToolCalling = true, )) currentConversationId = id }@@ -142,125 +135,75 @@ class InferenceService : Service() { timestamp = Clock.System.now().toEpochMilliseconds() )) - var isLooping = true- var nextInput: com.google.ai.edge.litertlm.Message? = null+ var fullResponseText = ""+ var displayedText = ""+ var tagBuffer = ""+ var insideTag = false+ var insideTitleBlock = false+ var titleBuffer = "" - while (isLooping) {- var fullResponseText = ""- var displayedText = ""- var tagBuffer = ""- var insideTag = false- var insideFunctionBlock = false- var insideTitleBlock = false- var titleBuffer = ""+ // On the first loop iteration, build multimodal content+ val stream = run {+ val contents = mutableListOf<Content>() - // On the first loop iteration, build multimodal content- val stream = if (nextInput == null) {- val contents = mutableListOf<Content>()- - // Add images- imagePaths.forEach { path ->- contents.add(Content.ImageFile(path))- }- - // Add audio- audioPath?.let { path ->- if (File(path).exists()) {- contents.add(Content.AudioFile(path))- }- }- - // Add text last- if (userText.isNotBlank()) {- contents.add(Content.Text(userText))+ // Add images+ imagePaths.forEach { path ->+ contents.add(Content.ImageFile(path))+ }++ // Add audio+ audioPath?.let { path ->+ if (File(path).exists()) {+ contents.add(Content.AudioFile(path)) }+ } - conv.sendMessageAsync(com.google.ai.edge.litertlm.Message.user(Contents.of(contents)))- } else {- conv.sendMessageAsync(nextInput)+ // Add text last+ if (userText.isNotBlank()) {+ contents.add(Content.Text(userText)) } - stream.catch { e ->- updateMessageInDb(aiMsgId, "Error: ${e.message}")- isLooping = false- }.collect { chunk ->- val chunkText = chunk.contents.contents.filterIsInstance<Content.Text>().joinToString("") { it.text }- fullResponseText += chunkText+ conv.sendMessageAsync(com.google.ai.edge.litertlm.Message.user(Contents.of(contents)))+ } - for (char in chunkText) {- if (char == '<') { - insideTag = true- tagBuffer = "<" - } else if (insideTag) {- tagBuffer += char- if (char == '>') {- insideTag = false- when {- tagBuffer.contains("start_function_call") -> insideFunctionBlock = true- tagBuffer.contains("end_function_call") -> insideFunctionBlock = false- tagBuffer.contains("title_start") -> insideTitleBlock = true- tagBuffer.contains("title_end") -> {- insideTitleBlock = false- updateTitleInDb(conversationId, titleBuffer.trim())- }+ stream.catch { e ->+ updateMessageInDb(aiMsgId, "Error: ${e.message}")+ }.collect { chunk ->+ val chunkText = chunk.contents.contents.filterIsInstance<Content.Text>().joinToString("") { it.text }+ fullResponseText += chunkText++ for (char in chunkText) {+ if (char == '<') {+ insideTag = true+ tagBuffer = "<"+ } else if (insideTag) {+ tagBuffer += char+ if (char == '>') {+ insideTag = false+ when {+ tagBuffer.contains("title_start") -> insideTitleBlock = true+ tagBuffer.contains("title_end") -> {+ insideTitleBlock = false+ updateTitleInDb(conversationId, titleBuffer.trim()) }- tagBuffer = "" }+ tagBuffer = ""+ }+ } else {+ if (insideTitleBlock) {+ titleBuffer += char } else {- if (insideTitleBlock) {- titleBuffer += char- } else if (!insideFunctionBlock) {- displayedText += char- }+ displayedText += char } }- - if (displayedText.isNotBlank()) {- updateMessageInDb(aiMsgId, displayedText)- } } - // Check for tool calls to continue the loop- val toolRegex = Pattern.compile("<start_function_call>(.*?)<end_function_call>", Pattern.DOTALL)- val matcher = toolRegex.matcher(fullResponseText)-- if (matcher.find()) {- val callBody = matcher.group(1)?.trim() ?: ""- val toolResult = processManualCallBody(callBody)- updateMessageInDb(aiMsgId, "Thinking...")- nextInput = com.google.ai.edge.litertlm.Message.tool(Contents.of(listOf(Content.ToolResponse("manual_action", toolResult))))- } else {- isLooping = false+ if (displayedText.isNotBlank()) {+ updateMessageInDb(aiMsgId, displayedText) } } } - private fun processManualCallBody(body: String): String {- return try {- val tools = AssistantToolSet(applicationContext)- val name = body.substringBefore("(").trim()- val argsString = body.substringAfter("(").substringBeforeLast(")")- val argsMap = mutableMapOf<String, String>()- if (argsString.isNotBlank()) {- argsString.split(",").forEach { pair ->- val parts = pair.split("=")- if (parts.size == 2) {- argsMap[parts[0].trim()] = parts[1].trim().removeSurrounding("\"").removeSurrounding("'")- }- }- }- when (name) {- "get_local_current_date_time" -> tools.getLocalCurrentDateTime()- "get_list_of_apps" -> tools.getListOfApps()- "open_app" -> tools.openApp(argsMap["packageId"] ?: "")- "send_message" -> tools.sendMessage(argsMap["recipient"] ?: "", argsMap["message"] ?: "")- "make_phone_call" -> tools.makePhoneCall(argsMap["recipient"] ?: "")- "get_weather" -> tools.getWeather(argsMap["latitude"]?.toDoubleOrNull() ?: 0.0, argsMap["longitude"]?.toDoubleOrNull() ?: 0.0)- else -> "Error: Unknown tool $name"- }- } catch (e: Exception) { "Error: ${e.message}" }- }- // Database interaction placeholders - implementation should be provided by your DB layer private suspend fun fetchHistoryFromDb(id: Long): List<Message> = viewModel.getAll<Message>().filter { it.conversationId == id } private suspend fun upsertMessageToDb(msg: Message): Long = viewModel.upsert(msg)