LiteRT-LM Documentation
repository·main·Indexed 27 days ago
https://github.com/google-ai-edge/litert-lmA production-ready orchestration layer for running Large Language Models (LLMs) with LiteRT across Android, iOS, Web, Desktop, and IoT devices. It provides stable APIs for Python, Kotlin, and C++, with early previews for Swift and JavaScript. Key features include a CLI for local model execution, a builder for managing .litertlm files, and advanced constrained decoding support for tool calling, Regex, JSON Schema, and Lark grammar.
What's inside LiteRT-LM
- LiteRT-LM CLI is a command-line tool for LiteRT-LM, which serves as a production-ready orchestration layer for running Large Language Models (LLMs) with LiteRT. It is designed for high-performance, cross-platform execution.
Overview of LiteRT-LM Python API
mainLiteRT-LM provides Python bindings for the LiteRT-LM orchestration layer. It is designed for high-performance, cross-platform execution of Large Language Models (LLMs) using LiteRT. It serves as a production-ready layer for orchestrating LLM workloads on edge devices.Configure ModelDataProcessor and Prompt Templates
mainThe
ModelDataProcessorconverts genericMessageformats into theInputDatarequired by theSession. It is initialized using aDataProcessorConfig(often derived from model metadata).Prompt templates are implemented using Minja (a C++ Jinja implementation). The specific template used is typically provided by the model file metadata. To support a new model type, you must implement a custom
ModelDataProcessorto handle its specific data preprocessing and template requirements.Supported Language APIs and Status
mainLiteRT-LM provides APIs for various platforms. Choose the language based on your target environment and stability requirements:
Language Status Best For... Python ✅ Stable Prototyping & Scripting Kotlin ✅ Stable Android apps & JVM C++ ✅ Stable High-performance native Swift 🚀 Early Preview Native iOS & macOS JavaScript (web) 🚀 Early Preview Browser environments Flutter 🚀 Community Cross-platform mobile Use LiteRT-LM Builder to build and unpack LiteRT-LM files
mainLiteRT-LM Builder provides both a command-line tool and a Python API designed for building and unpacking LiteRT-LM files. This tool is essential for managing the lifecycle of LiteRT-LM model files.Explore LiteRT-LM API references
mainLiteRT-LM provides APIs for C++, Kotlin, and Python. Depending on your target platform, you can use the following documentation to integrate the library:
C++ API
- Conversation API: For managing conversational flows.
- Constrained Decoding: For controlling model output formats.
- Tool Use: For enabling models to interact with external tools.
- Advanced: ANTLR for Tool Use: For advanced tool use implementations using ANTLR.
Kotlin API
- Use the Kotlin API guide for Android or JVM-based development.
Python API
- Use the official Python API documentation for Python-based integration.
Understand the Tool Calling Flow in LiteRT-LM C++
mainTool calling in LiteRT-LM is managed by the
ModelDataProcessorimplementation specific to your model. The process follows these stages:- Tool Declarations: Formatted using
ModelDataProcessor::FormatTools. - Tool Call Parsing: Parsed by
ModelDataProcessor::ToMessage. - Formatting Calls and Responses: Tool calls and responses are formatted via
ModelDataProcessor::MessageToTemplateInput. Note that additional formatting may occur within the model's chat template.
- Tool Declarations: Formatted using
Build and run LiteRT-LM on Linux or MacOS
mainPrerequisites
- Linux:
clangmust be installed. - MacOS: Xcode command line tools must be installed (
xcode-select --install). - Git LFS: Run
git lfs pullto fetch prebuilt binaries.
Build and Run
- Set the model path:
export MODEL_PATH=<path to your .litertlm file> - Build the binary:
bazel build //runtime/engine:litert_lm_main - Run the binary:
bazel-bin/runtime/engine/litert_lm_main \ --backend=cpu \ --model_path=$MODEL_PATH
bazel build //runtime/engine:litert_lm_main bazel-bin/runtime/engine/litert_lm_main \ --backend=cpu \ --model_path=$MODEL_PATH- Linux:
Declare tools in C++ using Preface
mainTo make tools available to the model, you must declare them within a
Prefaceobject. This object is passed to theConversationConfig::Builderwhen creating aConversation.Tool declarations must be a JSON array where each tool is defined using a JSON schema containing the tool's
name,description, andparameters(includingtype,properties, andrequiredfields).constexpr absl::string_view kToolString = R"([ { "name": "get_weather", "description": "Returns the weather for a given location.", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The location to get the weather for." } }, "required": [ "location" ] } } ])"; JsonPreface preface; preface.tools = nlohmann::ordered_json::parse(kToolString); // Use preface in ConversationConfig::Builder ABSL_ASSIGN_OR_RETURN(auto conversation_config, ConversationConfig::Builder() .SetSessionConfig(session_config) .SetPreface(preface) .Build(*engine));Install litert-lm-builder
mainInstall the
litert-lm-builderpackage from PyPI. It is recommended to use a virtual environment.uv venv source .venv/bin/activate uv pip install litert-lm-builderUse ExternalConstraintConfig for custom C++ constraints
mainTo use your own custom
Constraintimplementations (e.g., a specialized C++ state machine), initialize yourConversationwithExternalConstraintConfig(). You can then pass astd::unique_ptr<Constraint>toSendMessageusingExternalConstraintArg.#include "runtime/conversation/conversation.h" ConversationConfig::Builder builder; builder.SetConstraintProviderConfig(ExternalConstraintConfig()); auto config = builder.Build(*engine).value();Send multimodal data (Image and Audio) via Conversation API
mainTo use multimodal capabilities, the
Enginemust be initialized with appropriate vision and audio backends (e.g.,litert::lm::Backend::GPUfor vision).When sending multimodal messages, the
contentfield in theMessageobject must be an array of objects rather than a single string. Each object in the array defines atype(e.g.,text,image, oraudio) and its corresponding data (e.g.,textorpath).// To use multimodality, the engine must be created with vision and audio // backend depending on the multimodality to be used auto engine_settings = EngineSettings::CreateDefault( model_assets, /*backend=*/litert::lm::Backend::CPU, /*vision_backend*/litert::lm::Backend::GPU, /*audio_backend*/litert::lm::Backend::CPU, ); // ... Create Engine and Conversation ... // Send message to the LLM with image data. absl::StatusOr<Message> model_message = (*conversation)->SendMessage( Message{ {"role", "user"}, {"content", { // Now content must be an array. {{"type", "text"}, {"text", "Describe the following image: "}}, {{"type", "image"}, {"path", "/file/path/to/image.jpg"}} }}, }); CHECK_OK(model_message); // Send message to the LLM with audio data. model_message = (*conversation)->SendMessage( Message{ {"role", "user"}, {"content", { // Now content must be an array. {{"type", "text"}, {"text", "Transcribe the audio: "}}, {{"type", "audio"}, {"path", "/file/path/to/audio.wav"}} }}, }); CHECK_OK(model_message);