Repository navigation
Description
Motivation
ARTEMIS's roadmap calls for on-device lightweight VLMs — local execution of small edge vision models for low-latency, privacy-first automation. This issue documents the design and architecture behind PR #176, which implements that item: the full agent loop (perception → planning → action → verification) running against a local OpenAI-compatible server hosting Gemma 4 E4B (4-bit MLX, ~6 GB resident).
Architecture
┌─────────────────────────── ARTEMIS ───────────────────────────┐
│ Flash runner Pro graph: Planner → Operator → Checker │
│ │ │ (bind_tools / with_structured) │
│ └────── services/llm.py ── ChatOpenAI ─────────────────┤
│ │ OpenAI-compatible HTTP │
└──────────────────────────┼─────────────────────────────────────┘
▼
┌──────────── local OpenAI-compatible server (e.g. MLX) ────────┐
│ /v1/chat/completions · tool schemas · image_url inputs │
│ gemma4-e4b (vision + reasoning, 4-bit, single process) │
└────────────────────────────────────────────────────────────────┘
▲
Screenshots, OCR text, UI hierarchy ── perception layer feeds
the same OpenAI multimodal message format regardless of backend.
One capable local multimodal model serves operation, visual grounding, and screen understanding — no separate detector/VLM split required.
Design decisions
-
OpenAI-compatible adapter, not a bespoke SDK. All agents already speak through
ChatOpenAI; a local server exposing/v1/chat/completionsplugs in with zero agent-side changes.ModelProvider.CUSTOMcovers any conforming server. -
Structured output via
function_calling, not strict JSON schema. Small local providers commonly rejectresponse_format: {strict: true}. Tool-schema calls are the portable path (services/llm.py). -
MIME sniffing on the wire. Simulators/drivers emit PNG bytes even for
.jpgpaths; strict gateways rejectimage/jpeglabels on PNG content.artemis/utils/image_codec.pysniffs magic bytes at every send site. -
Bounded context for small models. A 4B model's effective attention window is narrow: protocol rules are repeated as focus reminders adjacent to the latest turn, injected sections are budget-bounded, and Flash prunes intermediate screenshots (providers cap images-per-request).
-
ARTEMIS operates the model itself.
artemis model pull/serve/stopmanagesmlx_vlm.serveras a background process (optionallocalextra, Apple Silicon); a diagnostics probe detects missing models at startup and emits guidedartemis model pull/serve <alias>actions instead of failing mid-task. BYO OpenAI-compatible servers (Ollama, vLLM, …) work identically — remediation falls back to generic hints for non-catalog aliases. -
Apple Vision OCR where native. On macOS, OCR runs through Vision directly; other platforms skip it. OCR feeds perception, not prompts — no prompt growth.
Known limitation
E4B's termination discipline is the residual risk: it can recognize the goal is met yet continue deliberating instead of settling [x] milestones and ending the turn. A mark_done affordance or stable-screen loop detector is the natural follow-up — interested in maintainer input on which fits the codebase's conventions.
Scope
PR #176 — 45 files, +2128/−90. No iOS/device-driver changes; device drivers are orthogonal.
Next milestone: fine-tune Gemma for ARTEMIS
Measured on a 10-task iOS eval (gemma4-e4b, live runs): 80% goal completion, 60% self-termination, 0% infeasibility detection — the model executes well but can't reliably stop, give up, or verify its own detections. Prompt-side fixes (focus reminders, bounded context) help but carry a cost: ~11K-token operator prompts at ~50 s/step.
Fine-tuning targets both directions at once:
Objectives
- Shrink the prompt. Today ~11K tokens/operator call is mostly instructions — tool protocol, ledger rules, action grammar, reminders re-taught every turn. Baking these into weights should let the prompt drop to goal+observation (~2–3K tokens): faster prefill, more of the small context window left for actual screen state.
- Fix the measured weaknesses. Train specifically on: settling
[x]+ ending the turn when the goal is met; declaring infeasibility when the target doesn't exist (App Store run: 14 steps, 1379 s, never gave up); rejecting hallucinated detections (E4B reported an "App Store icon" that wasn't there); exact tool-arg schemas (launchnotopen; no Android keycodes on iOS).
Method sketch
- Data: ARTEMIS's own execution traces are already (prompt → response → action-outcome) triples — successful trajectories become SFT positives; the measured failure classes (termination loops, infeasibility loops, bad args) become corrected negative→positive rewrites.
- Technique: LoRA/QLoRA SFT on the same 4-bit E4B deployment (keeps the ~6 GB footprint); optionally GRPO-style preference on done-vs-continue turns later.
- Eval: reuse the task suite from this milestone — same metrics, so improvement is measured not felt: self-termination %, infeasibility detection, tool-arg validity, steps-to-goal, prompt tokens/call.
Open questions for maintainers
- Ship tuned weights as an HF repo alias in the
artemis modelcatalog (gemma4-e4b-artemis), or an adapter on top of base E4B? - Acceptance bar for swapping the default alias — e.g. ≥95% self-termination on the eval suite?
Update: vision-token budget matters more than input resolution
Measured on the iOS grounding suite (5 present + 3 absent targets): the shipped max_soft_tokens=280 downsamples a phone screenshot to ~528×1152 effective and produced wrong-thumbnail taps, echoed coordinates, and lookalike-anchored detections of absent elements (App Store → pointed at Collections). At 1120 soft tokens (the model's supported max; ~near-original detail, +840 prompt tokens/image) the same suite went 8/8 — including correct [] refusals for absent targets. artemis model serve now applies it by default (--vision-tokens to override). Fine-tuning should train at the higher budget.
Activity
banggaoo commentedon Oct 10, 2026
Update — PR #176 now covers the full local-model path end to end:
Landed since last update
artemis model pull/serve/status/stop/list— managedmlx_vlm.serverlifecycle for catalog aliases;serveapplies the 1120 vision soft-token budgetmark_donecompletion affordance for the Pro/operator loop: structural claim → convergence gate → settlement verification; false claims bounce back to execution[x]or[!]blocked) now route to settlement — a fully-blocked plan terminates instead of loopingdocs/local_models.md: install → pull → serve → verify → run flowMeasured grounding status (gemma4-e4b, 1120 tokens, live sim screenshot via detector path)
banggaoo commentedon Oct 10, 2026
Live Android verification on
feat/gemma4-upstream(emulator-5554, API 36):aaf5e5f8: Flash + local Gemma endpoint — observed screen, confirmed goal state,report_task_status(completed)→ PASS17fe2324:Open the Settings appfrom home — Gemma selectedclick(target=17, 'Settings icon'), tap executed via ADB (910,1970), verified result,report_task_status(completed)→ PASS.mCurrentFocus=com.android.settingsconfirmed on-device.mlx_vlm.server.LLM_FLASH_HARD_TIMEOUT_SECONDScovers slow local providers.banggaoo commentedon Oct 10, 2026
Complex multi-step live test (emulator-5554, session f0dc8f01): "Open Settings, navigate to Display & touch, and turn on Dark theme" — PASS in 7 turns: click Settings → click Display & touch → toggle Dark theme → verified → report_task_status(completed). ui_night_mode=2 confirmed on-device.
Two defects found and fixed in e118e48 (Flash hardening):
banggaoo commentedon Oct 16, 2026
Update — the PR now includes the hybrid Flash/Laya decision loop and terminal-boundary verification, validated live on Android (emulator-5554, API 36) with a 100-task complex batch currently running.
Hybrid Flash architecture (new since last update)
Gemma/VLM now leads UI perception while Laya handles fast in-screen action selection:
TARGET: visible / not-visible / reached.TARGET: reachedroutes to a verification turn rather than terminating directly.XML/accessibility bounds stay deterministic; Gemma may supply normalized coords only as a fallback for elements missing from XML.
Terminal verification gate
report_task_status(completed)no longer ends a task on the model's word. The existing Pro checker (run_final_check+ enumerated read-only probes likesettings get) audits the final screen/UI against the goal:final_check_max_attempts) → finalized as failed.final_check_enabled/checkpoint_timeout/disable_checker.This caught the motivating bug class: an earlier run reported "Dark theme enabled" while
ui_night_modestayed1. It also means a state that is true-but-visually-delayed (e.g. sunset schedule) is decided by probes, not pixels.Loop hardening (driven by live failures)
Control: 'Switch (on/off)'with live state, so toggles are verifiable rather than tapped blind.tool_choice="required".Live batch results (in progress)
100 complex Settings/app goals queued serially. Early tally: 5 completed / 6 failed / 2 cancelled (restart casualties, re-queued) after ~2h. Completed tasks were checker-verified against ground truth (e.g.
airplane_mode_on=0,ui_night_mode=2,Wi-Fi is enabled). Failures so far are honest failures — e.g. Adaptive brightness lives inside a SystemUI dialog whose controls exposeclickable=false, so they never reach the element menu.Tests
GOOGLE_API_KEY=dummy— tests constructChatGoogleGenerativeAIat import).All model lifecycle stays under
artemis model ...(pull/serve/status/stop/list); the managedlayaalias spins up a dedicatedlaya-servevenv.