litert-runtime
Что он делает
Этот скилл направляет добавление машинного обучения на устройстве в Android-приложение с моделью .tflite, используя API LiteRT CompiledModel. Он нужен Android-разработчикам, которые решают на телефоне задачи с изображениями, аудио или эмбеддингами.
Когда использовать
- ✓Когда вы хотите, чтобы модель классификации изображений или другая модель зрения работала внутри Android-приложения.
- ✓Когда нужно настроить LiteRT в Gradle, выбирая между средой Play services и встроенной средой.
- ✓Когда вы хотите запускать модель .tflite на GPU с откатом на CPU.
Ссылка на скилл
https://github.com/android/skills/blob/main/device-ai/litert/litert-runtime/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Добавь классификацию изображений с моделью .tflite в мое Android-приложение с LiteRT на GPU.”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
Скилл помогает выбрать среду выполнения, добавить зависимости Gradle и подготовить изображения для модели. Затем он показывает, как запускать модель на GPU и при необходимости переключаться на CPU.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с GitHub.
This skill provides step-by-step guidance for building an Android app that runs
a .tflite model with the LiteRT CompiledModel API
(com.google.ai.edge.litert:litert 2.x; source repository) on the CPU or
the GPU, with the runtime bundled in the APK or from Google Play services. Don't
use the deprecated org.tensorflow.lite.Interpreter API. For
open text language models using .litertlm files, suggest the litert-lm
skill.
Prerequisites
- A Kotlin Android project (
minSdkmust be24or higher, as declared by the LiteRT 2.3.0 AARs). - The runtime that Step 1 picks: the Google Play services runtime (
com.google.android.gms:play-services-litert, the default; see LiteRT in Google Play services), or the bundled runtime (implementation("com.google.ai.edge.litert:litert:2.3.0")andimplementation("com.google.ai.edge.litert:litert-gpu:2.3.0")from Google Maven). For the bundled runtime, from 2.3.0 the GPU accelerator is the second artifact: withlitertalone the app builds, andCompiledModel.createwithCompiledModel.Options(Accelerator.GPU)throwsLiteRtExceptionbecause the APK has no GPU accelerator library. WithCompiledModel.Options(Accelerator.GPU, Accelerator.CPU)it doesn't throw: the model runs on the CPU while the app reports the GPU, and only Logcat shows it (GPU accelerator could not be loaded and registered). No manifest entry is needed:litert-api, whichlitertdepends on, declares the OpenCL driver libraries (uses-native-library) in its own manifest. - A verified
.tflitemodel and its input contract (input dimensions, mean, standard deviation, channel order, and tensor layout). For models with a verified recipe, inspect the LiteRT model recipes.
Critical mandates
- Single-thread confinement : One single-thread executor or confined coroutine dispatcher must own the
CompiledModelinstance. Creation, inference, and closing must execute on that same background thread, never on the main thread. - Buffer lifecycle : Allocate
TensorBufferinstances once usingcreateInputBuffersandcreateOutputBuffers, reuse them across inferences, and close all input and output buffers before closing theCompiledModel. - Synchronous timing :
model.runenqueues work on the GPU and returns before GPU execution completes. Always measuremodel.runand output buffer readback (outputs[0].readFloat) together. - Warm-up and exception safety : Execute one warm-up inference inside the helper constructor's
initblock so first-run GPU shader compilation doesn't block the first user interaction, and callcloseincatchbefore rethrowing so neitherCompiledModelnorTensorBufferhandles leak if buffer allocation or warm-up throws. - Runtime choice : Before Step 1, you must read LiteRT in Google Play services and choose the runtime. Use the Google Play services runtime unless the app needs the NPU, custom operators, or a Support library class that this skill can't replace (such as
MetadataExtractor), or also targets devices without Google Play services. Never put both runtimes in the same build variant. - Migration : When the app already uses
org.tensorflow.litecode, you must read the "Migrating from legacy TFLite Interpreter" section in full before you edit any file. Migrated code must not import anyorg.tensorflow.liteclass (includingDataType), every legacy GPU choice (GpuDelegate, or the Support library'sModel.Device.GPU) becomesCompiledModel.Options(Accelerator.GPU, Accelerator.CPU), and an NNAPI choice maps to that same GPU option.
Detailed steps
Step 1: Configure Gradle and place the model file
Search the project for libs.versions.toml, gradle.properties,
app/build.gradle.kts, and any existing org.tensorflow.lite imports before
editing build files. Then pick the runtime:
- Google Play services runtime (default) : Use it unless one of the bundled runtime cases applies, also when the request doesn't name a runtime. You must read LiteRT in Google Play services now: its dependencies replace the ones in this step, and its
Environmentreplaces theenvironmentproperty of Step 2. Use version17.0.0exactly, and run `./gradlew assembleD
Частые вопросы
Какую среду выполнения использовать?
Скилл просит выбрать между средой Google Play services, которая используется по умолчанию, и встроенной средой.
Какая минимальная версия Android нужна?
Значение minSdk проекта должно быть 24 или выше, так как этого требуют библиотеки LiteRT.
Использует ли он старый TensorFlow Lite Interpreter?
Нет. Скилл советует не использовать этот устаревший API и применяет CompiledModel.
Подробности
Оригинальное описание автора
Configures and implements LiteRT (.tflite) on-device inference on Android in Kotlin using the CompiledModel API on CPU and GPU. Use this skill for any Android LiteRT or .tflite task, including Gradle setup, image classification or vision/audio/embedding helpers, TensorBuffer reuse, CPU memory optimization, Bitmap preprocessing, AndroidViewModel GPU-to-CPU fallback with warm-up on a single-thread dispatcher, LiteRT in Google Play services (play-services-litert), migrating from legacy org.tensorflow.lite.Interpreter, GpuDelegate, or play-services-tflite, and latency benchmarking. Don't use for r
repo: android/skills
Популярность
- Звёзды на GitHub
- 10k
- Место в рейтинге
- #11912
- Лицензия
- Apache-2.0
- Обновлён
- 29.10.2026
Комментарии
- …
Другие скиллы из этого репозитория
agp-9-upgrade
10kПомогает агенту обновить Android-приложение до Android Gradle Plugin 9 и разобрать его несовместимые изменения. Не подходит для мультиплатформенных проектов.
camerax
10kПомогает агенту создавать камеру в Android-приложениях с CameraX: запись видео, аппаратное управление, ML Kit и эффекты Media3.
android-for-cars-parked-apps
10kПомогает агенту адаптировать Android-приложение для видео, игр или браузера, чтобы оно работало как припаркованное приложение в Android Auto и Android Automotive.
appfunctions
10kПомогает агенту найти ключевые сценарии в Android-приложении и открыть их как AppFunctions, которые могут запускать ИИ-агенты и голосовые команды.
Похожие скиллы
android-clean-architecture
280kПомогает агенту эффективно организовывать Android-проекты. Структурирует код, чтобы его было проще поддерживать и развивать.
compose-multiplatform-patterns
280kПомогает агенту применять паттерны Compose Multiplatform и Jetpack Compose в KMP-проектах: состояние, навигация, темы и производительность.
dart-flutter-patterns
280kАгент пишет код для приложений на Dart и Flutter по современным паттернам, чтобы они были надёжными и управляемыми.