Audience: Developers and AI agents embedding on-device LiteRT-LM models in Android/KMP applications, or modifying Book’s LiteRT-LM provider (core/providers/litertlm).


Overview

The :core:providers:litertlm module provides an on-device Kotlin Multiplatform adapter for Google’s LiteRT-LM SDK (formerly MediaPipe LLM Inference API). It implements Book’s core :domain Agent interface, allowing on-device models (such as Gemma 2B/7B, Gemma 3n, Phi-3, or Llama-3) to drive Book’s AgentLoop with real-time token streaming and local tool orchestration.


Module Position & Architecture

:core:providers:litertlm is an outer-ring adapter in Clean Architecture. It depends only on :core:domain and wraps the platform-specific LiteRT-LM C++/JNI SDK (com.google.ai.edge.litertlm).

:core:domain  <---  :core:providers:litertlm  <---  :android:gallery:app / :jvm:cli
 (Agent API)          (LitertLmAgent)                  (UI / Loop Adapters)

Domain Contract Implementation

Domain Interface LiteRT-LM Provider Class Responsibility

Agent

LitertLmAgent

Implements nextTurn(), delegates streaming to ConversationSeam

AgentEvent

AgentEvent.TextDelta and ThinkingDelta

Real-time token and thought channel streaming events

—

ConversationSeam

Seam over SDK Conversation & Engine to keep logic JVM-testable

—

DefaultConversationSeam

Production androidMain wiring LiteRT-LM SDK Engine & sendMessageAsync

—

SessionReconciler

Reconciles domain Message history with stateful SDK conversations

—

ToolCallParser

Parses tool call markup into AssistantContent.ToolCall


Core Components

1. LitertLmAgent

The primary entry point implementing us.nineworlds.book.domain.Agent:

  • Stateless-per-turn API: Accepts domain conversation history (List<Message>) and active tools (List<Tool>), delegating state reconciliation to SessionReconciler.

  • Eager Initialization: Exposes initialize(), which triggers underlying seam.initialize() to load native C++ libraries and initialize the LiteRT-LM Engine when entering a chat screen.

  • Real-time Delta Streaming: Emits AgentEvent.TextDelta and AgentEvent.ThinkingDelta directly into the returning Flow<AgentEvent> as tokens arrive from the engine.

2. ConversationSeam & DefaultConversationSeam

  • Seam Abstraction: ConversationSeam abstracts LiteRT-LM SDK engine lifecycle and streaming calls.

  • Eager Engine Loading: DefaultConversationSeam initializes LiteRT-LM’s native Engine upon initialize(), avoiding deferred startup latency when the first prompt is sent.

  • Real-time Token Bridge: Uses LiteRT-LM’s async sendMessageAsync(contents, callback) paired with a coroutine Channel<Pair<String?, String?>>:

val channel = Channel<Pair<String?, String?>>(Channel.UNLIMITED)
val callback = object : MessageCallback {
    override fun onMessage(message: SdkMessage) {
        channel.trySend(message.toString().ifEmpty { null } to message.channels["thought"])
    }
    override fun onDone() { channel.close() }
    override fun onError(throwable: Throwable) { channel.close(throwable) }
}
conv.sendMessageAsync(SdkContents.of(emptyList()), callback)
for ((text, thought) in channel) {
    onDelta(text, thought)
}

3. ToolCallParser & ToolCallMarkers

Supports multi-turn tool calling across diverse model architectures:

  • Recognizes Gemma-style call:toolName{arg="val"} calls as well as standard <|tool_call> / <tool_call> XML markers.

  • Normalizes tool name typos or mangled names against the active ToolRegistry.

  • Emits AgentEvent.ToolCallStarted for detected tool invocations without executing them (tool execution is owned by Book’s domain AgentLoop). '''

Streaming Pipeline Sequence

Diagram
LiteRT-LM SDK (MessageCallback)
       │ (onMessage token delta)
       ▼
DefaultConversationSeam (Channel trySend)
       │ (onDelta suspend call)
       ▼
LitertLmAgent (Flow emit)
       │ (AgentEvent.TextDelta)
       ▼
Book AgentLoop -> Gallery Bridge -> UI ViewModel

Embedding LitertLmAgent in Custom Applications

To embed LitertLmAgent in a Kotlin Multiplatform or Android application:

Step 1: Configure LitertLmAgentConfig

val agentConfig = LitertLmAgentConfig(
    modelPath = "/path/to/gemma-3n.task".toPath(),
    backendType = LitertLmBackend.GPU, // CPU, GPU, or NPU
    maxTokens = 2048,
    enableThinking = true,
)
val agent = LitertLmAgent(agentConfig)

Step 2: Initialize On Screen Entry

Call agent.initialize() during screen or ViewModel initialization to eagerly load native libraries and compile the LiteRT-LM engine:

// Eagerly loads model into memory before user sends first prompt
agent.initialize()

Step 3: Run via AgentLoop

Pass agent to Book’s AgentLoop alongside local tools:

val loop = AgentLoop(
    agent = agent,
    toolRegistry = DefaultToolRegistry(setOf(myLocalTool, myMcpTool)),
)

// Stream agent response and tool executions
loop.events.collect { event ->
    when (event) {
        is AgentLoopEvent.AgentStreamDelta -> print(event.delta)
        is AgentLoopEvent.ToolExecutionStarted -> println("\nExecuting tool: ${event.toolName}...")
        is AgentLoopEvent.LoopTerminated -> println("\nTurn complete.")
        else -> {}
    }
}