Zero Labs
Industry News / AI

I Crammed RAG, a Vector Database, and a Gemma LLM into a Mobile App. Here’s What Happened.

Source · Towards AI By Ahmed Afridee

From the publisher’s feed, collected in the ZeroLabs newsroom.

No cloud. No API keys. No excuses.The full on-device pipeline — from writing a note to getting an answer. Nothing in this flow touches a network after the initial model download.It started with a paranoid thought.I was taking meeting notes on my phone — project decisions, research fragments, half-formed ideas — and I wanted to ask a question across all of them. What did I decide about the API design last month? What did that article say about PostgreSQL indexing?The obvious answer was to pipe everything into one of the big AI APIs. But then I thought: every note I’ve ever written would be traveling to someone else’s server. My research. My half-baked ideas. My meeting minutes.I didn’t like that.So I did what any reasonable developer does when they don’t like the obvious answer: I spent considerably more time building the unreasonable one.The Constraint That Changed EverythingI gave myself one rule: after the initial model download, the app works with the network radio completely off.No cloud inference. No embeddings API. No telemetry. The AI runs on the phone. The vectors live in the phone’s storage. The only thing that ever leaves the device is nothing.That one constraint rippled through every technical decision that followed.“How Hard Could It Be?”(Famous last words.)The stack I landed on looks simple on paper:Layer Technology LLM inference flutter_gemma — Gemma 4 E4B IT (~4.3 GB) Embeddings flutter_gemma — EmbeddingGemma (768-dim vectors) Vector store ObjectBox with HNSW index Hybrid retrieval Dense cosine + BM25 + MMR re-ranking State / routing GetX Markdown chat UI gpt_markdownTwo Gemma models. A local vector database. Hybrid retrieval with re-ranking. All inside a Flutter app. On a phone.Reader, it was hard.The First BootThe first time you open Smart Notes, you’re greeted with a setup screen and two progress bars slowly filling up.The first bar is downloading Gemma 4 E4B IT — a ~4.3 GB LiteRT bundle from HuggingFace. This is the brain: the generative model that reads your notes and writes an answer.The second bar is downloading EmbeddingGemma — a smaller model that does one thing exceptionally well: turning text into numbers. Specifically, 768-dimensional float vectors that encode meaning rather than spelling.Both models download once. After that, the app doesn’t care whether you’re on a plane, in a basement, or in a country with aggressive data laws. It just works.Every Note You Save Goes Through a Four-Step PipelineThis is where it gets interesting.When you hit save on a note, the app doesn’t just write text to disk. It does something more obsessive.Step 1 — Chunk. The note is split into overlapping segments of roughly 480 tokens. The chunker tries to break on sentence boundaries first. When the text is too dense for that, it falls back to a sliding window with a 32-word overlap — so no idea gets guillotined mid-thought.Step 2 — Embed. Each chunk gets passed through EmbeddingGemma, which returns a 768-dimensional vector. That vector is a coordinate in meaning-space. Notes about databases cluster near each other. Notes about your weekend do not.Step 3 — Prepend context. Before embedding, the note’s title and timestamps are prepended to the chunk. “Project kickoff — meeting notes — 2026–05–01: the team decided to…” This grounds the vector. Without it, similar-sounding chunks from completely different contexts bleed into each other during retrieval.Step 4 — Store. The chunk text, its vector, and a reference back to the parent note go into ObjectBox, which maintains an HNSW index on the vector column. Approximate nearest-neighbour search in sub-millisecond time, even across thousands of chunks.All of this happens silently, in the background, while you move on with your life.Asking a Question Feels Like Magic (The Machinery Is Anything But)“What did I decide about the API design last month?”You type the question. The app takes a breath. An answer appears, with citations.Here’s what happened in that breath:The question gets embedded using the same EmbeddingGemma model, producing a vector that represents the intent of the question, not just the keywords.Dense search finds the top candidates in ObjectBox by cosine similarity — chunks whose meaning is closest to the question’s meaning.BM25 re-ranks those candidates for exact keyword matches. This matters more than you’d think. Dense vectors are brilliant at semantics but they tend to blur over proper names, version numbers, CLI flags, and code identifiers. BM25 doesn’t blur. It counts.A weighted-sum fusion merges the two lists — each score is min-max normalized, then combined as 0.7 × dense + 0.3 × BM25 — then Maximal Marginal Relevance diversifies the final set. MMR is the unsung hero of this whole pipeline. Without it, if five chunks all say "use PostgreSQL for indexing," the LLM sees the same advice five times. With MMR (lambda: 0.7 — 70% relevance, 30% diversity), the fifth slot goes to something genuinely different. The LLM receives context that's wide, not just confident.The prompt is assembled with token-aware trimming. Gemma 4’s context window is 2,048 tokens. The system instruction and template reserve 768. Whatever is left gets divided among the retrieved excerpts — no silent truncation, no surprises.Gemma generates the answer. Streaming. On-device. The response renders in Markdown, with [#1], [#2] citation labels pointing back to the exact excerpts it used.The Feature That Surprised Me MostI almost didn’t build the graph view. I thought it would be a gimmick.I was wrong.Every note in the library has a mean vector — the average of all its chunks’ embeddings. When you open the graph view, the app computes pairwise cosine similarities across all your notes and draws an edge between any two that exceed a similarity threshold of 0.35.The result is a force-directed graph. No tags. No folders. No manual linking.A meeting note about “database schema” floats toward an old research note about “PostgreSQL indexing” that you had completely forgotten. The connection was always there in the content. The graph just makes it visible.I spent twenty minutes the first time I ran it just staring at the clusters.(For large libraries — 500+ notes — only the top hubs by degree are rendered to keep the layout fast. Tap any node to jump straight to the editor.)The Parts That Humbled MeLet me be honest about what fought back.The token budget. A fixed 2,048-token context window is not forgiving. Build the prompt too long and the inference call throws an error. Too short and the answer is shallow. I ended up writing a character-to-token estimator (4 chars ≈ 1 token for Latin text, conservative) and trimming excerpts dynamically. It took several embarrassing failures before the arithmetic felt right.The similarity floor. Setting kGraphSimilarityFloor too low and the graph becomes a hairball. Too high and every note is an island. The 0.35 threshold works well for EmbeddingGemma's particular geometry — but this is model-specific. If you swap the embedder, budget time to re-tune it.The gated model. EmbeddingGemma requires accepting Google’s license on HuggingFace before you can download it. The app surfaces a clear warning if the token is missing and includes a retry button. It’s not complicated, but it’s a real friction point for first-time setup.ObjectBox codegen. The vector entities use generated code (objectbox.g.dart). Clone the repo, change a model, and forget to run build_runner — the build fails cryptically. It's in the README now. It should have been in the README from the start.Try It YourselfThe project uses FVM to pin the Flutter SDK. After cloning:fvm installfvm flutter pub getcp config.json.example config.json# add your hf_... token to config.jsonfvm flutter run --dart-define-from-file=config.jsonThe HuggingFace token is passed at compile time via --dart-define-from-file. It is forwarded as a Bearer credential to HuggingFace's download API to pull the gated EmbeddingGemma model — that's its only network use.https://github.com/Afridee/smart_notesWhere I Want to Take ThisThe architecture is model-agnostic — any flutter_gemma-compatible LiteRT bundle can slot in where Gemma 4 sits today. As on-device models get smaller and smarter, the app gets better for free.The graph currently rebuilds on open, which works fine up to a few hundred notes but will need an event-driven approach for larger libraries. Export and import — notes plus vectors as a portable bundle — is the other feature I keep thinking about.The Bigger PointOn-device LLMs are past the proof-of-concept stage.The models are good enough to be genuinely useful. The toolchain — LiteRT, flutter_gemma, ObjectBox — is stable enough to ship. And the privacy guarantee is real, not a marketing line: the inference happens on the processor in your hand, and the data never leaves unless you choose to move it.That paranoid thought I had about my notes traveling to someone else’s server? It turned out to be a useful constraint. The best features in this app — the hybrid retrieval pipeline, the semantic graph — exist specifically because I couldn’t outsource the hard parts to a cloud API.Sometimes the unreasonable path is the interesting one.If you’re building anything in the on-device AI space, I’d genuinely love to hear about it in the comments.I Crammed RAG, a Vector Database, and a Gemma LLM into a Mobile App. Here’s What Happened. was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.