Skip to content

About

Android client for ExecuServe: use on-device models from another app.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

ExecuServe client for Android

Use the model ExecuServe is serving on this phone from your own Android app.

ExecuServe keeps an ExecuTorch model loaded on the phone and answers the OpenAI and Anthropic APIs on 127.0.0.1. Your app does not load a model, link a runtime or ship weights: it calls ExecuServe. This library covers what an app needs around those calls:

  • Find it. Is ExecuServe installed? (Package visibility is declared for you.)
  • Start it. Open ExecuServe's start confirmation and get the address back once it listens.
  • Call it. Models, load and unload, status, text chat and streamed text chat, with ExecuServe's extras typed: cached_tokens, timings, prompt progress, reasoning kept apart from the answer, and errors with ExecuServe's codes (invalid_api_key, model_not_found, context_length_exceeded, ...).

Showcase: an ordinary app streaming answers from the model ExecuServe serves on the same phone

Watch the showcase (1080p, 40 s), filmed on a Snapdragon 8 Elite phone with airplane mode on: the client sample asks ExecuServe to start, the person approves, and answers stream in from the phone's own model, each step beside the client code that does it. How it was made.

It is a thin layer over OkHttp (the transport, internal to the library) and kotlinx.serialization. If your app already uses an OpenAI SDK, keep it and point it at client.openAiBaseUrl with the same key; the tests below check that OpenAI's own Java SDK works that way.

Not in this library:

  • Inference in your process. That is the shape of Qualcomm's GenieX or Google's LiteRT-LM, not of a shared server.
  • Choosing CPU, GPU or NPU. An ExecuServe model's file decides that; ModelInfo.backend says which.
  • Getting a key without the person copying it. ExecuServe has a pairing flow for its browser chat (/pair); this client does not implement it.
  • Tools, images, the Responses and Messages APIs. Use an OpenAI or Anthropic SDK for those.

Setup

Requires Android 12 (API 31)+, compileSdk 36+, and Android Gradle Plugin 8.9.1+ (the latter two come from AndroidX Activity). With google() and mavenCentral() in your repositories, add this to your app's build.gradle.kts:

dependencies {
    implementation("org.experimentalmachines:execuserve-client:0.1.1")
}

Gradle resolves the library's dependencies automatically. Release downloads · Publishing. 0.1.1 adds status().permissions, refuses redirects and refuses unusable keys when the client is made; apps built against 0.1.0 run unchanged (what changed).

Try a complete app: Local Chat is a standalone Android project that installs this Maven Central release: choose among ExecuServe's models, chat with streaming, thinking, Stop and per-answer timings, and watch the server's state. It never loads or unloads models that other apps share; only its messages do, as any client's would. Its emulator verification uses two real models in airplane mode.

One manifest line is yours to add. ExecuServe speaks plain HTTP on loopback, Android refuses cleartext for apps targeting API 28+, and a library cannot allow it for you:

<application android:networkSecurityConfig="@xml/execuserve_network_security_config" ...>

The file ships in the library and opens 127.0.0.1 and localhost only. If you already have a network security config, copy its domain-config into yours. Without it, every call fails with an IOException that says so, except isUp(), which returns false.

A key. The person creates one in ExecuServe (Settings, API keys) and pastes it into your app. Every model, chat and status call needs one, loopback included, because any app with INTERNET can reach 127.0.0.1; isUp() (/health) does not. A key is printable ASCII: ExecuServeClient refuses one with a space, a control character or anything outside ASCII with an IllegalArgumentException when it is made, rather than failing every call.

Use

// In an Activity. Installed? If not, ExecuServe.installIntent() opens its Play Store page.
if (!ExecuServe.isInstalled(this)) { startActivity(ExecuServe.installIntent()); return }

var client = ExecuServe.localClient(apiKey)                    // http://127.0.0.1:8080

// Not running? Ask. When ExecuServe is stopped it shows the person a confirmation; when it
// is already running it answers at once. The answer arrives in this callback, later: make
// the calls that need the server here, not after launch().
val start = registerForActivityResult(StartExecuServe()) { result ->
    when (result) {
        is StartResult.Running -> {
            // The address ExecuServe reports (its port is the person's setting); null when it
            // was already running, in which case keep the address you had.
            result.openAiBaseUrl?.let { client = ExecuServeClient(it, apiKey) }
            lifecycleScope.launch { ask(client) }
        }
        is StartResult.NotStarted -> showError(result.reason ?: "ExecuServe was not started")
    }
}

lifecycleScope.launch { if (client.isUp()) ask(client) else start.launch(null) }

suspend fun ask(client: ExecuServeClient) {
    val model = client.models().first { "chat" in it.capabilities }
    client.chatStream(
        ChatRequest(model.id, listOf(ChatMessage.user("What is the capital of France?")), maxTokens = 256),
    ).collect { event ->
        when (event) {
            is ChatEvent.Content -> append(event.text)
            is ChatEvent.Reasoning -> showThinking(event.text)       // when the model thinks (see Reasoning)
            is ChatEvent.PromptProgress -> showProgress(event)       // only with reportProgress = true
            is ChatEvent.Finished -> Unit
            is ChatEvent.Completed -> log(event.usage, event.timings)
        }
    }
}

