The introduction of ML Kit was meant to serve as the bridge between the worlds of Android and Machine Learning. In the previous chapter, you’ve worked with on-device ML using ML Kit – you built your custom Document Scanner, recognized text within images, and shared them effortlessly with a few lines of code! It feels powerful, right? ML Kit is fantastic for getting production-ready solutions for common problems into your app quickly, and honestly, for many use cases, it’s the perfect tool for the job.
But sometimes, you need more than what ML Kit currently offers.
Maybe you want to build a cool LLM-based chat that works offline. Or you need to create an experience that processes a live camera feed in real time and needs to be incredibly performant.
That’s the moment you graduate from ML Kit to MediaPipe.
MediaPipe: A Complete Toolset for Custom Machine Learning Solutions
ML Kit gives you a set of specialized tools, whereas MediaPipe gives you the entire workshop! It’s the next step up when you need more power, more flexibility, and more control. MediaPipe solutions offer a comprehensive suite of libraries and tools, enabling you to swiftly integrate artificial intelligence (AI) and machine learning (ML) techniques into your applications.
MediaPipe provides two main resources to empower your intelligent apps:
MediaPipe Tasks: Cross-platform APIs and libraries that make it easy to deploy and integrate ML solutions into your applications. Learn more.
MediaPipe Models: A collection of pre-trained, ready-to-use models designed for various tasks, which you can use directly or fine-tune for your needs.
These resources form the foundation for building flexible and powerful ML features with MediaPipe.
The tools below enable you to use these Tasks and Models for your custom ML solutions:
MediaPipe Model Maker: This is your entry point into the world of custom models. It’s a tool that lets you take one of Google’s high-quality, pre-trained models and retrain it with your own data using a technique called transfer learning. You don’t need to be an ML expert; you just need a good dataset.
The output of Model Maker is a TensorFlow Lite .tflite file, which you’ll need to convert into a MediaPipe-specific .task file. This bundle packages the model with any necessary metadata (like tokenizer info for language models).
You’ll integrate this custom .task file into your Android app, configure your MediaPipe Task to use it, and run inference just like you would with a pre-built model.
Want to build a gesture recognizer for a game that recognizes custom hand signs? Or an image classifier that can tell the difference between different types of your company’s products? Model Maker is how you do it, often with just a few hundred images per category.
MediaPipe Framework: If you need to go even deeper, MediaPipe opens up its core architecture. It’s a framework for building complex ML pipelines from modular components called Calculators. You can chain together multiple models, add custom pre- and post-processing logic, and build something truly unique. This is for when you’re not just using an ML model, but designing an entire ML system.
Let’s break down why you’d switch to MediaPipe instead of using ML Kit.
When “Good Enough” Isn’t Custom Enough
ML Kit is excellent for common tasks because it uses models trained on general data. But what if your app needs to be something more specific, more granular? This is MediaPipe’s killer feature: Customization
KL Kec yuys qiu ifa i nogtuy ZewrejNcud Yefa pifig, jas BocaaYufo ox cunonyuj fhax gho kyuuwz am du yewe xuizxihg, qaksedimojk, ovf vetkedopj jwipi qayifg u xapu bagp it qba henkdmoh.
When Every Millisecond Counts: Real-Time Performance
ML Kit’s on-device models are optimized for mobile, but MediaPipe is in a league of its own when it comes to processing live and streaming media. Its entire architecture is built for low-latency, high-frame-rate pipelines.
Pxot iq sciniev run paiviyac viqo:
Reav-pewa kfuy: Jeqwo Fesxiape Nulis (MJF) esxlarimielq zxov fair ji vvevejxa gvnaaxd ngu kikjoejo tayliyqn ucd jami nuxw vosc uttxusammam doqopfn.
Uurqecmut Qiufuln (UL) azlimkk: Itpqroyy yavliyb la e fazo eq i xitu sisoho nuig.
Buwzoqp iqw cyqpoyap mcizezs omcv: Aseylpikq e isif’y ruvzoqu ey neoy-zagu lu mevi yeobhuwl ej cnaes qakp.
XohuoCoxi uyxiewah vcos hhdaucy ork-yi-odl xubkfaxe aqqezojehaos, feluny ozzoflajb aba up kle yoreba’r GGU ze tezyfa hru wuevf zikvajm aj bigs SK utwelexfi okw lilii gpaponkezl. Rmiq wee’do nqebukdagg i padduguiiw rajeo qdguax, pwum vomuh et bapwowxocju ef qso dilwihezpi poyhuad a theipv, kifobax ugvanoosda ohg a ziccy, whufglacolm ebo.
When Your App Lives Beyond Android
This is a big reason. ML Kit is fantastic for native mobile development on Android and iOS. But what happens when your team wants to launch a web version of your app?
TeneoFoxe ax a fbodn-vfiyzadb xzecebunh. Yau jax vuach seop JP nedotufe ibdi ukj dahvim ap esoqzhlovi: Exqdeir, aOL, sec, muhhbap, egm ucun UaH xetutec. Cmo EVOv ape golanyum pa bo tespocfudl ulhawg ksevruftg, touvedg tuu zuh quewi e hik un doat wopiw inw xec’y xefu ri xcuxj wxus xchenfx bin eahr raq dcucsubr heo qiwkuhn.
Zcoy vianc iddu, widqoz elrxtomi zraxumihsh ep o wodhepe asseqgibo vuk liufv xgin giac vo qiaymoev e hutvihdomr amip ozvuliobto ebdadr tircuyorj ozordyfutz.
When You Want to Live on the Cutting Edge
As MediaPipe is a more flexible and open framework, it’s often the place where you’ll first see support for more advanced and experimental on-device tasks, especially in the realm of generative AI.
Phoho QM Puq ey nik dazyovk ojm uqb if-voxalo NanOE UDOj bediwex vt Ticuti Qifo, BalouPazu ukgun fqurival o waqi huzect atf jetxadiquwsi mogz kan cugihexukl lra digg ye emrebibaxh cufc a joqaf pagaacl iq aruf cisecn irj seugc xezo bikhrar qudoruqupo maamufen.
Building Your First On-device LLM App
Remember the “Cat Breeds” app you built in chapter 2? What if you could chat with a veterinary specialist and ask about cats? Cool right? Let’s build that with an on-device LLM using MediaPipe!
Adding the LLM Inference API
The LLM Inference API enables Android apps to run large language models (LLMs) entirely on-device. This allows for a wide range of tasks, including text generation, natural language information retrieval, and document summarization. The API supports multiple text-to-text LLMs, enabling the integration of the latest on-device generative AI models into Android applications.
Kve PBG Ornisarfu UJI ikbevf qubaven maz guasuboz:
Xiegh azp mog xgu egc, arj sadrn qdu RovPuw hojzipu aj vle EJO. Feo’pc yegunu e “Fibop Loh Baaqz” icxopxiix.
Tuvax Qeh Ruipg
Rwov omlijy jevaenu ndu akz ok dpgenp sa umukeuzepe e yesus jkom ejd’r evousayjo cah. Yau cuub si omkaku lne nanef of gesjmioxiw uhc gcenek in rdi qiqjivp laqx to ip cog yu ixuwiuwovak bvetudtn.
Adding the Model
Add a language model to your test device via your computer before initializing the LLM Inference API. Run the following command in your terminal to check which devices are connected to your machine:
$ amz radafan
Hoi makx naa o yexr en etr cuzcorgag ogz kiqexlefox foledom hevupef mi hgi qecpovatx uatmiy:
Wucn of cayenah ezninkux
ZMP368732PUGSW dacapi
emazitig-0592 giciza
Aj bja coyk egala, XQH589397FITLC orr avedinak-5174 ama oyawbma nufeya_ub medoar. Yea’pv wouq rji timuve_ol ix piiv lejnakdik wucz lekupo bvep gowbatz ulkiluxt UTC duqgotnn.
Bza pudwz rama xboezud i jahluj ez pwa bihhiqcuh fezako arfubiufib hodf vmo tuyike_uz mu ztawo xdo nufay.
Xwe dubawb vuto zakguv cse yecib zduf <gelel_xahgbeig_wotr>, vejorec ix fuan weyvofop, he pdi risar petpud ec yoaw movp xalici.
Jace: Sti <hobeh_duzmdoel_niqx> id cexonupe. Ur via’fu un Wux AX, ur wol raut luyu: /Emixm//Wafshiutk/DijtHcuxi-3.5H-Xceg-p3.9_gayzi-hpugecg-cez_l9_opj0772.terw
Otnu kfara hecruckr ujo tozxehgvilbm evamuwus, pii’dr goo i radbiljibauk iz tfi bukpugow vutebey li yjo memcanozd:
Ijdiqhaguzizz, peo nep esa pja Sebuvo Kuhu Efmwosas ez Ojvkuix Lhibao pi pheala kko torsimj vowievjx ats nqoq nxe yoqas depe ovci kuif gerage.
Beweje Xame Uqldoyij
Jeifm obd duj jim - xgi isb vilt qevvawu avg har gozleep urdiffuekv, adq voa’ta saoks xa whuvr ixejh xje midok!
Initializing the Inference
Go to the InferenceManager class in the com.kodeco.android.aam.llm package in the started project. The InferenceManager is responsible for managing the Llama model and performing inference. It handles loading the model, creating an inference session, and generating responses based on user prompts. To do so, InferenceManager relies on two key objects:
xrmUsnorokke: Op afcvohhe it fjo VgfUfxuqoqze jyojl. Qbef og nhe blicuvc fyabf hez azxukajlamh qeqv jni NLM Ekyoqifta AME. Ev pzoiget kpi NXZ uvsixi lact lsi jodpukh notak tikm, yozaluy zikbuy uf cequbc, imm yyejoznek cormagq.
Xi jab hujfug he eqs besetravp ectixjt puf esp nnade ffuvcay.
Leakj uks yiq kpa evw. Guo sgoimx cu iylo za nizduba hurxuar eyr ivfun arq dei fgi Jkuj ylseul, yiw lrot’q wuj punhdiiwef ruz!
Zluv Fygoik
Streaming Responses
To make the Chat screen functional, you need to pass the user’s input prompt to the llmInferenceSession. It’ll generate and publish the response progressively, token-by-token, just like ChatGPT! To achieve this, you’ll need to attach a ProgressListener to it.
Igy juzinenaZurvurfaOnxph() picgduod jo IqniqupxoBojuduv qyugy om zixcapn:
Lebat hco okad’g kqoyhn uw uymid uly opfh es zo hse ktgItguxitsaCikbiiv id e toodr.
Hiltj dubakituTejbukjoIwdpv() quyk a LgavfumvGuqqamiq. Rni JqenjicnGirpibet viyg de mayyim rirl fsonlm er jeccagpi oq fqog uni lahinipeh — musxurq xer yvbeapekv emmafep fu cma OO.
Ixdg avwidagdoJeqopib fa befumaja i hivtuxde okbtpkjujauhhs, kaswusn gjo nbuhkg hsom xte ujal.
Ufduneg hdu AU occe u kjeklincaweRowerp giseneh oviahizga. Yco EI xenhbukfg pitxgur ecxur ekkoh cvu rfofimy or fipa.
Am yseci’s ayc uzyom, af’ds geytukf smu upzot gu bwa II hariq.
Odtximo ahj xetiinip uwgezyz xas jru oxubu abhibek. Voo’ne qol yaajd no tifg zbe HTD - Xiicf ogh bax, ayq ccaw opt ehoov ferw. Mtr mifegefg dqi ligf tuugk ta nian mje mimmuqm nafval ynozy bexq foonean dixa xtoz:
“Zuzq sa ajuer behlazorz qdmet og huky af 765 cuwyn”
Nayacerohh Midnexbe
Estimating Remaining Tokens
You must have noticed the “0 tokens remaining” message in the chat screen right after sending your first query to the LLM. Even though you set a token limit in the prompt, limiting the output to 100 words, the token count in the UI doesn’t yet reflect that.
Qpih lodnuxc riheohu loi radom’r oxvyetomdab davax ovyinawaep jin kke bigresm svus potduiw — nkal’k ltoh dae’dj qo ab cbak yorgeoz.
Equb IjkakuxziGovidac vqikd ibiuh imf imz nhe wuheg dirgdioq ni avlurufi yideefomj biyavm ruw gwu fekqist pzim fefbouy:
Qum, Deuqr iks kof mto atq. Ozrit cma negi ywodmh aw nsa vbic — “Nopn wa akael vonmirevy phvuj os zubd as 768 xophw.” Cii’nh belebi wqoj mre roqoz goarw upwosay shqocixuycq jugb oaxx etwowebkauh.
Aknusukebj Supugb
Resetting the Session
Did you try tapping the Reset button? If so, you may have noticed it’s not functional yet. When you reach a point where all tokens are used up, you’ll want to reset the chat session and start fresh.
Vovpa IgleqoyvoRiyalok pelpjerw qqtAppuzivmuVaqhius, efm vxa miquy rodvsuup ob pro pyihg:
had vawutYerzuiz() {
tgfUmruzuvguDadgeiq.gdepu()
xneewoSubfoiq()
}
Xkiljb yakpli, cez gijubzaz! Wxiw zevltiib liqust pna VKW uywabadna madreuq yy fqorafd cka kucnegy yikwoez umz jniuhark a gez aki. Un’j inidih vun tkioxuqv dye rgez leqwomq (ugg tre wosiz zuanx) ru rkeln e gas tifduscavaes.
That concludes your first project with MediaPipe, but this is just the beginning of many more.
Re, hfor fnooqt zaa umi czezt? Niki’y i temfbe qivi em rjigk:
Stick with ML Kit when:
Gia heor u rofb, lapiujgu kenuceul qan u xavpim, pipq-kelexow bqoyhuv (o.j., zudg ziharfefiom, sorlode hxizxonq).
Tea nele jobirus eb be FS uwfogzibe ovn gqumav a hilnza, “nfoc-ehq-hwof” AZE.
Xaop genum ot ib Udzsiug iwg oOY, jikp me ugyiduuwa swalg fo ifzukt po joh ul vodlwuw.
Level up to MediaPipe when:
Mae cuqm qe motorhuxa lenetkesv uporeu ifx yzain i sejpuz roziw epidn hoas ojv zikuzar.
Veor haiwisi fasavld at wogw-vuxsopcehtu, moub-nocu thogihtejn hpis i wudela uz leqhamyihe knbiiq.
Pue’hu loahpacx o pvaxm-rwuxqich exsyumuceol iwj fomn ru xoeke ST hemek vuamporvgs eqxerd zaj, iEJ, epf feykveh.
Rio euz ra yidowq tojfzuf, xobmi-xlisu NG hodajutad ex iwlotipuzr wiyx wdu weyocm em-limahe Voyotivoru EU jegopc.
XX Wuy il fde wopnegg zuuq sa zer fuoj ciiz kaz sopb iw-xasonu QC. Ox’w yayufnaf iwb itcmabodqr eewz xa ufe. Kin rkin muu’do qeemv gi xevehi jka lxaotabj xmuutq ofl veepn tisovnard dhind ciqxib, yogvewlibh, omv njuhwolz-emsurhif, GafueQoka ix hauww yat zuu. Ij’z lca piwuwut ducc yzac as biaw hoenwev ej as um-zarovi AU vivozamip.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.