Una biblioteca de Android que envuelve el SDK de C++ de MobileAgent con API compatibles con Kotlin y Java. Se conecta a MobileAgent Server mediante WebSocket para ejecutar, gestionar y supervisar las tareas del agente.
Descargue el SDK
Uso
Importe el archivo AAR
Copie el archivo AAR en su proyecto y agregue la dependencia al archivo build.gradle:
dependencies {
implementation(files('libs/sdk-release.aar'))
}
Uso básico
Opción 1: use Flow (recomendado)
Flow proporciona un manejo reactivo de eventos para las corrutinas de Kotlin:
import com.wuying.mobileagentsdk.MobileAgentSdk
import com.wuying.mobileagentsdk.MobileAgentEvent
import com.wuying.mobileagentsdk.MobileAgentState
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.collectLatest
// Use try-with-resources to automatically manage the lifecycle.
MobileAgentSdk().use { sdk ->
// Collect events in a coroutine.
lifecycleScope.launch {
sdk.events.collectLatest { event ->
when (event) {
is MobileAgentEvent.StateChanged -> {
when (event.state) {
MobileAgentState.CONNECTED -> {
Log.d("SDK", "Connected")
// Execute a task.
sdk.executeTask("Please help me open settings", 10)
}
MobileAgentState.DISCONNECTED -> {
Log.d("SDK", "Disconnected")
}
else -> {}
}
}
is MobileAgentEvent.TaskResult -> {
Log.d("SDK", "Task complete: ${event.resultText}")
}
is MobileAgentEvent.Stream -> {
Log.d("SDK", "Stream data: ${event.content}")
}
else -> {}
}
}
}
// You can also collect only specific types of events.
lifecycleScope.launch {
sdk.events
.filterIsInstance<MobileAgentEvent.StateChanged>()
.collect { event ->
Log.d("SDK", "State: ${event.state}")
}
}
lifecycleScope.launch {
sdk.events
.filterIsInstance<MobileAgentEvent.TaskResult>()
.collect { event ->
Log.d("SDK", "Task result: ${event.resultText}")
}
}
// Connect to the server.
sdk.connect("wss://localhost:30005/ws")
// The SDK is automatically destroyed at the end of the use block.
}
Opción 2: use una devolución de llamada
Para proyectos sin corrutinas:
import com.wuying.mobileagentsdk.MobileAgentSdk
import com.wuying.mobileagentsdk.MobileAgentCallback
import com.wuying.mobileagentsdk.MobileAgentState
MobileAgentSdk().use { sdk ->
// Set the callback.
sdk.setCallback(object : MobileAgentCallback {
override fun onStateChanged(state: MobileAgentState) {
when (state) {
MobileAgentState.CONNECTED -> {
Log.d("SDK", "Connected")
sdk.executeTask("Please help me open settings", 10)
}
MobileAgentState.DISCONNECTED -> {
Log.d("SDK", "Disconnected")
}
else -> {}
}
}
override fun onTaskResult(
taskId: String,
result: String,
resultText: String,
success: Boolean,
actualSteps: Int
) {
Log.d("SDK", "Task complete: $resultText")
}
override fun onStream(
taskId: String,
step: Int,
agent: String,
contentType: String,
content: String
) {
Log.d("SDK", "Stream data: $content")
}
// Implement other callbacks as needed.
})
// Connect to the server.
sdk.connect("wss://localhost:30005/ws")
}
Gestión del ciclo de vida
El SDK implementa AutoCloseable para liberar los recursos automáticamente:
// Recommended: Automatically manage the lifecycle.
MobileAgentSdk().use { sdk ->
sdk.connect("wss://localhost:30005/ws")
// Use the SDK...
} // Automatically calls close() to release resources.
// Or, manage the lifecycle manually.
val sdk = MobileAgentSdk()
try {
sdk.connect("wss://localhost:30005/ws")
// Use the SDK...
} finally {
sdk.close() // or sdk.destroy()
}
API
Gestión de la conexión
connect(url: String)
Establece la conexión con el servidor:
sdk.connect("wss://localhost:30005/ws")
connectWithTicket(ticket: String)
Establece la conexión con un ticket (requiere compatibilidad del lado del servidor):
sdk.connectWithTicket("your-ticket-here")
disconnect()
Cierra la conexión con el servidor:
sdk.disconnect()
Gestión de tareas
executeTask(task: String, maxSteps: Int): String
Ejecuta una tarea y devuelve su identificador:
val taskId = sdk.executeTask("Please help me open the settings app", 10)
pauseTask(taskId: String)
Pausa una tarea:
sdk.pauseTask(taskId)
resumeTask(taskId: String)
Reanuda una tarea:
sdk.resumeTask(taskId)
cancelTask(taskId: String)
Cancele una tarea:
sdk.cancelTask(taskId)
Consulta de estado
getState(): MobileAgentState
Devuelve el estado actual de la conexión:
val state = sdk.getState()
when (state) {
MobileAgentState.CONNECTED -> // Connected
MobileAgentState.CONNECTING -> // Connecting
MobileAgentState.DISCONNECTED -> // Disconnected
}
API de Flow
El Flow events emite todos los tipos de eventos. Utilice filterIsInstance para filtrar eventos específicos:
// Collect all events.
sdk.events.collect { event ->
when (event) {
is MobileAgentEvent.StateChanged -> // Handle state changes.
is MobileAgentEvent.TaskResult -> // Handle task results.
is MobileAgentEvent.Stream -> // Handle stream data.
// ...
}
}
// Collect only specific types of events.
sdk.events
.filterIsInstance<MobileAgentEvent.StateChanged>()
.collect { event ->
// Handle only state changes.
}
Tipos de eventos:
|
Tipo de evento |
Descripción |
|
|
El estado de la conexión cambió |
|
|
La lista de tareas pendientes se actualizó |
|
|
La tarea inició |
|
|
El paso inició |
|
|
Se recibieron datos de streaming |
|
|
El paso finalizó |
|
|
Se recibió el resultado de la tarea |
API de devoluciones de llamada
Métodos de MobileAgentCallback. Todos tienen implementaciones predeterminadas vacías; sobrescriba solo lo que necesite:
|
Método |
Descripción |
|
|
El estado de la conexión cambió |
|
|
La lista de tareas pendientes se actualizó |
|
|
La tarea inició |
|
|
El paso inició |
|
|
Se recibieron datos de streaming |
|
|
El paso finalizó |
|
|
Se recibió el resultado de la tarea |
|
|
Mensaje JSON sin procesar ni analizar sintácticamente |
Clases de datos
MobileAgentState
Enumeración del estado de la conexión:
enum class MobileAgentState {
DISCONNECTED, // Disconnected
CONNECTING, // Connecting
CONNECTED // Connected
}
TodoItem
Clase de datos de un elemento de la lista de tareas pendientes:
data class TodoItem(
val id: String,
val title: String,
val status: String,
val details: String
)
MobileAgentEvent
Clase sellada para todos los tipos de eventos:
sealed class MobileAgentEvent {
data class StateChanged(val state: MobileAgentState)
data class TodoWrite(val todos: Array<TodoItem>, val count: Int)
data class TaskStart(val taskId: String, val task: String, val maxSteps: Int)
data class StepStart(val taskId: String, val step: Int)
data class Stream(val taskId: String, val step: Int, val agent: String, val contentType: String, val content: String)
data class StepEnd(val taskId: String, val step: Int, val status: String, val summary: String)
data class TaskResult(val taskId: String, val result: String, val resultText: String, val success: Boolean, val actualSteps: Int)
}
Uso avanzado
Analice sintácticamente el razonamiento del agente
MobileAgent envuelve el razonamiento del agente dentro de etiquetas <conclusion> en la salida de streaming. Extraiga este contenido de los eventos Stream.
Formato de <conclusion>
Formato XML:
<conclusion>This is the agent's thought process...</conclusion>
Implementación en Kotlin
Analice sintácticamente el razonamiento conforme llegan los datos de streaming:
import com.wuying.mobileagentsdk.MobileAgentSdk
import com.wuying.mobileagentsdk.MobileAgentEvent
class ConclusionParser {
private val conclusionBuffer = StringBuilder()
private var inConclusion = false
/**
* Processes stream data to extract content from <conclusion> tags.
*/
fun processStream(content: String): String? {
val result = StringBuilder()
for (char in content) {
if (!inConclusion) {
// Not inside a conclusion; check for the start of <conclusion>.
conclusionBuffer.append(char)
// Check for <conclusion>.
if (conclusionBuffer.length >= 12) {
if (conclusionBuffer.endsWith("<conclusion>")) {
inConclusion = true
conclusionBuffer.clear()
result.append("[Thought] ")
} else if (conclusionBuffer.length > 12) {
// Keep the last 11 characters for the next check.
conclusionBuffer.delete(0, conclusionBuffer.length - 11)
}
}
} else {
// Inside a conclusion; check for the end tag.
conclusionBuffer.append(char)
// Check for </conclusion>.
if (conclusionBuffer.length >= 13) {
if (conclusionBuffer.endsWith("</conclusion>")) {
// Found the end tag.
inConclusion = false
val conclusionContent = conclusionBuffer.toString()
.dropLast(13) // Remove </conclusion>.
.trim()
if (conclusionContent.isNotEmpty()) {
result.append(conclusionContent).append("\n")
}
conclusionBuffer.clear()
continue
} else if (conclusionBuffer.length > 13) {
// Keep the last 12 characters for the next check.
conclusionBuffer.delete(0, conclusionBuffer.length - 12)
}
}
// If not part of a potential end tag, output immediately.
if (!couldBeEndTag(conclusionBuffer.toString())) {
result.append(char)
}
}
}
return if (result.isNotEmpty()) result.toString() else null
}
/**
* Checks if the end of the buffer could be a prefix of the end tag.
*/
private fun couldBeEndTag(buffer: String): Boolean {
val prefixes = listOf(
"<", "</", "</c", "</co", "</con", "</conc",
"</concl", "</conclu", "</conclus", "</conclusi",
"</conclusio", "</conclusion"
)
return prefixes.any { buffer.endsWith(it) }
}
/**
* Resets the parser state.
*/
fun reset() {
conclusionBuffer.clear()
inConclusion = false
}
}
// Sample usage
MobileAgentSdk().use { sdk ->
val parser = ConclusionParser()
lifecycleScope.launch {
sdk.events
.filterIsInstance<MobileAgentEvent.Stream>()
.collect { event ->
// Parse and print the output.
val output = parser.processStream(event.content)
if (output != null) {
print(output)
}
}
}
sdk.connect("wss://localhost:30005/ws")
}
Versión simplificada
Para analizar sintácticamente después de que finalice la tarea, en lugar de hacerlo durante el streaming:
/**
* Extracts all content from <conclusion> tags in a complete string.
*/
fun extractConclusions(content: String): List<String> {
val conclusions = mutableListOf<String>()
val regex = "<conclusion>(.*?)</conclusion>".toRegex(RegexOption.DOT_MATCHES_ALL)
for (match in regex.findAll(content)) {
val conclusion = match.groupValues[1].trim()
if (conclusion.isNotEmpty()) {
conclusions.add(conclusion)
}
}
return conclusions
}
// Sample usage
lifecycleScope.launch {
sdk.events
.filterIsInstance<MobileAgentEvent.TaskResult>()
.collect { event ->
// Extract the thought process from the task result.
val conclusions = extractConclusions(event.resultText)
println("Agent's thought process:")
conclusions.forEachIndexed { index, conclusion ->
println("${index + 1}. $conclusion")
}
}
}
Salida
[Thought] The user wants to open the Settings app. I need to find its package name and Activity.
[Thought] By querying the system app list, I found the Settings app: com.android.settings/.Settings
[Thought] Now I will start the Settings app.
Task complete: Successfully opened the settings app.
Uso conjunto de Flow y devoluciones de llamada
Ambos enfoques funcionan de manera simultánea:
MobileAgentSdk().use { sdk ->
// Use Flow to handle the main logic.
lifecycleScope.launch {
sdk.events
.filterIsInstance<MobileAgentEvent.TaskResult>()
.collect { event ->
// Handle the task result.
}
}
// Use a callback for logging.
sdk.setCallback(object : MobileAgentCallback {
override fun onRawMessage(rawJson: String) {
// Log raw messages for debugging.
Log.d("SDK_RAW", rawJson)
}
})
sdk.connect("wss://localhost:30005/ws")
}
Manejo de errores
try {
MobileAgentSdk().use { sdk ->
sdk.connect("wss://localhost:30005/ws")
}
} catch (e: IllegalStateException) {
Log.e("SDK", "Failed to create SDK", e)
} catch (e: Exception) {
Log.e("SDK", "Connection error", e)
}
Compruebe el estado del SDK
val sdk = MobileAgentSdk()
// Check if the SDK is destroyed.
if (sdk.isDestroyed()) {
Log.w("SDK", "The SDK has been destroyed.")
}
// Check if the SDK is valid.
sdk.checkNotDestroyed() // Throws an exception if destroyed.
Configuración de ProGuard
El SDK incluye el archivo proguard-rules.pro para conservar los métodos nativos. Por lo general, no se requiere configuración adicional.
Configuración manual:
# MobileAgentSDK
-keep class com.wuying.mobileagentsdk.** { *; }
-keepclassmembers class com.wuying.mobileagentsdk.MobileAgentSdk {
private native <methods>;
}
Dependencias
Dependencia en tiempo de ejecución:
dependencies {
// The only runtime dependency
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
}
El SDK excluye los frameworks de interfaz de usuario (AppCompat, Material) para mantenerse ligero.