Conversations. ExecuServe keeps none: send the whole history each time. Each loaded model keeps the cache of its last exchange, marked with the key that made it, so a follow-up from the same key that extends that exchange can skip re-reading it (Usage.cachedTokens says how many tokens it reused). Another key's request or an unload in between replaces that cache.

Models are shared. Every app on the phone uses the same ExecuServe and its memory. load() and unload() act for all of them: an unload makes the next request of every app using that model wait for a reload and lose its cache, and a load can push out the model another app is using. A chat app needs neither, since a request loads its model; leave memory to ExecuServe, as Local Chat does.

What a key may do. The person decides per key in ExecuServe (Settings, API keys): a new key may chat with every model and may not load or unload. status().permissions says what yours may do (null from an ExecuServe that predates permissions), and models() lists only the models it may use. A call it may not make throws ExecuServeException with HTTP 403 and code permission_denied or model_not_permitted; ask the person to change the key, not to retry.

Reasoning. With thinking left null, Qwen3 and SmolLM3 follow ExecuServe's setting, which is off unless the person changed it. Pass thinking = true (or false) to decide per request; the thinking arrives as ChatEvent.Reasoning, before the answer.

Cancelling. Cancel the coroutine (or stop collecting) and the call returns at once and any open connection closes, even in the middle of a read and even with every IO thread busy; ExecuServe then stops the model. A stream that fails still hands the collector every event that arrived before the failure, then throws it.

What calls throw:

Exception When
ExecuServeException ExecuServe answered with an error. Branch on code; isRetryable covers rate limits, an overloaded or hot server, its per-request deadline and a client it dropped as too slow, retryAfterSeconds its Retry-After. An error inside a stream has afterStreamStarted = true, the stream's status 200 and no Retry-After.
ExecuServeUnreachableException Nothing listens at the address: ExecuServe is stopped or on another port.
ExecuServeProtocolException The answer was not ExecuServe's JSON; a required field was missing or of the wrong type (a chat's choices, message, content, finish reason and usage counts; a stream chunk's choices and delta; a model's id; a status's lane, admission and resident list, and its permissions when present); a redirect, which ExecuServe never sends and the client does not follow; or a stream closed before its finish and usage (the server failed after the reply began). Optional fields (a reply's id and model, timings) default when absent or malformed, and fields the client does not read are ignored.
another IOException A timeout, a reset, or the missing network security config.
CancellationException You cancelled.

With an OpenAI SDK instead:

val openai = OpenAIOkHttpClient.builder()
    .baseUrl(client.openAiBaseUrl)   // http://127.0.0.1:8080/v1
    .apiKey(apiKey)
    .build()

ExecuServe-only request fields go in as extra body properties, for example putAdditionalBodyProperty("chat_template_kwargs", JsonValue.from(mapOf("enable_thinking" to false))).

Speed

Measured from an app's process through this library, on a Snapdragon 8 Elite reference phone with the test model (Qwen3 0.6B, CPU, 4-bit weights, fp32 KV cache), streamed, greedy, 256-token replies, phone cooled to thermal status 0 before each request:

Prompt First token Decode Whole 256-token reply
32 tokens 40 ms 92 tok/s 2.8 s
~500 tokens 0.68 s 51 tok/s 5.7 s
~1,430 tokens 2.5 s 27 tok/s 12.2 s
a follow-up extending a ~1,370-token turn (1,375 tokens cached) 86 ms

The library and HTTP add 3 to 5 ms per request. Speed depends on the model, its export and the phone far more than on this client; see the measurement for method, raw data, heat, and an ExecuServe counting problem found on the way. Run it on your own phone with scripts/bench-on-phone.sh --model <id> after scripts/test-on-phone.sh.

Tests

Recorded results: 34 host tests passed for 0.1.1. A Snapdragon 8 Elite phone (Android 16) and an Android 12 emulator each passed 9 integration tests + 1 start-flow test.

# Host tests and public API dependency check
./gradlew :client:testDebugUnitTest :consumer-check:compileDebugKotlin

# Integration tests on a connected Android device
scripts/test-on-phone.sh --model /path/to/Model.pte

Setup and coverage · Device results and logs · Speed and latency

Layout

  • client/: the library.
  • consumer-check/: compiles the public API with nothing but :client.
  • sample/: a one-screen app that uses it, and the on-phone tests.
  • examples/local-chat/: a standalone app that uses the published Maven Central artifact.
  • scripts/test-on-phone.sh: the on-phone tests; scripts/check_run.py decides whether a run passed.
  • scripts/bench-on-phone.sh: speed and latency (LatencyBenchmark), summarised by scripts/summarize_bench.py.
  • docs/results/: what each run measured, with its raw output.
  • docs/showcase.md, docs/media/: the showcase video; scripts/showcase/ records and edits it.

License

Apache-2.0. Models keep their own licenses.

About

Android client for ExecuServe: use on-device models from another app.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages