Your AI server, running locally on Android.
PocketNode turns an Android smartphone into a local, hardware-aware LLM inference server with an OpenAI-compatible HTTP API, foreground service persistence, and GPU acceleration.
Reference device: Pixel 7 Pro (Tensor G2, Mali-G710, 12 GB RAM).
Stage 7: tool calling and load progress (OpenAI tool calls for Open WebUI's Native mode, RAM progress bar while a model loads).
GPU inference on the Pixel 7 Pro works (about 10–12 tokens/s with gemma-4-E2B-it). The remaining device checks are in docs/geraetetest-stufe-2.md, docs/geraetetest-stufe-3.md, docs/geraetetest-stufe-4.md, docs/geraetetest-stufe-5.md, docs/geraetetest-stufe-6.md and docs/geraetetest-stufe-7.md.
| Stage | Content | State |
|---|---|---|
| 1 Foundation | OpenAI-compatible API, auth, queue, streaming, tests, CI | done |
| 2 Engine | LiteRT-LM backend (GPU / CPU), model folder, foreground service, dashboard | done, GPU verified on device |
| 3 Robustness | RAM guard, thermal handling, autostart, idle unload, model download, diagnostics | done, device test open |
| 4 Device profiles | Device profiles, engine optimization (GPU / CPU threads / NPU), export, NPU libraries | done, device test open |
| 5 Server operation | Server mode screen, heat limits with battery temperature, CPU variant with all cores, charge-limit hint | done, device test open |
| 6 Model folder and polish | Model folder on the device storage, reload after a failed optimization, token count for too_few_tokens, larger server-mode text, test chat 2048 tokens, notification offers "Start" when stopped |
done, device test open |
| 7 Tool calling and load progress | tools / tool_choice / tool_calls in the chat API, test chat tool switch, RAM progress bar while a model loads |
done, device test open |
| 8 Performance | Use the hardware more, including an evaluation of LiteRT-LM speculative decoding | open |
| 9 Web admin | Web admin with several API keys | open |
| 10 Embeddings | /v1/embeddings, evaluate the LiteRT-LM embedding engine |
open |
Design and plans:
- Design
- Plan for stage 1
- Plan for stage 2
- Plan for stage 3
- Design for stage 4: device profiles
- Design for stage 5: dedicated server operation
- Design for stage 6: model folder and polish
- Design for stage 7: tool calling and load progress
| Module | Content |
|---|---|
:core |
Pure Kotlin/JVM: engine contracts, EngineManager (queue, model switching), HTTP API (Ktor CIO), LiteRtLmBackend, model folder, FakeBackend. No Android classes, so its tests run without the Android SDK. |
:app |
Android app: settings, foreground service, overview, models and settings screens. Only built when an Android SDK is present (ANDROID_HOME or local.properties). |
- Install the debug APK from the latest CI run (artifact
pocketnode-debug-apk) on anarm64-v8adevice with Android 12 or newer. - Under Models, tap Download and paste an
httpslink to a.litertlmfile (a Hugging Face token is only needed for gated models and is not stored). Alternatively copy a model into the app's model folder or import it from a file:adb push model.litertlm /sdcard/Android/data/com.pocketnode.server/files/models/
- Allow Nearby devices when the app asks. On Android 17 this grants local network access; without it, devices on the same network cannot reach the server (connections time out), while clients from routed networks still work.
- Tap Start server, then load a model under Models. The overview shows the address, the active accelerator (GPU or CPU) and the API key (with QR code).
- Allow unrestricted battery use when the app asks on the first server start (the overview keeps a reminder while it is missing), and keep the phone on a charger with a charge limit (e.g. 80 %).
The debug APK is signed with a fixed key that is checked into this repository (app/debug.keystore). Updates therefore install over the previous version without losing the downloaded models. Because the key is public, anyone could sign an APK that replaces yours: install only builds from this repository, for your own use.
Instead of importing a model (which copies it into the app's folder), you can point PocketNode at a folder on the device storage, for example /storage/emulated/0/AI-Modelle. Every .litertlm file in it appears on the Models screen marked "from folder" and is read in place, without a copy.
- In Settings, under "Model folder", tap "Grant access". This opens the system screen "All files access" for the app. PocketNode needs that permission (
MANAGE_EXTERNAL_STORAGE) to hand LiteRT-LM a normal file path. It uses it only to list and read.litertlmfiles in the chosen folder. Back in the app, the state updates without a restart. - Tap "Choose folder" and pick the folder in the system picker. Only folders on the device storage are accepted: the internal storage (
primary:<folder>becomes<external storage>/<folder>) and SD cards or other volumes (<volume>:<folder>becomes/storage/<volume>/<folder>). Cloud providers, the Downloads provider and anything else are rejected with a message, and nothing is stored. Only the resulting path is stored, one folder at a time. - "Remove" forgets the folder; its models disappear from the list without a server restart.
Rules:
- Duplicates: If a file in the model folder has the same model id (file name without the extension) as a model in the app's folder, the app folder's file wins, the folder file is skipped, and the log shows one WARN line per change.
- No delete: The app never deletes files in the model folder; the "Delete" button is hidden for folder models. Downloads and imports still go into the app's folder.
- Folder gone or access revoked: If the folder is missing, unreadable or the "All files access" permission is revoked, the folder contributes no models and Settings shows the reason. No crash, models in the app's folder keep working and the server keeps running. A model loaded from the folder stays loaded even if its file is deleted or the folder vanishes; it disappears from the list and from
/v1/models, and a request naming it after another model was loaded gets404 model_not_found. Nothing crashes. - Everything else works the same: folder models are selectable, loadable, optimizable (profiles are keyed by file name and size) and listed by
/v1/models. - When the Models screen has no model at all, its hint also mentions that a model folder can be set in Settings.
- Heat limits: The system thermal status and the battery temperature are evaluated together. New requests get
503 too_hotwithRetry-After: 30from thermal statusCRITICALor a battery at 45 °C or more; a running generation finishes. The running generation is aborted fromEMERGENCYor 50 °C. After rejecting, requests are admitted again only when the status is belowCRITICALand the battery is at 42 °C or less (3 °C gap against flapping); if the battery temperature is unknown, only the status counts. The overview shows the thermal status, the battery temperature and a warning while requests are rejected, also when the server is stopped. The engine optimization also waits (up to 2 minutes) until the status is belowMODERATEand the battery is below 45 °C (an unknown battery temperature does not hold it back). The limits are constants incore/.../hardware/HeatGuard.kt. - Server mode: For a phone that only serves, the overview has a "Server mode" button (or the setting "Open server mode when the server runs" opens it once per server run while the app is visible; the boot start itself never opens it, but bringing the app to the foreground while the server runs can open it once). The screen stays on at minimal brightness, shows only a few grey status lines (address, model and accelerator, queue, speed, thermal status and battery temperature) on black, hides the system bars and moves the lines every minute against burn-in (16 sp text, grey). A tap shows "Double-tap to exit" for 5 s; a double tap or back leaves it, and the server keeps running. Because the app is in the foreground with the screen on, the low-latency Wi-Fi lock applies.
- Charge limit: While charging at 90 % or more, the overview suggests limiting the charge to 80 % in the system battery settings (button "Battery settings", "Hide" hides the hint for good). Android normally does not let apps read whether a charge limit is already active, so the hint may show even if it is.
- Notification: While the server starts or runs, the notification offers "Stop". When the server is stopped (from the app or the notification), the notification says "Stopped" and offers "Start"; tapping it starts the server again, and the notification then shows the real status. After a failed start (for example the port is taken) it offers "Start" (retry) and "Stop", because a failed server still holds the foreground service. The stopped notification can be swiped away.
- Memory: Before loading, the app checks that free RAM covers 1.2 × the model file plus 512 MB. Otherwise the request fails with
503 insufficient_memory, naming both numbers. - Autostart: In Settings, "Start after reboot (if it was running)" restarts the server after the phone booted, but only if it was running before. It starts once the phone has been unlocked for the first time.
- Idle unload: Optionally frees the model's memory after 15 to 120 minutes without requests. The next request loads it again, which takes a few seconds.
- Diagnosis: The fourth tab shows the device profile and the last 200 log entries, with a button to copy both into a bug report. Its "Test model" card sends a question through the app's own API on
127.0.0.1(API key, streaming; up to 2048 output tokens) and shows the answer live with time to first token and tokens/s. If it works there but not from another device, the problem is the network, not the server. - GPU fallback: The overview shows a clear notice when the GPU was requested but the model runs on the CPU. The reason is in logcat under the tag
PocketNode. - Wi-Fi with the screen off: The app holds a low-latency Wi-Fi lock, but Android only honours it while the screen is on and the app is in the foreground. With the screen off, Wi-Fi power saving adds a few hundred milliseconds to the first response. For the lowest latency, run the phone with the screen on, ideally in server mode.
Android 17 blocks local network traffic, including incoming connections, for apps targeting API 37 unless the app holds ACCESS_LOCAL_NETWORK (permission group "Nearby devices"). The symptom is very specific: ping works and clients in other subnets get answers, but clients in the phone's own subnet time out without even a TCP ACK. The overview shows a warning while the permission is missing. For a quick check without the permission:
adb shell am compat disable RESTRICT_LOCAL_NETWORK com.pocketnode.serverThen restart the app.
A device profile tells PocketNode which compute unit (CPU, GPU or NPU), how many CPU threads and which memory factor work best on a device. The overview shows which profile applies ("bundled", "measured on …", "none", or the progress of a running optimization).
Which profile applies, in this order:
- Measured on this device, entry for exactly this model.
- Measured on this device, device default (derived from all measured models).
- Bundled profile for this device model (manufacturer +
Build.MODEL). - Bundled profile for the same SoC.
- No profile: GPU, CPU as fallback; threads from the core count; memory factor 1.2.
The setting Accelerator in the settings keeps working: "Automatic" follows the profile, "GPU" and "CPU" override the compute unit but keep the profile's threads and memory factor.
Engine optimization measures what is possible on the device (CPU thread variants: the recommended count, the fast cores and all cores, each at most 8 and without duplicates, so 4 and 8 on the Pixel 7 Pro; GPU if an OpenCL library exists, NPU if its libraries were added), one candidate after the other, with a fixed benchmark prompt of about 256 tokens. The winner is the setting that answers a typical agent request fastest: reading 1500 prompt tokens plus writing 300 answer tokens (prefill and decode both count; Open WebUI sends long system prompts, history and tool descriptions). An NPU within 10 % of the best wins anyway because it draws less power and stays cooler. The Diagnosis tab shows the typical-request time per candidate. A candidate that fails because the run produced too few tokens shows how many it produced, e.g. "too few tokens for a measurement (produced: 1)". The result is stored as the measured profile and applied on every later start.
- Automatic: On a device without any profile, the optimization runs the first time the server starts with a model installed (for the selected or first model), or the first time you tap "Load" on a model in the app. A model loaded implicitly by an API request does not start it. Until it finishes, the API answers
503 optimizingwithRetry-After: 30, and/healthreportsstatus: unavailable. Afterwards the winner is loaded. If a run that was started with "load the winner" ends without a winner (the device got too warm, the run was cancelled or every candidate failed), the model is loaded again with its normal profile or default settings instead of leaving the server without a model; if that reload fails, it is only logged. - Retries: If the device got too warm or the app was killed mid-measurement, the next start tries again, at most 3 attempts in total. After a cancel by the user or when every candidate failed, nothing runs automatically any more; start it by hand. A restart or stop caused by the app itself does not count.
- By hand: Diagnosis, card "Engine optimization": start, cancel, results table. "Export profile" opens the Android share sheet with the JSON file (only with a measured profile). The server may be stopped meanwhile; starting the server then waits and happens by itself once the run ends. With the server stopped, stay in the app while it measures: if the app goes to the background, the run is cancelled without saving anything (without the server's foreground service Android could freeze it mid-measurement).
- Re-measure hint: The card suggests measuring again when the profile was measured with another LiteRT-LM version, or when the NPU libraries changed since the last successful measurement.
The profile contains no serial number, IP address, API key or file paths.
- In the app, open Diagnosis and run the optimization ("Start optimization") until it is done.
- Tap "Export profile" and save the file.
- Put it into
profiles/as<manufacturer>-<model>.json(lowercase, hyphens) and open a pull request.
Details and the file format are in profiles/README.md. The next version then knows your device from the first start.
The NPU paths of LiteRT-LM need vendor libraries (for example Qualcomm's dispatch library and QNN runtime, MediaTek NeuroPilot, Google's Tensor dispatch library for the Tensor G5), plus a model compiled for exactly that SoC. PocketNode does not ship them. You get them from the chip vendor's SDK or the LiteRT NPU runtime.
In Diagnosis, card "NPU libraries", add .so files or a ZIP. Only arm64-v8a ELF files are accepted, and a ZIP with unsafe paths (such as ../) is rejected as a whole. The files are copied into the app's private storage (files/npu/); the card lists each with size and SHA-256 and offers "Remove all". The libraries apply from the next server start. Adding libraries never starts a measurement; run the optimization by hand afterwards.
Security: NPU libraries run with all permissions of the app, including access to the API key. Use only files from the chip vendor's SDK. The app shows this warning once before the first add.
Known limit: Qualcomm's NPU loads part of its code on the signal processor via its own search path (ADSP_LIBRARY_PATH). Whether that works from app storage is untested. PocketNode points the path to files/npu; if it still fails, the result is an honest "failed" (or "not available") in the NPU candidate's row of the results table, not a crash.
Requires JDK 17 or newer for the fake backend, JDK 25 for a real model.
POCKETNODE_API_KEY=dev ./gradlew :core:runPOCKETNODE_PORT changes the port (default 8080). Without POCKETNODE_API_KEY a random key is generated and printed. Without POCKETNODE_MODELS_DIR the server uses the fake backend.
curl -s localhost:8080/health
curl -s localhost:8080/v1/models -H "Authorization: Bearer dev"
curl -sN localhost:8080/v1/chat/completions \
-H "Authorization: Bearer dev" \
-H "Content-Type: application/json" \
-d '{"model":"fake-small","stream":true,"messages":[{"role":"user","content":"Hi"}]}'The fake backend always answers Hello from PocketNode. It exists to verify clients such as Open WebUI against the API before a real model is involved.
The desktop run can also use the real LiteRT-LM engine on the CPU. LiteRT-LM 0.20.0 is compiled for Java 25, so this needs JDK 25.
mkdir -p ~/pocketnode-models
# Any .litertlm model, e.g. from https://huggingface.co/litert-community
curl -L -o ~/pocketnode-models/granite-350m.litertlm \
https://huggingface.co/litert-community/granite-4.0-350m-litert-lm/resolve/main/granite-4.0-350m_q8_ekv1280.litertlm
POCKETNODE_MODELS_DIR=~/pocketnode-models POCKETNODE_API_KEY=dev ./gradlew :core:runEvery non-empty .litertlm file in the folder is a model; its id is the file name without the extension. Files added or removed while the server runs show up on the next request. The desktop run binds to 127.0.0.1 unless POCKETNODE_HOST is set.
Tests against a real model run when POCKETNODE_TEST_MODEL points at a .litertlm file:
POCKETNODE_TEST_MODEL=~/pocketnode-models/granite-350m.litertlm ./gradlew :core:test| Endpoint | Auth | Behaviour |
|---|---|---|
GET /health |
no | Status (ok, loading, no_model, unavailable), loaded model, active accelerator, queue length, thermal level, battery_c (battery temperature in °C, omitted when unknown), heat (admit, reject_new, abort_running: what the heat guard currently does with requests), profile (bundled, measured, none, optimizing) |
GET /v1/models |
Bearer | All installed models |
POST /v1/chat/completions |
Bearer | JSON response, or an SSE stream with "stream": true |
Supported request fields: model, messages (roles system/developer, user, assistant, tool; text only; the last message must be from user or tool), stream, max_tokens, max_completion_tokens, temperature, top_p, top_k, stop, stream_options.include_usage, tools, tool_choice, parallel_tool_calls. Unknown fields are ignored.
One generation runs at a time, up to four more wait in a queue. A request for another installed model switches the model. When a streaming client disconnects, the generation stops.
tools (type function: name, description, parameters as a JSON schema object) and tool_choice (auto, none, required, or {"type":"function","function":{"name":"…"}}) are accepted. parallel_tool_calls is accepted and ignored. PocketNode never executes tools and never goes online: the model decides, PocketNode returns the calls, the client runs them and sends the results back.
- Calls: when the model calls tools, the answer has
message.tool_calls(idof the formcall_plus 24 letters and digits,typefunction,function.name,function.argumentsas a JSON string holding an object) andfinish_reasontool_calls.contentisnullunless the model wrote text before the calls. With"stream": truethe calls come in one chunk withdelta.tool_calls(each withindex), followed by a chunk withfinish_reasontool_calls. - Results: send the assistant message with its
tool_calls(content may benull) and onetoolmessage per call (tool_call_id,content). Consecutive tool messages are handled as one set of results. Atool_call_idmust match a call in an earlier assistant message. tool_choice:nonesends no tools to the model, so it answers in text. A named function must be listed intools.- Models without tool support: if the engine rejects the tools, the request is answered as text, with one WARN line in the log naming the model, and no error. Some chat templates silently ignore tools instead; then there is no WARN and the model simply answers in text. With
tool_choicerequiredor a named function, the answer also falls back to plain text if the engine rejects the tools. If a tool call breaks after text was already streamed, the answer ends gracefully with a WARN. Some small models (for examplegranite-350m) write tool calls as plain text instead; that is the model's behaviour, not a PocketNode error.
curl -s http://<IP>:8080/v1/chat/completions \
-H "Authorization: Bearer <API-KEY>" -H 'Content-Type: application/json' \
-d '{"model":"<model-id>","messages":[{"role":"user","content":"What is the weather in Berlin?"}],
"tools":[{"type":"function","function":{"name":"get_weather","description":"Current weather for a city",
"parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}]}'Open WebUI: the default function-calling mode "Native" now works with tool-capable models (for example Gemma 4 E2B/E4B and Qwen3 4B Instruct), including web search. Open WebUI runs the search and sends the result back; PocketNode itself stays offline. The "Legacy" mode (Open WebUI injects the results into the prompt) still works too.
Test chat: in the Diagnosis tab the switch "Test tool" offers the model one sample tool, get_current_time. If the model calls it, the app answers with the device time (one round trip at most) and shows "Tool called: get_current_time" above the final answer.
Load progress: while a model loads, the Models screen (row of that model) and the overview show a bar with "RAM 2.1 / 4.9 GB": the growth of the app's memory since the load started against the expected requirement. It is not shown for the candidate loads of an engine optimization.
All errors use the OpenAI format {"error": {"message", "type", "code"}}.
| Status | code |
Meaning |
|---|---|---|
| 400 | invalid_json, messages_required, last_message_must_be_user, unsupported_role, unsupported_content, unsupported_parameter, invalid_max_tokens, invalid_stop, invalid_sampling, model_not_loaded, context_length_exceeded |
Invalid request |
| 400 | invalid_tool, invalid_tool_choice, invalid_tool_call_id, invalid_tool_call |
Invalid tools entry (type, name, parameters), unknown function in tool_choice, tool message without a matching call, or tool-call arguments that are not a JSON object |
| 401 | invalid_api_key |
API key missing or wrong |
| 404 | model_not_found, not_found |
Model not installed, or unknown endpoint |
| 405 | method_not_allowed |
Wrong HTTP method |
| 413 | request_too_large |
Body larger than 4 MiB |
| 429 | queue_full |
Queue is full, see Retry-After |
| 500 | internal_error |
Unexpected error, details only in the log |
| 503 | no_model, model_load_failed, unavailable |
No model, loading failed, or the device refuses requests (see Retry-After) |
| 503 | too_hot |
The device is too hot, retry after Retry-After seconds |
| 503 | insufficient_memory |
Not enough free RAM to load the model |
| 503 | optimizing |
An engine optimization is running, retry after Retry-After seconds (30) |
When a stop sequence cuts the output, usage is omitted. A failure after a stream has started is sent as an event data: {"error": …}; the stream then ends without [DONE].
./gradlew :core:test # no Android SDK needed
./gradlew :app:testDebugUnitTest # needs the Android SDK (API 37)
./gradlew :app:assembleDebugCI runs the tests, lint and the APK build on every push to main and on pull requests, and stores the debug APK as an artifact.
Google's official NPU path (Tensor SDK, LiteRT-LM NPU models) only covers Tensor G5 and G6. On the Pixel 7 Pro, chat models therefore run on the GPU with the CPU as fallback. Stage 4 replaces the originally planned NPU probe: the app measures what the device can do and stores it as a profile; devices with an NPU can add the vendor libraries themselves (see NPU libraries). Design: device profiles.
MIT