Audience: Android developers wanting to embed Book’s domain AgentLoop in custom Compose/Hilt applications, or developers working on the Google AI Edge Gallery application (android/gallery/app).


Overview

The Google AI Edge Gallery application (android/gallery/app) uses Book’s domain AgentLoop and on-device LiteRT-LM provider (:core:providers:litertlm) as its core multi-turn agentic execution engine.

By routing chat and tool execution through Book’s Clean Architecture layer, Gallery achieves:

  • On-Device Agentic Tool Loop: Support for local device tools (Skills, Android Intent actions, JavaScript evaluation) and remote Model Context Protocol (MCP) tools.

  • Real-Time Token Streaming: Immediate UI token updates as LiteRT-LM generates text on device.

  • Eager Model Warmup: Zero initial prompt latency by initializing the native LiteRT-LM engine when the chat screen is opened. '''

Component Architecture

The integration consists of four main layers:

[ LlmChatViewModel ]  (Compose UI / Hilt ViewModel)
        │
        ▼
[ BookAgentRuntimeExecutor ]  (Adapter implementing Gallery's AgentRuntimeExecutor)
        │
        ▼
[ DefaultGalleryAgentBridge ]  (Bridge in :android:gallery-bridge)
        │
        ▼
[ Book AgentLoop ]  (Domain execution ring in :core:domain)
        │
        ▼
[ LitertLmAgent ]  (On-device provider in :core:providers:litertlm)
Diagram

Key Integration Components

1. BookAgentRuntimeExecutor

Located at com.google.ai.edge.gallery.agent.BookAgentRuntimeExecutor:

  • Implements Gallery’s AgentRuntimeExecutor interface.

  • Registered as a @Singleton Hilt binding (@AiChatExecutor).

  • Initialization Lifecycle:

override suspend fun initialize(context: Context, config: AgentRuntimeConfig, onDone: (String) -> Unit) {
    val agent = LitertLmAgent(agentConfig)
    agent.initialize() // Eagerly initializes native LiteRT-LM engine
    val bridge = DefaultGalleryAgentBridge(agent = agent)
    bridge.createLoop()
    activeBridge.value = bridge
    config.model.markInitialized(bridge) // Registers instance with ModelManagerViewModel
    onDone("")
}
  • Streaming Execution: Delegates executeStream() to bridge.runStream(). Returns a safe Flow with AgentEvent.Error if uninitialized, preventing unhandled background coroutine exceptions.

2. DefaultGalleryAgentBridge

Located in :android:gallery-bridge (us.nineworlds.book.android.gallerybridge.DefaultGalleryAgentBridge):

  • Bridges Gallery’s Hilt dependency graph with Book’s domain AgentLoop.

  • Owns DefaultToolRegistry and dynamically mirrors Gallery ToolDefinition`s (MCP tools, Skills, Intent runners) into Book domain `Tool instances.

  • Translates AgentLoop domain events into GalleryAgentBridge.TranslatedEvent`s (`LoopInitiated, StreamToken, ToolStarted, ToolFinished, LoopTerminated).

3. AgentTools & Safe Initialization

Located at com.google.ai.edge.gallery.customtasks.agentchat.AgentTools:

  • Provides local Android tools: LoadSkillTool, RunMcpTool, RunJsTool, and RunIntentTool.

  • Safely handles asynchronous Compose lifecycle binding: exposes hasMcpManagerViewModel and guards ::property.isInitialized so background model setup succeeds even before Compose UI passes mcpManagerViewModel or context. '''

Step-by-Step Developer Guide: Embedding AgentLoop in an Android App

Follow these steps to embed Book’s AgentLoop in your own Android application.

Step 1: Add Project Dependencies

Include :core:domain, :core:providers:litertlm, and :android:gallery-bridge in your app’s build.gradle.kts:

dependencies {
    implementation(project(":core:domain"))
    implementation(project(":core:providers:litertlm"))
    implementation(project(":android:gallery-bridge"))
}

Step 2: Implement an Executor / Bridge Adapter

Create an adapter class to coordinate model initialization and loop execution:

class AppAgentExecutor @Inject constructor() {
    private var activeBridge: DefaultGalleryAgentBridge? = null

    suspend fun initializeModel(modelPath: String, backend: LitertLmBackend) {
        val config = LitertLmAgentConfig(
            modelPath = modelPath.toPath(),
            backendType = backend,
        )
        val agent = LitertLmAgent(config)
        agent.initialize() // Pre-load native engine

        val bridge = DefaultGalleryAgentBridge(agent = agent)
        bridge.createLoop()

        // Register custom local tools
        bridge.registerTool(MyCustomAndroidTool())

        activeBridge = bridge
    }

    fun streamPrompt(prompt: String): Flow<GalleryAgentBridge.TranslatedEvent> {
        val bridge = checkNotNull(activeBridge) { "Model not initialized" }
        val loop = bridge.currentLoop ?: bridge.createLoop()
        return bridge.runStream(loop, prompt)
    }
}

Step 3: Trigger Eager Initialization in ViewModel

Initialize the model in your ViewModel when navigating to the chat screen:

@HiltViewModel
class ChatViewModel @Inject constructor(
    private val executor: AppAgentExecutor,
) : ViewModel() {

  fun onScreenOpened(modelPath: String) {
      viewModelScope.launch(Dispatchers.Default) {
          executor.initializeModel(modelPath, LitertLmBackend.GPU)
      }
  }

  fun sendPrompt(userQuery: String) {
      viewModelScope.launch(Dispatchers.Default) {
          executor.streamPrompt(userQuery).collect { event ->
              when (event) {
                  is GalleryAgentBridge.TranslatedEvent.StreamToken -> {
                      updateUiToken(event.token)
                  }
                  is GalleryAgentBridge.TranslatedEvent.ToolStarted -> {
                      showToolIndicator(event.toolName)
                  }
                  is GalleryAgentBridge.TranslatedEvent.LoopTerminated -> {
                      onTurnComplete(event.finalResponse)
                  }
                  else -> {}
              }
          }
      }
  }
}

Step 4: Collect Real-Time Tokens in Jetpack Compose

Render streaming responses smoothly in Jetpack Compose:

@Composable
fun ChatScreen(viewModel: ChatViewModel = hiltViewModel()) {
    val uiState by viewModel.uiState.collectAsState()

    LaunchedEffect(Unit) {
        viewModel.onScreenOpened("/sdcard/models/gemma-3n.task")
    }

    Column {
        LazyColumn {
            items(uiState.messages) { message ->
                TextMessageItem(text = message.text)
            }
        }
        MessageInputField(onSend = { text -> viewModel.sendPrompt(text) })
    }
}