AI in apps interview questions
92 questions from the AI in apps lessons. Open a question to see the junior, mid and senior answers. Each one links to the lesson that explains it.
AI foundations for app developers
What is a token in an LLM, and how does the model generate text?
- Junior
- A token is a chunk of text, usually a word or a sub-word. The model reads the tokens so far, scores every token in its vocabulary, and picks the next one. It repeats this loop until it produces a stop token or hits a length limit.
- Mid
- Each step is a forward pass through the transformer. The input is a 1-D tensor of token IDs; the output is a probability distribution over the vocabulary. A sampling step (controlled by temperature and top-p) picks one token, which is appended to the context. Because generation is sequential, longer outputs take longer.
- Senior
- In production you also manage the context window: you must track how many tokens the prompt and history consume, because exceeding the limit causes errors or lost history. See [chat state, history and context limits](/learn/ai/chat-state-history-and-context-limits). You set a maximum output token limit to bound cost and latency. For streaming UIs you render each token as it arrives, so the user sees text appear word by word.
What does temperature do, and when would you set it to zero?
- Junior
- Temperature controls randomness. Low temperature makes the model pick the most likely token every time. High temperature makes it pick rarer tokens more often. Setting it to zero means greedy decoding: always pick the top token.
- Mid
- Temperature divides the logits before the softmax. As it approaches zero, nearly all probability goes to the top token, so output becomes close to deterministic. At high values the distribution flattens and rare tokens get more mass. The usual pitfall is setting temperature too low for creative tasks, which makes the output repetitive, or too high for factual tasks, which increases hallucination.
- Senior
- In a real codebase you expose temperature as a user setting or a per-feature constant, not a hard-coded value. For structured output (JSON extraction) you set it low to get more consistent, parseable results. For creative writing you set it higher. You also combine it with top-p sampling: temperature shapes the distribution, top-p truncates the tail. You verify the effect by running the same prompt many times and comparing outputs.
How do you handle structured output from an LLM in an Android app?
- Junior
- You ask the model to return JSON and parse it with kotlinx.serialization into a data class. If parsing fails, you show a fallback UI instead of crashing.
- Mid
- You define a @Serializable data class as the schema and include it in the prompt. After decodeFromString, you add explicit checks: range validation on numeric fields, enum checks on string fields, and non-empty checks on lists. The model can return syntactically valid JSON that violates your schema, so the extra checks are necessary. You wrap everything in a try/catch and return null on failure.
- Senior
- You also handle the case where the model wraps the JSON in markdown fences or adds prose before the JSON. You strip non-JSON content before parsing. For critical paths you add a second validation pass against a business-rule layer (for example, a price must be positive and below a cap). You log the raw JSON and the parse result to a server for offline analysis, so you can see how often the model violates the schema. You never put the model's API key in the APK; the call goes through your backend.
How do you decide between on-device and cloud inference for an Android feature?
- Junior
- On-device means the model runs on the phone, so it works offline and keeps data private. Cloud means the model runs on a server, so you get a bigger, better model but need internet and pay per request.
- Mid
- The trade-offs are privacy, offline use, latency, model quality, app size, battery, and device coverage. On-device models add to app size (or need a download), use battery, and not all devices can run them well. Cloud gives you the latest model but adds network latency and per-token cost. You also consider that on-device models are smaller and may produce lower-quality output for complex tasks.
- Senior
- You prototype both paths and measure: on-device, you check latency, memory, heat and battery on the lowest-tier device you support. Cloud, you measure p95 latency and cost per session. You check the current docs for which models run on-device and on which devices, because that list changes frequently. For a hybrid approach you run a small model on-device for the common case and fall back to cloud for edge cases, with a timeout so the user is not waiting. You gate the feature behind a flag so you can disable it if a model update degrades quality.
When would you choose on-device inference over a cloud call in an Android app?
- Junior
- On-device is better when the user needs the feature offline, when privacy is critical because the data should not leave the phone, or when you need very low latency without a network round-trip. The main downside is that the model is smaller and the app gets bigger.
- Mid
- On-device wins for latency-sensitive, privacy-sensitive, or offline tasks like text classification or image tagging. The model weights load into RAM and run on the NPU or CPU, so there is no network cost. The pitfall is that a large model can cause OutOfMemoryError on low-RAM devices, so you must check available memory before loading and provide a cloud fallback.
- Senior
- The decision is a multi-axis trade-off: privacy, offline, latency, model quality, app size, battery, device coverage, and per-token cost. In a real codebase I would wrap both paths behind an AiBackend interface, pick at startup based on ActivityManager memory info and device support, and log which path was taken so I can monitor the ratio in analytics. I would also A/B test whether the on-device model quality is acceptable for the feature before committing.
How do you keep the cloud AI API key out of the Android app?
- Junior
- The API key should never be in the app code, BuildConfig, or a string resource. It lives on your server. The app sends the prompt to your server, and your server calls the model provider with the key.
- Mid
- The key is stored in your server's secret manager (environment variable, vault, or equivalent). The Android app authenticates to your server with its own token (OAuth, JWT, or a session cookie). This way, even if the APK is decompiled, the attacker only sees your server URL, not the provider key. The pitfall is accidentally logging the key in server-side debug output.
- Senior
- Beyond keeping the key server-side, I would add rate limiting and per-user quotas on the server so a compromised client cannot drain the budget. I would also audit the server logs for key exposure and rotate keys on a schedule. In the Android app, I would use a short-lived token obtained at login, not a long-lived secret, and consider App Check or Play Integrity so only my real app can call the backend.
A user reports the AI feature is slow. How do you diagnose whether it is on-device or cloud latency?
- Junior
- Check whether the feature is using the on-device or cloud path. If it is cloud, the delay is likely the network round-trip. If it is on-device, the delay is the model loading or inference time on the CPU.
- Mid
- Add timing logs around the AiBackend.complete call: record start, end, and which implementation ran. For cloud, also log the HTTP status and response time. For on-device, log whether the model was already loaded or had to be loaded from disk. The usual pitfall is that the first call is slow because the model loads into RAM, but subsequent calls are fast; users only notice the first call.
- Senior
- I would instrument both paths with a structured log that includes device model, RAM class, NPU flag, model size, and whether the call was cached. In the cloud path, I would add a Server-Timing header from the backend to separate network time from model inference time. I would then look at p95 latency in the analytics dashboard, not the average, because a few slow devices hide in the mean. If on-device p95 is high, I would check whether the model fell back to CPU instead of GPU or NPU and whether thermal throttling is kicking in.
How do you handle a cloud model returning invalid JSON as structured output?
- Junior
- You should not assume the JSON is valid. Parse it in Kotlin and catch the exception. If parsing fails, show an error message to the user instead of crashing.
- Mid
- Define a data class matching the expected schema and use a JSON parser. Catch the parse exception and treat it as a normal error path. The pitfall is that the model may return valid JSON with wrong field types or missing fields, so you should also validate the decoded object (non-null fields, enum values) before using it.
- Senior
- I would add a retry with a stricter prompt that includes the JSON schema and an example, but cap retries to control cost. On the server side, I would validate the response before forwarding it to the client. On the client, I would log the raw response for debugging but never show it to the user. I would also add a schema version field so I can handle breaking changes in the output format without a client update.
How do you ensure an LLM returns valid JSON in a production Android app?
- Junior
- You add a JSON schema to the prompt and tell the model to respond only with JSON. You then parse the response with a JSON library. If parsing fails, you show an error message.
- Mid
- You embed the schema in the prompt (or use the API's response-schema mode if it has one) and set a low temperature to reduce randomness. You parse the raw string with kotlinx.serialization inside runCatching. On failure you retry once with a stricter prompt, then fall back to a default UI state. You never let the raw string reach the UI layer.
- Senior
- You treat the model output as untrusted input, the same as a network response. You validate with kotlinx.serialization using ignoreUnknownKeys = true to absorb extra fields, but you still assert that required fields are present and correctly typed. You log the raw response for offline analysis, add a retry with exponential backoff, and track a structured-output success rate in your analytics. In a real codebase you would verify this by checking that every call site wraps the parse in runCatching and that the UI has a fallback branch for the Failure case.
What happens when a prompt exceeds the context window? How do you handle it?
- Junior
- The model cannot read the full input. It either ignores the oldest part or the API returns an error. You should keep the prompt short.
- Mid
- The API rejects the request or older context gets dropped. In Android you must chunk long documents, summarise old conversation turns, and prioritise the most relevant context. You estimate token count before sending (roughly 4 characters per English token) and trim if needed.
- Senior
- Truncation is silent in some runtimes, so the model answers from a partial context and the user gets a wrong answer with no error signal. You must measure token count client-side, implement a sliding-window or summarisation strategy for conversation history, and add a test that asserts the prompt stays under the window. You also monitor for context-length errors in production and alert on them. Check the current docs for the exact window size of your model, because it changes between model generations.
A user reports that the AI feature gives wrong answers. How do you investigate?
- Junior
- You check the logs to see what prompt was sent and what the model returned. You try the same input again to see if it is reproducible.
- Mid
- You reproduce the issue by replaying the exact prompt and context. You check whether the context window was exceeded, whether the temperature was too high, or whether the model hallucinated a fact. You add the case to a regression test set. You also check if the model version was updated between the user's session and now.
- Senior
- You separate three failure modes: context truncation (the model never saw the relevant data), hallucination (the model invented a plausible but false answer), and prompt ambiguity (the user's intent was unclear). You check the raw prompt and response in your logging system, verify the context retrieval step returned the right documents, and confirm the temperature and schema were correct. You add the case to a golden-set evaluation and track the hallucination rate over time. You also check whether the UI presented the answer with a confidence indicator or a source citation, because the fix may be in the UI layer, not the model.
Where should the LLM API key live in an Android app architecture?
- Junior
- It should not be in the app code. It should be on a server.
- Mid
- The key lives on your backend server. The Android app calls your server, which calls the LLM. You never put the key in BuildConfig, local.properties, or any file in the app module, because an APK can be decompiled and the key extracted in minutes.
- Senior
- The key is a server-side secret, managed by your secrets manager (Vault, AWS Secrets Manager, or equivalent). The Android app authenticates to your backend with a short-lived token (OAuth, JWT). Your backend adds the LLM key server-side and proxies the request. You add a CI check that greps the built APK for key patterns and fails the build. You rotate keys on a schedule and monitor for anomalous usage. In a real codebase you verify this by confirming that no string in the app module matches a key pattern and that the network layer calls your domain, not the LLM provider's domain directly.
On-device AI
How does ML Kit manage the model lifecycle on Android?
- Junior
- You get a client with getClient(), call process() on an image, and get a Task back. You should call close() when you are done to free memory.
- Mid
- The client holds native resources. You create it once, reuse it, and close it in onDestroy or onCleared(). The process() call returns a Task<T> that you bridge into coroutines. ML Kit does the work on its own threads, so the main rule is not to block the main thread waiting for it.
- Senior
- Beyond the API contract, the first call can be slower while the model loads, so you create the client early. For unbundled models you handle the case where Play services has not downloaded the model yet. You also track native heap with dumpsys meminfo to confirm the model is actually freed after close(). For GenAI, the model is downloaded separately and gated behind a feature-status check, so the lifecycle has an extra download-and-verify step before the first call.
What are the constraints of ML Kit GenAI APIs compared to classic vision APIs?
- Junior
- GenAI APIs like summarization and proofreading run on-device through AICore. They only work on supported devices, so you check availability first. They also have usage quotas.
- Mid
- Classic APIs (text, barcode, face) run on-device and are broadly available. GenAI APIs run Gemini Nano through AICore and are device-gated. You must call a feature-status check, trigger a model download, and handle the unsupported case. GenAI also does not run in the background, so you cannot schedule it in a WorkManager job.
- Senior
- The trade-off is latency versus capability: classic APIs are fast and universal, GenAI is slower but adds NLP-level features. In a real codebase you build a feature-flag layer that checks AICore availability at app start, caches the result, and routes to a server-side fallback when the device is unsupported. You also log quota errors in analytics, because hitting the quota makes calls fail. The Prompt API gives you more control but you must keep input within the model's context limit yourself.
How do you handle a device that does not support AICore or the NPU?
- Junior
- You check the feature status before calling the GenAI API. If it is not supported, you show a message or fall back to a server call.
- Mid
- You call the feature-status API at app start, store the result, and gate every GenAI call behind it. For classic APIs you do not need this check. For GenAI you also need to handle the model-download failure case, where the device is supported but the download has not completed.
- Senior
- You design the fallback per feature: summarization uses Gemini Nano when the status is AVAILABLE and otherwise degrades to a server-side model through your backend (or hides the feature), while a barcode scan always works locally. You verify the fallback in CI by running the app on an emulator without AICore and asserting the UI shows the degraded path. You also log which tier was used so you can measure the real distribution across your user base.
Why must you call close() on ML Kit recognizers, and what happens if you do not?
- Junior
- Calling close() frees the model from memory. If you do not, the model stays loaded and uses extra RAM.
- Mid
- The model lives in native memory, not the Java heap, so you cannot rely on the GC to free it in time. If you create a recognizer in onCreate and never close it, each screen navigation adds another native allocation. After several navigations the process can exceed the native limit and the OS kills it.
- Senior
- In a large app with many screens that use vision APIs, the risk compounds. You either centralize the recognizer in a @Singleton scope and keep it for the app's lifetime, or scope it to a feature's ViewModel and close it in onCleared(). You add a lint rule or a static-analysis check that flags any TextRecognizer, FaceDetector, or BarcodeScanner without a matching close() call. In production you monitor native heap with dumpsys meminfo in a canary build to catch regressions before release.
Explain the difference between IMAGE, VIDEO and LIVE_STREAM running modes in MediaPipe Tasks.
- Junior
- IMAGE processes one still image and returns a result synchronously. VIDEO processes decoded video frames in order, also synchronously, with a timestamp per frame. LIVE_STREAM is for a live camera feed; it is asynchronous and requires a result listener and a timestamp on every call.
- Mid
- In LIVE_STREAM you call detectAsync() and the task fires the listener when done. Each call must pass an increasing timestamp in milliseconds; if the task is still busy it drops the new frame rather than queuing it. IMAGE (detect) and VIDEO (detectForVideo) return the result directly, with no listener, and VIDEO never drops frames.
- Senior
- The key trade-off is latency versus throughput. LIVE_STREAM optimises for the latest frame, so under load it drops old frames, which is correct for a camera overlay but wrong for a video-encoding pipeline where you need every frame. In a real codebase I measure the drop rate by counting listener callbacks versus frames submitted. I also check that the timestamp source is SystemClock.uptimeMillis(), not currentTimeMillis(), which can jump backwards.
How do you wire a MediaPipe ObjectDetector into a CameraX pipeline?
- Junior
- You create an ImageAnalysis use case with STRATEGY_KEEP_ONLY_LATEST and OUTPUT_IMAGE_FORMAT_RGBA_8888. In the analyzer you turn the ImageProxy into a Bitmap, wrap it with BitmapImageBuilder to get an MPImage, call detector.detectAsync(mpImage, timestampMs), and close the proxy.
- Mid
- The critical detail is that imageProxy.close() must be in a try/finally so an exception does not leak the proxy. The detector must be created with RunningMode.LIVE_STREAM and a result listener set on the options builder. The listener fires on a background thread, so results go into a StateFlow or are posted to the main thread. The frame must also be rotated by imageInfo.rotationDegrees.
- Senior
- In production I also handle the case where the model is not yet downloaded: the analyzer checks a StateFlow<Boolean> and skips detectAsync() until the model file exists. I measure frame-drop rate in a debug overlay. If creating the task with Delegate.GPU fails on a device, I recreate it with Delegate.CPU and accept lower FPS rather than crashing.
What happens if you forget to call close() on a MediaPipe detector?
- Junior
- The native memory for the model stays allocated. If you create a new detector without closing the old one, you leak memory each time.
- Mid
- The model weights and any GPU buffers remain in native memory. After a few screen navigations or rotations the process can run out of memory and be killed by the OS. The fix is to call detector.close() in ViewModel.onCleared() or when the screen is done, and to close every ImageProxy.
- Senior
- I add a debug check that watches native heap across repeated navigations, so the leak is caught before release. In a large app with multiple screens using different tasks, I centralise task lifecycle in one owner (a ViewModel or a small manager class) so callers cannot forget to close.
How do you handle a large .tflite model that cannot be bundled in the APK?
- Junior
- You download the model file after install and store it in the app's private directory. You show a loading screen until the download finishes.
- Mid
- Use Play Asset Delivery to manage the download, or a WorkManager job with retry and back-off. Point BaseOptions at the downloaded file (or pass it as a buffer). You must handle the case where the download fails or is interrupted, and show a retry UI.
- Senior
- I gate the download behind a feature flag and a device-capability check (RAM, storage). The WorkManager job is constrained to unmetered network. I verify the downloaded file with a checksum before passing it to BaseOptions. If the model is not ready, the analyzer skips detectAsync() and the UI shows a placeholder. I also monitor download success rate and model-load time in analytics, and I plan a CPU fallback for devices where the GPU path fails.
Walk me through the CameraX to MediaPipe pipeline end to end.
- Junior
- CameraX's ImageAnalysis use case gives you ImageProxy objects on a background thread. You turn each proxy into a Bitmap, wrap it as an MPImage, pass it to a MediaPipe task like ObjectDetector, and get results back. You must close the proxy and the detector when you are done.
- Mid
- You set ImageAnalysis to RGBA_8888 and STRATEGY_KEEP_ONLY_LATEST so the camera delivers the right format and drops stale frames. Inside the analyzer you convert to a Bitmap, rotate it by imageInfo.rotationDegrees, build an MPImage with BitmapImageBuilder, then call detector.detectAsync with an increasing millisecond timestamp. Results come back on the result listener set in the options. The proxy is closed in a finally block, and the detector is closed when the screen is done to free native memory.
- Senior
- The pipeline is a producer-consumer chain: the camera HAL fills a buffer pool, ImageAnalysis hands you the latest buffer, you convert and hand off to MediaPipe, and results come back on a callback thread. The key design decisions are the backpressure strategy (KEEP_ONLY_LATEST prevents queue buildup), the running mode (LIVE_STREAM is async and drops frames under load), and the delegate choice (GPU with CPU fallback). In a real codebase I would add a frame-drop counter, create the detector before the camera starts, and verify on a low-end device that the overlay still updates.
What happens if you forget to close the ImageProxy?
- Junior
- The camera buffer is not returned to the pool. After a few frames the pool is exhausted and ImageAnalysis stops delivering new frames, so the camera preview appears frozen.
- Mid
- CameraX has a limited number of image buffers. Each unclosed proxy holds one. Once they are all held, the analyzer gets no new frames. The fix is to always call proxy.close() in a finally block, including on exception paths.
- Senior
- The preview keeps running because it is a separate use case, so the bug looks like a frozen overlay, not a frozen camera. In a production codebase I would add a unit test with a fake ImageProxy that asserts close() is called on success and on exceptions. I would also make sure that any async work (like a coroutine that processes the image) copies the pixels first and never touches the proxy after close.
How do you handle frame drops in LIVE_STREAM mode?
- Junior
- LIVE_STREAM can drop frames when the model is slow. You should not assume every frame produces a result. Your UI should handle missing results gracefully, for example by keeping the last known detection visible.
- Mid
- In LIVE_STREAM, MediaPipe drops a new frame while it is still processing the previous one. You can reduce wasted work by using STRATEGY_KEEP_ONLY_LATEST on the CameraX side, a smaller model, or a faster delegate (GPU over CPU). On the UI side, track the timestamp gap between consecutive results and show a 'processing' indicator when the gap exceeds a threshold.
- Senior
- The trade-off is latency versus completeness: LIVE_STREAM keeps results current by skipping frames, which is right for a camera overlay. If every frame matters, such as analysing a recorded video, VIDEO mode processes every frame in order instead. In a real app I would pick the model size per device tier and log a frame-drop rate metric so we can see the impact on low-end devices.
How do you choose between CPU and GPU for a MediaPipe task, and where does NPU fit?
- Junior
- GPU is often faster for vision models. CPU is the safest fallback because every device has it. You set Delegate.CPU or Delegate.GPU in BaseOptions.
- Mid
- You try GPU first and catch the creation failure to rebuild the task on CPU. GPU support varies by device and model, so always test the CPU path on a low-end device. NPU is not a BaseOptions choice for MediaPipe Tasks; for NPU you use LiteRT directly.
- Senior
- The choice is per device, not per build. GPU is not always faster for small models, and it competes with the UI and camera for the GPU. In a real codebase I would measure first-frame latency and steady-state fps per delegate on a sample of devices, log the chosen delegate, and keep a remote flag to force CPU on bad devices. If I need NPU, I move that model to LiteRT CompiledModel, which takes accelerator options with fallback.
How does LiteRT accelerator selection and fallback work?
- Junior
- You list accelerators in CompiledModel.Options, like GPU then CPU. LiteRT uses the first one if the device supports it, otherwise the next one.
- Mid
- You pass something like Options(Accelerator.GPU, Accelerator.CPU) to CompiledModel.create. The choice happens at create time, so the cost is paid once. The usual pitfall is listing only NPU or GPU, so the model fails to load on devices without that support. GPU also needs the litert-gpu dependency.
- Senior
- Selection happens at load time, not per inference, so you pay the probe cost once. NPU support is vendor-specific and can vary between firmware versions, so log which accelerator was actually selected and monitor fallback rates in production. If a specific driver has a known bug, gate NPU behind a remote flag rather than shipping a hotfix, because a hard native crash cannot be caught. NPU also needs extra setup, so treat it as an optimisation, not a requirement.
How do you manage the lifecycle of a CompiledModel in an Android app?
- Junior
- You load the model when the screen opens and call close() when the screen is destroyed, typically in onDestroy of the Activity or Fragment.
- Mid
- You load in a ViewModel, create the buffers once, and close the buffers and the model in onCleared. The pitfall is not calling close(), which leaks native memory. For configuration changes, the ViewModel survives rotation, so the model stays loaded.
- Senior
- For long-running services you must handle process death: the model is gone and you need to reload. For multiple models, serialize loading to avoid OOM. You can share one CompiledModel instance via a companion object or a singleton, but you must coordinate close() carefully so one screen does not free a model another screen still uses. Measure native memory with adb shell dumpsys meminfo before and after a session to confirm no leak.
How do you distribute a large model to users without bloating the APK?
- Junior
- You put the model file in the assets folder and it ships with the APK. For small models this is fine.
- Mid
- Large models should not be in the base APK. Use Play Asset Delivery (fast-follow or on-demand) or download with WorkManager after install. The pitfall is exceeding the APK size limit or making the install too slow for users on slow connections.
- Senior
- You also consider Play for On-device AI, which handles model delivery and versioning through the Play Store. For your own download path you need to handle partial downloads, checksums, and storage cleanup on update. A/B test model versions and monitor download failure rates. The file format matters: .tflite for LiteRT, .litertlm for LiteRT-LM. Always show a progress UI and allow the user to retry.
How do you verify that on-device inference is performant enough for your use case?
- Junior
- You run the app on your phone and check that it does not crash and the result appears on screen.
- Mid
- You measure inference time with System.nanoTime() before and after run(), and test on at least one low-end device. The pitfall is testing only on a flagship and missing jank on a budget phone.
- Senior
- Build a CI pipeline that runs inference on a device farm with a mix of chip vendors and memory tiers. Track p50 and p99 latency, not just the average. Monitor thermal throttling: sustained inference can slow the NPU or GPU after a few minutes. Have a graceful degradation path (lower resolution, fewer frames, or skip inference) when latency exceeds a threshold. Log the selected accelerator and inference time to your analytics backend so you can spot regressions after a model update.
What hardware accelerators are available for ML inference on Android, and how do you select them?
- Junior
- Android has three compute units for ML: CPU, GPU, and NPU. In LiteRT you list accelerators in CompiledModel.Options when you create the model. CPU is always available.
- Mid
- You pass accelerators in order, like CompiledModel.Options(Accelerator.NPU, Accelerator.GPU). LiteRT falls back down that list if the first is unavailable. GPU needs the litert-gpu dependency and NPU needs vendor setup. On top of that I add an app-level retry on CPU and log which attempt succeeded.
- Senior
- Beyond the API call, you need a runtime fallback chain because NPU support is vendor-specific and changes every chip generation. You also load the model early to hide the setup cost, and you measure on real low-end devices. In a large codebase you add a remote feature flag to disable NPU for a specific chip revision without a store update. You verify the active accelerator by logging it at load time and correlating with crash analytics.
How do you handle the case where the NPU is not available on a user's device?
- Junior
- You wrap the NPU model load in a try-catch and fall back to GPU, then CPU. The app keeps working, just slower.
- Mid
- You list GPU and CPU after NPU in the options, and if create still throws you retry with CPU only. Each step logs what was tried. The key pitfall is treating the NPU path as the only path and never testing the fallback on a device without an NPU.
- Senior
- You add a remote feature flag so you can disable NPU for a specific chip revision without a store update. You monitor crash analytics for native crashes that correlate with NPU initialization. You test on a device matrix that includes devices without NPU. For large models you also gate the download: if the device has no NPU and the model is too big for CPU, you skip the download entirely and show a cloud-assisted fallback.
What is the difference between GPU and NPU acceleration for ML workloads?
- Junior
- The GPU is a graphics processor that can also do matrix math. The NPU is a dedicated AI chip. The NPU is faster for inference but not every device has one.
- Mid
- The GPU handles parallel tensor operations and is available on most modern Android devices. The NPU is a vendor-specific coprocessor optimized for sustained inference with lower power draw. The GPU is a better fit for short, bursty tasks like a single image classification; the NPU wins for long-running workloads like on-device LLM token generation. The NPU is not present on every device, so you always need a GPU or CPU fallback.
- Senior
- The trade-off is not just speed. NPU kernels are vendor-specific, so a model that runs on one NPU may not run on another. You may need to quantize the model or compile it ahead of time per vendor. GPU acceleration is more portable but competes with the graphics pipeline, so heavy inference can cause frame drops in a camera app. In a real codebase you profile with Perfetto to see whether inference and rendering are fighting over the GPU.
How do you verify in production that your model is actually running on the accelerator you requested?
- Junior
- You log the accelerator name at load time and check the logcat output on a test device.
- Mid
- You log the selected accelerator and correlate it with crash analytics. If you requested NPU but the log shows CPU, the fallback triggered. You also add a timing assertion: if inference takes longer than a threshold on a device that should have an NPU, something is wrong. The pitfall is testing only on a flagship where NPU is always present, so the fallback path is never exercised.
- Senior
- You add a structured log field for the active accelerator and ship it to your analytics backend, so you can see the distribution across your install base. You compare inference time against known per-accelerator numbers from your device lab, because a request for NPU does not prove the model ran there. You add a remote flag to force a specific accelerator for A/B testing. For on-device LLMs you also track time-to-first-token per accelerator to catch regressions when a new chip revision ships.
How do you decide between a cloud LLM and an on-device LLM in an Android app?
- Junior
- On-device is better for offline use and privacy because data never leaves the phone. Cloud is better when you need a very large model or the device is too weak. You check the device capabilities first.
- Mid
- You weigh latency, privacy, model size and battery cost. On-device avoids a network round-trip and keeps data local, but the model is smaller and you must handle the case where the device cannot run it. You add a cloud fallback behind your own backend so the API key never ships in the APK.
- Senior
- You also factor in Play size limits, model-download bandwidth, thermal throttling and usage quotas. In practice you build a routing layer: try on-device first, fall back to cloud on quota exhaustion or unsupported hardware. You measure p95 latency on a low-end device, not a flagship, and you track crash-free sessions per device tier in your dashboard.
What is the correct order of operations before calling the ML Kit GenAI Prompt API?
- Junior
- You check whether the feature is available, download the model, and then call the API. If the feature is not available you show a message to the user.
- Mid
- The order is: get the client with Generation.getClient(), call checkStatus(), call download() if the status is DOWNLOADABLE and wait for DownloadCompleted, then call generateContent. Inference must run while the app is in the foreground. You also respect usage quotas and the input token limit.
- Senior
- You can call warmup() when the screen opens so the first request is faster, and you show download progress from DownloadStatus events. You log the status result to telemetry so you can see what fraction of your users actually get AVAILABLE, and you gate the feature behind a remote flag so you can switch to the cloud path if a model update behaves badly.
Why is the MediaPipe LLM Inference API deprecated and what replaces it?
- Junior
- The old API used .task model files and the tasks-genai module. It is now in maintenance mode. The replacement is LiteRT-LM with .litertlm model files.
- Mid
- LiteRT-LM is built on LiteRT, the new name for TensorFlow Lite. Its Kotlin API is an Engine created from an EngineConfig with a CPU, GPU or NPU backend, and a Conversation you send messages to, with streaming as a Flow. New on-device LLM work should start there.
- Senior
- In a real codebase you would migrate by wrapping the old tasks-genai calls behind an interface, then swapping the implementation to LiteRT-LM behind a feature flag. You also switch the model file from .task to a .litertlm build of the model, and verify output quality and speed on a golden test set and a low-end device before rolling out.
How do you handle a device where the GPU or NPU backend does not work for LiteRT-LM?
- Junior
- You try the faster backend first, and if the engine fails to initialize you create it again with the CPU backend.
- Mid
- You set backend = Backend.GPU() (or Backend.NPU(...)) in EngineConfig, wrap initialize() in a try-catch, and on failure close that engine and build a new one with Backend.CPU(). Backend support depends on the chip and drivers, so you cannot assume it. You initialize early, off the main thread, so the user does not wait.
- Senior
- You also measure inference time per accelerator on a device lab and store the result in a config server so the app can skip accelerators that are known to be slow on a given SoC. You also watch thermal state and shorten or pause long generations when the device gets hot. You expose the active accelerator in a debug overlay so QA can verify the fallback path on real hardware.
Cloud AI in the app
How does Firebase AI Logic keep the Gemini API key off the device?
- Junior
- The app calls Firebase.ai(backend = GenerativeBackend.googleAI()) and the SDK sends the request to the Firebase AI Logic proxy. The Gemini key stays on Google's side, so it is never in the APK.
- Mid
- The Firebase config in the APK is not a secret, so the real protection is App Check. With App Check enforced, the proxy blocks requests that lack a valid token from Play Integrity (or the debug provider in development).
- Senior
- You verify by decompiling the release APK and confirming no Gemini key is there, checking App Check metrics before turning on enforcement, and considering replay protection with limited-use tokens. You also set per-user rate limits in Firebase AI Logic and a budget alert so one user cannot run up the bill.
How do you render a streaming AI response in Jetpack Compose?
- Junior
- You call generateContentStream which returns a Flow<GenerateContentResponse>. You collect it in the ViewModel and append each chunk's text to the UI state.
- Mid
- You collect inside viewModelScope so the flow is cancelled when the ViewModel is cleared. You update a StateFlow-backed UiState with update { } to avoid race conditions. You re-throw CancellationException so the coroutine framework can clean up the flow collector.
- Senior
- You also handle back-pressure: if the user scrolls fast, the UI may not keep up with token arrival. You can batch updates, for example by sampling the text every few frames. For markdown you use a safe renderer that parses incrementally, not one that re-parses the full string on every chunk. You test cancellation by navigating away mid-stream and asserting the flow is closed and no memory is leaked.
Explain the function-calling loop in Firebase AI Logic.
- Junior
- You pass FunctionDeclaration objects as tools when you create the model. When the model wants a function, the response's functionCalls list has a name and JSON args. You run the function and send the result back.
- Mid
- The loop is: send prompt with chat.sendMessage → model returns function calls → your code runs them → wrap each result in a FunctionResponsePart → send it back with sendMessage → repeat. You cap the loop at a few steps to avoid an endless loop.
- Senior
- In production you add a step counter, a per-step timeout, and a fallback message if the model loops. You validate the JSON arguments against a schema before executing, because the model can produce malformed JSON. For sensitive functions (deleting data, sending email) you add a user-confirmation step between the FunctionCall and execution. You log each step for debugging but never log the full prompt if it contains PII.
What do you do when the chat history exceeds the context window?
- Junior
- You limit the number of messages you pass to startChat. For example, keep only the last 10 turns.
- Mid
- You store the full history in Room but pass only the last N turns to the model. When N is exceeded you trim the oldest turns. You also watch for the SDK throwing an exception when the token count exceeds the window and handle it gracefully.
- Senior
- You implement a sliding window plus a summarisation step: when the list exceeds the cap, you call generateContent on the oldest 5 turns to produce a one-paragraph summary, replace those turns with a single Content, and continue. You estimate tokens (a rough characters/4 rule, or the SDK's countTokens call) so you can trim before the call fails. You add an integration test that simulates 50 turns and asserts the list stays under the cap and the summary is present.
Why can't an Android app call the Anthropic Messages API or OpenAI API directly?
- Junior
- You cannot because the API key would be inside the APK and anyone can extract it with a decompiler. The key must stay on a server.
- Mid
- Beyond key exposure, a direct call gives you no place to enforce user auth, per-user rate limits, or billing quotas. The backend is the only layer that can do all three before the request reaches the provider.
- Senior
- In a real codebase you verify this by checking that no provider key appears in the app's outbound headers (use a proxy or a network inspector). You also confirm the backend has a circuit breaker and a per-user token bucket so one user cannot exhaust the provider quota, and you rotate keys on a schedule.
How do you stream an LLM response into a Jetpack Compose UI?
- Junior
- You read the HTTP response body line by line, parse SSE data: lines, and append each chunk to a string that Compose observes through a StateFlow.
- Mid
- You wrap the read loop in a Flow on Dispatchers.IO and collect it in a StateFlow-backed UiState inside viewModelScope, so the stream cancels when the ViewModel is cleared and the UI never blocks the main thread.
- Senior
- You also handle back-pressure because the UI cannot render faster than it composes, you render partial markdown through a safe renderer to avoid injection, and you show a typing indicator while the first chunk is in flight. In a real codebase you test the stream with a fake OkHttpClient that returns a canned SSE body and assert the collector stops after cancellation.
Explain the tool-call or function-calling loop.
- Junior
- The model returns a JSON object with a tool name and arguments. You run that tool, send the result back, and the model generates the final answer.
- Mid
- The loop can repeat multiple times. You must cap it with a small step limit to prevent an endless loop. Each iteration appends the tool result to the conversation history before the next call. In the Anthropic Messages API that means a tool_use block from the model and a tool_result block from you.
- Senior
- In production the tool execution happens on the backend so the app never sees raw tool arguments. You log every step for audit, validate the tool arguments against a JSON schema before execution, and alert when the step limit is hit because that usually signals a prompt or tool bug. You also set a per-user daily cap on tool calls to control cost.
How do you manage chat history and context limits?
- Junior
- You store messages in a list and send the whole list to the model each time the user sends a new message.
- Mid
- You persist history in Room and trim old turns when the token count approaches the context window. You may summarise older turns into one short summary to save tokens while keeping the gist.
- Senior
- You also handle the case where a single user message exceeds the window by truncating or rejecting it, you store the summary separately from raw turns so you can re-expand if needed, and you test with the maximum context size the model supports. Check the current docs for the window size because it changes between model releases.
How does streaming an AI response into a Compose UI work end-to-end?
- Junior
- The AI SDK returns a Flow of response objects. You collect that flow in the ViewModel and append each chunk of text to a StateFlow. The Composable observes the StateFlow and re-renders the text on every update.
- Mid
- The request runs when collect is called inside viewModelScope.launch. Each GenerateContentResponse carries a text field that may be null, so you skip nulls. The StateFlow drives recomposition through collectAsStateWithLifecycle(), which also pauses when the screen is not visible. For backend providers you read SSE or chunked HTTP with OkHttp or Ktor and map each chunk into the same Flow<String> shape.
- Senior
- Beyond the happy path, you must handle three failure modes: cancellation (re-throw CancellationException so the HTTP connection closes), error (catch generic exceptions and surface them in the UI state), and interleaving (cancel the previous Job before launching a new stream). In a real codebase I verify the path by writing a unit test with a fake Flow that emits, cancels, and errors, and by checking in Logcat that the OkHttp call is actually cancelled. I also profile with LeakCanary to confirm no StateFlow outlives the ViewModel.
What happens when the user navigates away mid-stream? How do you handle it?
- Junior
- When the user leaves the screen, the ViewModel is cleared and viewModelScope is cancelled. The collect call stops, and the upstream HTTP request is closed.
- Mid
- viewModelScope is tied to the ViewModel lifecycle, so onCleared cancels all child coroutines. The finally block in the try still runs, resetting isLoading to false. collectAsStateWithLifecycle() stops observing when the screen is in the background, but that does not cancel the coroutine in the ViewModel.
- Senior
- The subtlety is that collectAsStateWithLifecycle() only pauses observation; the coroutine in viewModelScope keeps running until the ViewModel is actually cleared. If the user backgrounds the app but the ViewModel survives, the stream continues. For long-running streams you may want to explicitly cancel on ON_STOP and resume on ON_START, or use a Job you can cancel and restart. I also check that the OkHttp call is truly cancelled by inspecting the connection pool in a debug build.
A user sends a second message while the first response is still streaming. What do you do?
- Junior
- You should cancel the first stream before starting the second one. Otherwise both streams write to the same text field and the user sees interleaved output.
- Mid
- Keep a Job reference in the ViewModel. At the start of send(), call previousJob?.cancel() and then launch the new coroutine, storing the new Job. Also reset streamingText to empty so the new response does not append to the old one. Add a short debounce on the send button to absorb accidental double-taps.
- Senior
- Cancelling the old job is necessary but not sufficient. The old coroutine's finally block may race with the new one's state update, so guard the StateFlow update with a check that the job is still the active one. In production I also add a generation counter: each send() increments it, and the collect lambda ignores chunks whose generation does not match the current one. This makes the race deterministic and testable. I also ensure the cancelled HTTP request releases its socket back to the OkHttp pool.
How do you render partial markdown that might have unclosed syntax?
- Junior
- A half-written bold marker (two asterisks with no closing pair) renders wrong in a standard markdown parser. The simplest fix is to show the raw text until the marker is closed.
- Mid
- Buffer the incoming text and only render complete markdown blocks. Detect open markers (unmatched asterisks, underscores, or backticks) and hold the trailing fragment in a separate pendingText field. Render the completed portion with a markdown renderer and show the pending fragment as plain text. This avoids crashes from naive parsers.
- Senior
- In a real app I use a streaming-safe renderer that tolerates incomplete syntax, or I apply a simple state machine that tracks open/close markers per chunk. I also sanitise the output to strip any HTML or script tags the model might emit. For performance, I throttle the markdown parse to a fixed interval rather than every token, because parsing on every chunk causes jank on low-end devices. I verify correctness with a test suite that feeds deliberately split tokens and asserts the rendered output matches the full-text render.
Explain the function-calling loop in an AI app.
- Junior
- The model returns a function name and JSON arguments instead of a text answer. Your code runs that function and sends the result back to the model. The model then produces the final text answer. You repeat this until the model stops requesting calls.
- Mid
- The loop has three phases: the model emits a function call with a name and an args map, your code executes the tool and builds a function response, and you send that back in the same chat. You cap the loop at a small fixed number of iterations so the model cannot loop forever. Each round-trip adds tokens to the context, so you must watch the context window.
- Senior
- Beyond the basic loop, the senior concern is where the loop runs. In Firebase AI Logic the loop can run client-side because there is no Gemini key in the app (protect it with App Check). For Claude or OpenAI the loop must run on your backend because the API key cannot live in the app. The backend also enforces per-user rate limits, logs every call for audit, and can short-circuit a loop before it reaches the model. You verify the cap works with a fake model that always returns a function call and asserting the loop terminates.
How do you prevent a prompt-injection attack through tool arguments?
- Junior
- You should not trust the model's output. Validate the arguments before using them, like you would validate user input from a text field.
- Mid
- The model can be tricked by a malicious user message into calling a destructive tool with attacker-chosen arguments. You validate the type and range of every argument, check that the calling user has permission for that tool, and log the call. You also cap the number of tool calls per request, and require user confirmation for anything sensitive, so a single injection cannot trigger side effects on its own.
- Senior
- Validation is necessary but not sufficient. You also need a least-privilege model: each tool declares which roles can call it, and the executor checks the user's role before running. You separate the model's reasoning from the execution: the model proposes a call, but a server-side authorisation layer decides whether to run it. You fuzz-test the executor with random argument maps and add a canary value to sensitive tools so you can detect unauthorised execution in logs.
What happens when the model returns multiple function calls in one response?
- Junior
- The model can ask for more than one tool at once. You need to run all of them and send back all the results.
- Mid
- The functionCalls list can contain multiple entries. You execute each one, build a FunctionResponsePart for each, and send them all back in the next sendMessage call. Calls returned together are usually independent, so they can run in parallel.
- Senior
- Parallel execution is the optimisation: if the calls are independent, run them concurrently with async in a coroutine scope and collect the results. If they are dependent, you must serialise. The senior trade-off is latency versus correctness: parallel calls reduce wall-clock time but make error handling harder because one failure must not cancel the others. You also need to decide whether a single failed tool aborts the whole batch or whether you send back a partial result set with an error for the failed call.
How does function calling interact with streaming in Compose?
- Junior
- When you stream the model's response, a function call might arrive in the middle of the stream. You need to handle that case.
- Mid
- A function call can appear in the stream. You wait until you have the complete call before executing the tool; some providers send the JSON arguments in pieces. In Compose you show partial text as it arrives, then pause the UI update while the tool runs, then resume with the model's final answer.
- Senior
- The interaction is a state-machine problem. The UI state has at least four phases: streaming text, awaiting tool result, streaming text again, and done. You model this as a sealed class in a StateFlow so Compose can render each phase. Cancellation is critical: if the user leaves the screen mid-tool, you cancel the viewModelScope coroutine, which cancels the HTTP call to the model and the tool execution. You also need to handle the case where the user sends a new message while a tool is still running: either queue it or cancel the in-flight call.
How does Firebase AI Logic startChat work, and where does the conversation state live?
- Junior
- startChat takes an optional list of Content objects as initial history. It returns a Chat object that appends new user and model turns internally. Each sendMessage call sends the full accumulated history to the model server. The model itself is stateless; it does not remember between calls.
- Mid
- The Chat object maintains a list of Content in memory. Every sendMessage resends that list. In a ViewModel you should own the history as a StateFlow and pass a trimmed copy to startChat each time, so you control what is sent and can persist to Room. The Chat object's internal list is a convenience, not a source of truth.
- Senior
- Because the model is stateless, the cost and latency grow linearly with history length. In production I keep the authoritative list in the ViewModel, trim it to a token budget before each call, and persist to Room. I create a fresh startChat per call rather than reusing one Chat object, because the Chat's internal list can drift from the ViewModel after a trim or a Room reload. I also verify in the codebase that no code path bypasses the trim step by calling generateContent directly.
How do you handle the context window limit in a long conversation?
- Junior
- The context window is a maximum number of tokens the model accepts. If you send more, the API rejects the request. You need to limit how much history you send.
- Mid
- Common strategies are a sliding window (keep the last N turns), a token-budget trimmer (count approximate tokens and drop from the front), or summarisation (call the model to compress old turns into one short summary). A sliding window is cheapest but loses early context. Summarisation preserves meaning but costs an extra API call and can introduce drift.
- Senior
- I combine a token-budget trimmer with a summarisation pass. The trimmer keeps the last K turns under budget. When turns are dropped, a background call asks the model for a one-paragraph summary of them, which goes back in as a short summary turn. I store the summary in Room alongside the raw turns so I can replay. I verify the trim logic with a property-based test: for any input list, the output must stay under the budget and must always include the most recent user turn.
What happens to chat state when the Android process is killed?
- Junior
- The ViewModel is destroyed and all in-memory state is lost. If the history is only in a StateFlow, the user sees an empty chat after the app restarts.
- Mid
- You persist every turn to Room as it is created. On ViewModel creation you load the last conversation from Room and call startChat with that history. The StateFlow is rebuilt from the Room query. You write each turn to Room as soon as it exists, so little is lost if the process dies.
- Senior
- I use a Room Flow query that emits the ordered list of turns for the active conversationId. The ViewModel collects that Flow into the StateFlow on creation. I write to Room before calling the model, so the user turn is durable even if the model call is cancelled. I also handle the case where the process dies mid-stream: the partial model text is stored with a 'partial' flag, and on reload the UI shows it as incomplete. I verify this by putting the app in the background and killing it with adb shell am kill during a stream, then confirming the UI restores correctly.
How do you prevent prompt injection from turning model output into a destructive command?
- Junior
- You should not execute model output directly. Parse it and check it before acting.
- Mid
- Define a sealed result type with an allow-list of actions. Parse the model's text into that type. If parsing fails, discard the response. For Firebase AI Logic, use a responseSchema so the model returns structured JSON. On a backend path, validate the JSON against a schema before the app receives it.
- Senior
- I treat all model output as untrusted input. The app parses it through a strict schema (sealed class or JSON schema) and maps only known actions to side-effects. Destructive actions require a second confirmation from the user. I add a server-side allow-list so the backend rejects unknown action strings before they reach the app. In the codebase I search for any place that calls a Room mutation or a navigation intent with a string that originated from a model response, and I ensure every such path goes through the parser. I also run a fuzz test that feeds known injection payloads and asserts no side-effect fires.
Building apps with AI agents
How does Claude Code differ from a chat-based AI assistant when working on an Android project?
- Junior
- Claude Code runs in your terminal or IDE and can read files, run shell commands like ./gradlew test, and edit files. A chat assistant only sees what you paste. Claude Code sees the whole repo and can verify its own edits by running the build.
- Mid
- The key difference is the agent loop: read context, plan, act, verify, repeat. Because it can run ./gradlew assembleDebug and read the output, it catches its own compile errors. A chat assistant has no feedback loop; it generates text and stops. In a Kotlin project this means Claude Code can iterate on a failing test until it passes, while a chat assistant gives you one shot.
- Senior
- The loop also means the agent's context window is the bottleneck. CLAUDE.md is always loaded; skills load on demand. In a large multi-module Gradle project you must curate what the agent sees or it wastes tokens on irrelevant modules. I verify the loop works by giving the agent a failing unit test and watching it run ./gradlew :app:testDebugUnitTest, read the stack trace, and retry. If it cannot run the test, the agent is just a fancy autocomplete.
What is the difference between CLAUDE.md and a skill, and when would you use each?
- Junior
- CLAUDE.md is a file at the repo root that is always loaded into every session. A skill is a folder in .claude/skills/ with a SKILL.md file that loads only when the task matches its description. CLAUDE.md holds global rules; a skill holds a focused procedure.
- Mid
- CLAUDE.md is the sticky note: build commands, hard rules, module layout. A skill is a drawer you open when needed: 'add a Compose screen', 'migrate a Retrofit call to OkHttp'. The skill's YAML front-matter has a name and description; the agent matches the description against the user's task. If you put everything in CLAUDE.md you burn context tokens on every turn. Skills follow the open Agent Skills standard, so they work across tools.
- Senior
- The trade-off is context budget vs. discoverability. CLAUDE.md is guaranteed to be in context but costs tokens on every turn. A skill is free until invoked but the agent must decide it is relevant. In a large multi-module project I keep CLAUDE.md short with build commands and hard rules, and I create skills per feature module. I verify a skill loads by running a task that matches its description, or by invoking it with /skill-name. Google's Android skills and the Android Studio agent use the same Agent Skills standard, so the format is portable.
How do hooks work, and what is a practical use case for an Android project?
- Junior
- Hooks are shell commands in .claude/settings.json that run on lifecycle events like PreToolUse and PostToolUse. PreToolUse runs before a tool call such as a file edit; PostToolUse runs after it. You can use PostToolUse to run ktlint after every edit.
- Mid
- The practical use case is blocking forbidden paths. A PreToolUse hook reads the tool input as JSON on stdin, checks tool_input.file_path, and exits with code 2 if it matches keystore.jks, local.properties, or any file containing a secret. This is a hard guardrail; a rule in CLAUDE.md is only context. Another use case: a PostToolUse hook runs ./gradlew spotlessApply so every file the agent touches is formatted before you review the diff.
- Senior
- Hooks and permission deny rules are the mechanisms that can stop the agent mid-action. PreToolUse receives the tool name and input, including the file path and proposed content; if it exits with code 2 the call is blocked. I use a PreToolUse hook that greps the diff for API-key patterns and blocks the write. I also use a Stop hook that runs a secret scanner on the diff before Claude finishes. The pitfall is that hooks run in a shell, so they must be fast; a slow hook blocks the agent's loop. I keep each hook small and test it by piping sample JSON into the script before committing it to settings.json.
What is your process for reviewing AI-written code in a production Android app?
- Junior
- I read the diff line by line, run ./gradlew test and ./gradlew lint, and check that the code follows our conventions. I treat it like a junior colleague's pull request.
- Mid
- Beyond the diff I check for architectural violations: did the agent expose a MutableStateFlow from a ViewModel? Did it call Retrofit from a feature module instead of going through :core:network? Did it add a hardcoded string instead of using strings.xml? I run the full test suite, not just the one the agent ran. I also check that no secret or keystore path was touched.
- Senior
- I review in three passes: (1) does it compile and pass tests, (2) does it respect the module boundaries and state-management rules in CLAUDE.md, (3) does it introduce a regression risk (a new var, a missing rememberSaveable, a ProGuard rule that strips a reflection-based class). I also check the session log for any secret that was pasted into the prompt. For a large diff I split the review by module and run ./gradlew :feature:login:testDebugUnitTest per module. The key insight is that the agent optimises for 'compiles and passes the test I gave it'; it does not optimise for your architecture, so the review must cover what the test does not.
What is CLAUDE.md and when does it load?
- Junior
- CLAUDE.md is a Markdown file at the repo root that Claude Code reads at the start of every session. It tells the agent about the project: package names, build commands, and architecture notes. Without it the agent guesses and may produce code that does not match the project.
- Mid
- CLAUDE.md is always loaded, so it adds to every prompt's context window. The usual pitfall is making it too long; a very large file slows the agent and dilutes the important facts. Keep it short (the docs suggest under about 200 lines) with project-level facts and move detailed conventions into skills that load on demand.
- Senior
- The trade-off is context-window cost versus correctness. A well-scoped CLAUDE.md (package name, module layout, build command, two or three architecture rules) pays for itself because the agent stops guessing. In a monorepo you can place a CLAUDE.md in each module so only the relevant one loads. Verify it works by starting a fresh session and asking the agent to add a new screen; if it uses the wrong package or build command, the file is missing a fact.
How do skills differ from CLAUDE.md, and where do they live?
- Junior
- A skill is a folder in .claude/skills/ with a SKILL.md file that has YAML front matter (name, description) and step-by-step instructions. Unlike CLAUDE.md, a skill loads only when the agent judges it relevant or when you invoke it as a slash command.
- Mid
- The key mechanism is on-demand loading: only each skill's description is in context at the start, and the full body loads only for the skills it needs. This keeps the context window small. The usual pitfall is writing a skill with no verification step, so the agent cannot check its own output. Google publishes official Android skills at github.com/android/skills.
- Senior
- Skills follow the open Agent Skills standard, so a skill is portable across agents that implement the format, not just Claude Code. The agent in Android Studio reads skills from .agents/skills/ or .android-studio/skills/ plus AGENTS.md. In a large team, a plugin bundles the skills, hooks, and MCP servers so a new developer runs one install command. The trade-off is that a skill that is too broad loads too often and bloats context; keep each skill narrow and task-specific.
What are hooks and when would you use them in an Android project?
- Junior
- Hooks are shell commands in .claude/settings.json that fire on lifecycle events: SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, and Stop. A common use is running ktlint after every file edit via PostToolUse.
- Mid
- The critical distinction is PreToolUse versus PostToolUse. PreToolUse runs before the tool call, so exit code 2 blocks it; PostToolUse runs after, so exit code 2 shows the error to Claude but does not revert the file. The usual pitfall is using PostToolUse to try to block a bad edit, which does not work. Always scope the matcher to the tools you care about, e.g. Edit|Write.
- Senior
- In a real codebase I would add a PreToolUse hook that blocks edits to .jks, .keystore, and signingConfig blocks, and a PostToolUse hook that runs ./gradlew ktlintCheck. I would also add a SessionStart hook that prints the module layout so the agent orients itself. The trade-off is latency: every hook adds a shell call, so keep the number of hooks small and the commands fast. Verify the hooks work by asking the agent to edit a keystore path and confirming the edit is blocked.
How do you govern AI-generated code in a team of five Android developers?
- Junior
- Every developer uses the same CLAUDE.md and the same set of hooks in .claude/settings.json. The team reviews every diff the agent produces, runs ./gradlew test, and checks that no signing files were touched. Secrets never go into CLAUDE.md or a skill.
- Mid
- Beyond the shared config, the team adds a PostToolUse hook that runs ./gradlew ktlintCheck and a PreToolUse hook that blocks keystore edits. Skills encode team conventions (Compose patterns, naming rules) so every developer's agent follows the same style. The usual pitfall is that one developer adds a local hook and the others do not, so the team standardises via a plugin that bundles skills, hooks, and MCP servers.
- Senior
- Governance is a layered system: CLAUDE.md sets project facts, skills encode conventions, hooks enforce guardrails, and the human review is the final gate. I would add a CI check that fails if CLAUDE.md or .claude/settings.json is missing, so a new module cannot bypass the config. I would also log Stop hook output to a shared channel so the team can audit what the agent did. The trade-off is that too many hooks slow every session, so I keep the hook count small and the scripts fast. I verify the system by running a scripted session that tries to edit a keystore and confirming the hook blocks it.
What is MCP and how does it differ from just letting the agent run shell commands?
- Junior
- MCP is a protocol that lets an AI agent call external tools. Instead of the agent typing a shell command and hoping it works, it sends a structured JSON-RPC request to a server that knows the tool's inputs and outputs. This is safer and more predictable than free-form shell execution.
- Mid
- MCP uses JSON-RPC 2.0 over a transport (usually stdio for local servers). The agent calls tools/list to discover available tools and their JSON Schema, then tools/call with validated arguments. The key difference from raw shell is that the schema constrains inputs, the server can enforce permissions, and a PreToolUse hook can block a call before it runs. With raw shell, the agent can type anything.
- Senior
- The deeper trade-off is that MCP adds a process boundary and a schema layer, which costs some overhead but gives you auditability, permission scoping, and the ability to swap the backend (local Gradle vs. a CI API) without changing the agent. In a real codebase I verify this by checking that .mcp.json is committed, the server code is in a separate package with its own tests, and the PreToolUse hook blocks any call that touches signing files or secrets. I also check that the server returns structured errors so the agent does not silently fall back to guessing.
How do you configure an MCP server for Claude Code in an Android project?
- Junior
- You create a .mcp.json file at the project root with a mcpServers key, or run claude mcp add with --scope project. A stdio server entry has a type, a command (the executable to run), optional args, and optional env variables. Claude Code reads this file when it starts a session and asks you to approve the servers.
- Mid
- With stdio, the agent spawns the server as a child process and talks over stdin/stdout. For a Gradle runner you might set command to node and args to the path of a server script. You pass non-secret config like PROJECT_ROOT through env, and secrets through ${VAR} expansion from the developer's environment. The server script implements tools/list and tools/call. A common pitfall is a hard-coded path that only exists on one machine.
- Senior
- Beyond the basic config, I add a PreToolUse hook in settings.json that inspects the tool name and arguments before execution, blocking anything that touches signingConfigs or keystore paths. I also add a PostToolUse hook that runs ktlint after any file-editing tool call. For a multi-module project I scope each server to a module directory via env so the agent cannot accidentally run a task on the wrong module. I review .mcp.json in every PR the same way I review gradle.properties.
What goes wrong when an MCP server crashes mid-session, and how do you handle it?
- Junior
- If the server process exits, the agent can no longer call its tools. The agent may skip those steps or produce incorrect output. The fix is to make the server robust and to check for errors after each call.
- Mid
- If the server crashes, its tools disappear from the session and the agent may move on, guessing results from its training data. The fix is to design the server to return an error result (isError true) on tools/call instead of crashing, with a message that says what is wrong. In Claude Code, /mcp shows which servers are connected or failed.
- Senior
- In a real codebase I add three layers: (1) the server catches all exceptions and returns a clear error result, and retries flaky work like adb itself; (2) a SessionStart hook runs a health check (like adb version for a device server) so a missing binary is caught before the agent starts work; (3) a PostToolUse hook logs every tool call to a file so I can audit what the agent did. I also serialise Gradle calls inside the server so two calls do not fight over the same build.
How do MCP servers interact with CLAUDE.md, skills, and hooks in a Claude Code session?
- Junior
- CLAUDE.md is always loaded as project context. Skills are loaded on demand when relevant. Hooks run on lifecycle events. MCP servers provide tools the agent can call. They are separate layers that work together.
- Mid
- CLAUDE.md tells the agent the project conventions. A skill (a folder with SKILL.md) gives it a procedure, for example 'how to run instrumented tests on a connected device'. The skill's instructions may reference an MCP tool like adb-device:installApk. Hooks in settings.json fire on PreToolUse, PostToolUse, UserPromptSubmit, SessionStart, and Stop, letting you run ktlint after an edit or block a dangerous call. The MCP server is the execution layer; the skill is the instruction layer; the hook is the guard layer.
- Senior
- The interaction matters because a skill can invoke an MCP tool, and a PreToolUse hook can intercept that invocation. In a real codebase I structure it so that the skill says 'call the gradle-runner tool with task testDebugUnitTest', the MCP server executes it, and a PostToolUse hook runs ktlint on any files the agent edited. A PreToolUse hook matching mcp__gradle-runner__.* can block risky arguments. Plugins can bundle skills, hooks, subagents, and MCP servers into one installable unit so the whole team gets the same setup.
How does Agent Mode in Android Studio differ from a single-turn chat?
- Junior
- Agent Mode can do multiple steps: it reads files, edits code, builds the project, reads the result, and loops until the task is done. It waits for me to accept or reject changes. A single-turn chat gives one answer and stops.
- Mid
- The key difference is the plan-execute-verify loop. Agent Mode uses AGENTS.md content in every prompt and pulls in a matching SKILL.md when relevant, then plans steps, executes them, and checks the result, for example by building or checking Logcat. The usual pitfall is accepting changes you did not read, such as an edit to build config.
- Senior
- AGENTS.md and skills guide the agent, but they are not a permission system, so the real controls are reviewing each change it proposes, version control, and pre-commit hooks or CI that block diffs to signing files. In a real codebase I check the Do NOT section of each SKILL.md and test that the agent respects it. The trade-off is speed versus safety: accepting changes quickly is fast but risky; reviewing every hunk is slower but safe.
What is the difference between AGENTS.md and a SKILL.md, and when do you use each?
- Junior
- AGENTS.md content is added to the start of every prompt. A SKILL.md lives in .agents/skills/<name>/ and is loaded only when the user's request matches the skill's description. AGENTS.md holds project-wide rules; a skill holds a focused procedure.
- Mid
- The mechanism is context management. AGENTS.md is like a system prompt: it is in every turn, so it must be short. A SKILL.md is loaded on demand when the model judges the description field in the YAML front matter relevant. The pitfall is putting a 300-line procedure in AGENTS.md, which wastes context window on tasks that do not need it.
- Senior
- In a large monorepo you might have one AGENTS.md at the root and per-module AGENTS.md files, plus many skills in .agents/skills/. The agent picks up AGENTS.md files in the current file's directory and its parents, so module rules apply when you work in that module, and a skill loads when the request matches. The trade-off is discoverability: a skill with a vague description is never loaded, so you must test each skill with three sample prompts before merging it. You also need a CI check that validates every SKILL.md has valid front matter and a non-empty Do NOT section.
How do you review code that an AI agent wrote before merging it?
- Junior
- You read the diff like any pull request: check every changed file, run the tests, and make sure the code follows the project's style. You do not trust the agent's summary.
- Mid
- You add three checks: run ./gradlew lint and ./gradlew test yourself, verify that no signingConfigs, keystore, or local.properties file was touched, and confirm that the agent did not add a new dependency without justification. The usual pitfall is that the agent's summary says "fixed lint" but the diff also changes a proguard-rules.pro entry that strips a class at runtime.
- Senior
- In a team workflow you add a pre-commit hook that blocks diffs to signing files and a CI job that runs the full test suite on the agent's branch. You also check that the agent's changes are covered by a test: if the agent added a function but no test, you reject the PR. The deeper question is whether the agent's change is the minimal fix or a rewrite; a senior reviewer asks "why did you change this file at all?" and expects the agent (or the developer who prompted it) to justify every hunk. You also verify that no secret or API key was pasted into the chat log, which may be stored in a server-side database.
A skill you wrote is not loading in Agent Mode. How do you debug it?
- Junior
- Check that the SKILL.md file is in the right folder (.agents/skills/<name>/ or .android-studio/skills/<name>/ for Android Studio) and that the name in the YAML front matter matches the folder name.
- Mid
- Beyond the path, check the description field. If it is a topic label like "Compose tips" instead of a trigger sentence, the model will not match it to the user's prompt. Also check that the YAML front matter is valid: missing --- delimiters or a tab character instead of spaces will silently break parsing.
- Senior
- First I force it with @skill-name to prove the file itself loads; if that works, the problem is the description. In a team setting you add a CI check that parses every SKILL.md, validates the front matter, and a short list of sample prompts to try by hand against each skill. The trade-off is that a very specific description loads reliably but misses paraphrased prompts, while a broad description loads too often and injects irrelevant steps. You tune by adding synonyms to the description and testing with real prompts from the team's issue tracker.
How do you review AI-generated code differently from a human-written PR?
- Junior
- I read every line of the diff, run the tests, and check for obvious issues like missing null checks or hardcoded values. I treat it the same as any other PR, but I pay extra attention because the agent may not know my codebase conventions.
- Mid
- I add a structured checklist: lint, unit tests, instrumented tests, release build, and a secret scan. AI code can produce a large diff in seconds, so I focus on semantic correctness: does the logic match the intent? I also check that the agent did not modify build files or signing configs, and I verify that every new public function has a test.
- Senior
- I layer the review: automated gates such as hooks and CI catch mechanical issues, and I focus my time on the semantic layer where AI fails most. I also check whether the agent had enough context: was CLAUDE.md up to date, were the right skills loaded? I track which categories of bugs recur and add them as hooks or lint rules so the next agent run catches them automatically.
What verification pipeline do you run after an AI agent edits your Android project?
- Junior
- I run ./gradlew test and ./gradlew build to make sure nothing is broken. I also read the diff to check for obvious mistakes.
- Mid
- I run ktlint, unit tests, instrumented tests, and a release build. I also scan the diff for secrets with a tool like gitleaks and check that no signing files were touched. I verify that the agent actually ran its own tests and did not skip that step.
- Senior
- I automate the pipeline as a post-merge hook or CI stage so it runs every time. I add project-specific checks: a lint rule that flags Context in ViewModels, a test that verifies no new public API is untested. I also review the agent's own test output: did it run ./gradlew test and actually pass, or did it skip that step? I track failure categories and feed them back into CLAUDE.md or hooks.
An AI agent's code passes all tests but users report a crash. What do you do?
- Junior
- I look at the crash log, find the stack trace, and fix the line that crashes. I add a test for that specific case so it does not happen again.
- Mid
- I reproduce the crash with the exact device and input. I check whether the test covers that path. Often the test uses a fake that does not model the real failure mode, so the test passes but production crashes. I add a test that models the real scenario, such as a rotation or a network timeout.
- Senior
- I check whether the crash is a race condition or a lifecycle issue that unit tests cannot catch. I add an instrumented test or a soak test. I also review the agent's context: did it have the right CLAUDE.md, were the relevant skills loaded? I add a regression test and a hook that blocks the pattern in future agent runs, so the same bug cannot recur.
How do you set up guardrails so an AI agent cannot break your release build?
- Junior
- I tell the agent not to change build files or signing configs. I review the diff manually before merging.
- Mid
- I configure .claude/settings.json: deny rules and a PreToolUse hook that block access to keystore files and local.properties. I add a CI check that runs the release build on every PR. I also add a secret scan so a hardcoded key is caught before merge.
- Senior
- I combine hooks, CI gates, and a CLAUDE.md that explicitly lists forbidden files. I use a subagent for risky tasks so the main agent's context is not polluted. I track which guardrails actually caught issues and remove the ones that never fire. I review the agent's permission scope: it should not have write access to the signing keystore or to BuildConfig fields that hold secrets, and secrets must stay on the server.
Shipping AI features
How do you defend against prompt injection in an Android app that uses AI?
- Junior
- You treat model output as data, not commands. Any action the model suggests that changes data needs the user to confirm it. Keyword checks for phrases like "ignore previous instructions" help a little but are easy to get around.
- Mid
- The key pitfall is RAG and tools: scraped web content and tool results enter the context and can carry injection, not just the user's typed input. You mark that content as untrusted, give tools the least power they need, validate tool arguments, and log suspicious inputs for review.
- Senior
- You treat all untrusted text (user input, scraped content, tool output) as potentially adversarial. You run a server-side classifier in addition to local pattern matching, because attackers adapt. You verify the fix by running a fixed eval set that includes known injection samples and checking that the model's output does not contain action commands. You also monitor online metrics like retry rate and thumbs-down to catch new injection patterns in production.
What does the Google Play Data safety form require for an app with AI features?
- Junior
- You must list every type of data your app collects, including user prompts sent to an AI provider. You also declare whether data is shared with third parties.
- Mid
- The form requires you to declare each data type (user content, health data, location, etc.) and whether it is shared with a third party such as an AI provider. Separately, Play's AI-generated content policy requires an in-app way to report offensive AI output. The pitfall is forgetting that user prompts and conversation history count as data you share.
- Senior
- You map every data flow in the app to a row in the Data safety form, including on-device vs cloud paths. You verify that the form matches what the code actually sends by auditing network calls in a debug build. You also check that the in-app report button meets Play's requirement for reporting AI-generated content, and you wire it to a backend that logs and reviews flagged outputs. You re-check the form every time you add a new data type or provider.
How do you update a prompt or model without shipping a new APK?
- Junior
- You store the prompt text and model name on a server or in Firebase Remote Config. The app fetches them at startup or on a schedule, so you change them without a Play release.
- Mid
- You version each prompt and model name in the config, and you roll out the new version to a percentage of users first. The pitfall is a bad prompt that degrades quality for everyone at once. You watch online metrics (thumbs up/down, retry rate) during the rollout and can roll back instantly. See Updating models and prompts in production.
- Senior
- You keep prompts and model names in a server config with a version field, and you gate the rollout behind a feature flag. On-device models are downloaded and versioned separately from the APK, so a model update does not require a Play release. You run the new prompt against a fixed eval set offline before enabling it for any users. You monitor latency, cost, and quality metrics in parallel, and you set an automatic rollback threshold. You also ensure the app handles a missing or stale config gracefully with a last-known-good fallback.
How do you evaluate whether a new prompt or model is safe to ship?
- Junior
- You test the new prompt on a set of example inputs and check that the outputs look correct. You compare the new results with the old ones.
- Mid
- You build a fixed eval set of real user inputs with expected properties (tone, length, no harmful content). You run the new prompt or model against this set offline and compare scores. You also watch online metrics like thumbs up/down and retry rate after a small rollout. The pitfall is using LLM-as-judge without calibration: the judge model can share biases with the model under test. See Evaluating AI features.
- Senior
- You maintain a versioned eval set that includes edge cases, injection samples, and adversarial inputs. You run offline evals with multiple scorers (rule-based checks plus a calibrated LLM-as-judge) and require a minimum score before rollout. You run a canary rollout to a small user group and monitor online metrics for a sufficient period. You track regression on the eval set after every prompt or model change. You also log a sample of production outputs for periodic human review to catch issues that automated scoring misses.
How do you test a feature that uses a non-deterministic LLM?
- Junior
- I would use a set of inputs and check if the output contains certain keywords or follows a specific format.
- Mid
- I would build a fixed test set of inputs and use an offline evaluation process to score the outputs against expected properties, ensuring the model meets specific criteria before release.
- Senior
- I would implement a multi-layered evaluation strategy. This includes offline evaluations using a fixed test set with property-based scoring, potentially using an LLM-as-a-judge for semantic quality, and monitoring online metrics like retry rates and user feedback to catch regressions in production.
What are some online metrics for an AI-powered Android app?
- Junior
- I would look at whether users are clicking a thumbs up or thumbs down button.
- Mid
- I would monitor user feedback like thumbs up/down, as well as the retry rate which indicates if the first response was unsatisfactory.
- Senior
- I would track user sentiment via explicit feedback, but also technical metrics like the rate of fallbacks to default behavior, latency distributions, and the frequency of users re-prompting the same query.
Why shouldn't we just use a very powerful model for everything?
- Junior
- Because powerful models can be slower and more expensive to use.
- Mid
- Larger models increase latency and cost, which can degrade the mobile user experience and increase operational expenses.
- Senior
- There is a trade-off between reasoning capability and efficiency. For many mobile tasks, a smaller, faster model is sufficient. We should evaluate if a smaller model meets our quality threshold to optimize for latency, cost, and battery life.
How do you know if a prompt change is a regression?
- Junior
- I would run the new prompt and see if the answers look different than before.
- Mid
- I would run a batch of known inputs through both the old and new prompts and compare the results using a scoring system.
- Senior
- I would use a regression testing suite where each input has an associated 'gold standard' or expected property. I would then compare the pass rate of the new prompt against the baseline pass rate to ensure no degradation in quality or format.
How do you handle AI latency in a mobile app?
- Junior
- You stream the response so the user sees text appear word by word instead of waiting for the full answer. You also set a timeout so the call does not hang forever. A loading indicator or skeleton UI keeps the user informed.
- Mid
- On the client you use a Flow from the server proxy and collect chunks into the UI state. You wrap the collection in withTimeout so a slow server does not freeze the screen. The usual pitfall is forgetting to cancel the upstream request when the user navigates away, which wastes tokens and money.
- Senior
- You also measure p50 and p95 latency in production and alert when p95 crosses a threshold. You decide whether to stream or buffer based on the feature: a chat UI benefits from streaming, but a one-line summary can be buffered. You verify the timeout is actually cancelling the HTTP call, not just the coroutine, by checking that the server logs show a closed connection.
How do you control the cost of an AI feature?
- Junior
- You cap the input length so users cannot paste huge documents. You cache repeated prompts so the same question does not hit the server twice. You pick a smaller model when the task does not need the largest one.
- Mid
- You add a per-user rate limit on the server and a daily budget alert in the cloud billing dashboard. The pitfall is capping only on the client, which can be bypassed by a modified APK. You also log token count per request so you can spot outlier usage.
- Senior
- You run a cost-per-active-user metric in your dashboard and set a burn-rate alert. You A/B test a smaller model against the larger one using your eval set before switching. You version the model name in server config so you can roll back a costly model without an app release. You also consider on-device inference for high-frequency, low-complexity tasks to eliminate per-call cost entirely.
What do you do when the AI service is unavailable?
- Junior
- You show an error message like 'AI is unavailable, try again later' and a retry button. You never show a blank screen or a raw stack trace.
- Mid
- You check a local cache first and show the last good answer with a 'stale' label. If there is no cache, you show a static fallback message. The pitfall is caching sensitive data that should not persist; you clear the cache on sign-out. You also add a circuit breaker on the server so it stops forwarding to a dead provider.
- Senior
- You design the fallback as a product decision, not an afterthought. For a search feature, the fallback is the old keyword search. For a chat feature, it is a canned response with a link to support. You monitor the fallback rate as a metric; a spike means the service is degraded and you page the on-call engineer. You also handle the case where the device does not support on-device inference by checking capabilities before offering the feature.
How do you decide which model to use for a feature?
- Junior
- You start with the smallest model that works and move up only if the quality is not good enough. You check the current docs for supported models and devices.
- Mid
- You build a fixed eval set of real inputs with expected properties and score each candidate model offline before release. The pitfall is evaluating on a toy set that does not reflect production traffic. You also factor in latency: a faster model that is slightly less accurate may be the right choice for a mobile UI.
- Senior
- You run the eval as a CI gate so every prompt or model change is scored before merge. You keep the model name in server config so you can switch without an app release and roll out gradually. You watch online metrics (thumbs up/down, retry rate) after rollout and set a rollback threshold. For on-device models, you handle download, versioning, and storage limits separately from the APK.
How do you handle updates to the AI model or prompts in a production Android app?
- Junior
- I would use a remote configuration service like Firebase Remote Config to change the prompt string without needing a new app release.
- Mid
- I would implement a configuration provider that fetches a JSON object containing the model ID and prompt. I would also ensure there is a hardcoded fallback in the app to prevent crashes if the fetch fails.
- Senior
- I would design a versioned configuration system. This allows us to roll out new prompts to a subset of users via canary releases and monitor telemetry like error rates or user feedback before a full rollout. I would also ensure the backend handles the actual API keys to keep them out of the client.
Where should LLM API keys be stored in an Android application?
- Junior
- They should be kept in a secure place, ideally not in the code.
- Mid
- They should never be in the Android app code or BuildConfig. They must stay on a secure server, and the app should call your own backend.
- Senior
- API keys must reside on the server side to prevent extraction via reverse engineering. The mobile client should authenticate with your backend using a short-lived user token, and the backend should act as a proxy to the LLM provider, managing rate limiting and secrets.
What happens if you update a prompt and the AI starts behaving unexpectedly?
- Junior
- I would try to fix the prompt and upload it again.
- Mid
- I would use the remote configuration tool to revert the prompt to the previous known-good version immediately.
- Senior
- I would trigger an immediate rollback via the remote config dashboard. Then, I would reproduce the issue using a fixed test set of inputs in an offline evaluation environment to identify why the new prompt failed before attempting a new iteration.
Why shouldn't you hardcode a specific versioned model name in your Kotlin code?
- Junior
- Because the model might be updated or removed by the provider.
- Mid
- Hardcoding makes the app brittle. If the provider deprecates that specific version, the app will stop working until a new version is released to the Play Store.
- Senior
- It prevents agility. By fetching the model identifier from a server, we can switch to a different model or a smaller, faster model instantly if we detect latency issues or cost spikes, without waiting for the Android release cycle.