LiteRT-LM Provider Layer — On-Device LLM Integration Architecture
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 |
|---|---|---|
|
|
Implements |
|
|
Real-time token and thought channel streaming events |
— |
|
Seam over SDK |
— |
|
Production |
— |
|
Reconciles domain |
— |
|
Parses tool call markup into |
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 toSessionReconciler. -
Eager Initialization: Exposes
initialize(), which triggers underlyingseam.initialize()to load native C++ libraries and initialize the LiteRT-LMEnginewhen entering a chat screen. -
Real-time Delta Streaming: Emits
AgentEvent.TextDeltaandAgentEvent.ThinkingDeltadirectly into the returningFlow<AgentEvent>as tokens arrive from the engine.
2. ConversationSeam & DefaultConversationSeam
-
Seam Abstraction:
ConversationSeamabstracts LiteRT-LM SDK engine lifecycle and streaming calls. -
Eager Engine Loading:
DefaultConversationSeaminitializes LiteRT-LM’s nativeEngineuponinitialize(), 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 coroutineChannel<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.ToolCallStartedfor detected tool invocations without executing them (tool execution is owned by Book’s domainAgentLoop). '''
Streaming Pipeline Sequence
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 -> {}
}
}
Related Documentation
-
Agent Loop Architecture — Execution engine details, tool calling, and context compaction
-
Gallery App Integration — Complete guide on how the Gallery Android app embeds Book’s
AgentLoop -
Streaming Sequence Diagram — PlantUML sequence diagram
-
Gallery Bridge Architecture Diagram — Class component diagram