Skip to content

Design: on-device multimodal agent execution via OpenAI-compatible local providers (Gemma 4 E4B) #177

Open

Description

@banggaoo

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

  1. OpenAI-compatible adapter, not a bespoke SDK. All agents already speak through ChatOpenAI; a local server exposing /v1/chat/completions plugs in with zero agent-side changes. ModelProvider.CUSTOM covers any conforming server.

  2. Structured output via function_calling, not strict JSON schema. Small local providers commonly reject response_format: {strict: true}. Tool-schema calls are the portable path (services/llm.py).

  3. MIME sniffing on the wire. Simulators/drivers emit PNG bytes even for .jpg paths; strict gateways reject image/jpeg labels on PNG content. artemis/utils/image_codec.py sniffs magic bytes at every send site.

  4. 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).

  5. ARTEMIS operates the model itself. artemis model pull/serve/stop manages mlx_vlm.server as a background process (optional local extra, Apple Silicon); a diagnostics probe detects missing models at startup and emits guided artemis 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.

  6. 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

  1. 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.
  2. 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 (launch not open; 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 model catalog (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

  1. banggaoo commented on Oct 10, 2026

    @banggaoo
    Author

    Update — PR #176 now covers the full local-model path end to end:

    Landed since last update

    • artemis model pull/serve/status/stop/list — managed mlx_vlm.server lifecycle for catalog aliases; serve applies the 1120 vision soft-token budget
    • Image-first ordering normalized at the remaining text-first multimodal call sites (planner, checker, explorer, flash runner, committee, outputter, history, pixel validator)
    • mark_done completion affordance for the Pro/operator loop: structural claim → convergence gate → settlement verification; false claims bounce back to execution
    • Plans with all top-level items resolved ([x] or [!] blocked) now route to settlement — a fully-blocked plan terminates instead of looping
    • Console setup wizard: Local Model Endpoint card with click-to-run pull/serve/stop (loopback-guarded, alias-validated subprocess endpoints, live log tail), copyable fallback for BYO OpenAI-compatible servers
    • docs/local_models.md: install → pull → serve → verify → run flow

    Measured grounding status (gemma4-e4b, 1120 tokens, live sim screenshot via detector path)

    • Present elements: 4/4 pixel-accurate centers (Select pill, search icon, Library/Collections tabs)
    • Absent elements: 3/5 clean refusals; 2/5 "lookalike decoy" misses (pointed at semantically-similar element instead of refusing) — the remaining failure mode targeted by fine-tune data
  2. banggaoo commented on Oct 10, 2026

    @banggaoo
    Author

    Live Android verification on feat/gemma4-upstream (emulator-5554, API 36):

    • Session aaf5e5f8: Flash + local Gemma endpoint — observed screen, confirmed goal state, report_task_status(completed) → PASS
    • Session 17fe2324: Open the Settings app from home — Gemma selected click(target=17, 'Settings icon'), tap executed via ADB (910,1970), verified result, report_task_status(completed) → PASS. mCurrentFocus=com.android.settings confirmed on-device.
    • Endpoint smoke: text-only ~7s, screenshot+prompt ~2.6s on direct mlx_vlm.server.
    • Note: local inference on this box occasionally exceeded the default 180s per-call cap under memory pressure; LLM_FLASH_HARD_TIMEOUT_SECONDS covers slow local providers.
  3. banggaoo commented on Oct 10, 2026

    @banggaoo
    Author

    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):

    • Local VLM servers can wrap the model's call:name{args} envelope into a function literally named "call" with unparseable args (mlx_vlm/Gemma 4 quirk) — calls are now recovered from invalid_tool_calls and from call: text envelopes.
    • A narration-only streak previously looped forever under max_turns=0; the loop now fails bounded after 8 consecutive no-tool-call turns.
    • tool_choice="required" is set for custom OpenAI-compatible providers — eliminated the narration-loop failure mode observed with Gemma 4 E4B.
  4. banggaoo commented on Oct 16, 2026

    @banggaoo
    Author

    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:

    1. Plan — Gemma produces a goal-path plan grounded on the first screenshot + UI hierarchy (no blind planning).
    2. Describe — each turn, Gemma describes the current screen, checks stateful control state, and emits TARGET: visible / not-visible / reached.
    3. Decide — Laya picks one action from a fixed menu (indexed taps + swipe/back/home/wait/done/fail), with goal, plan, description, last-action outcome, and repeat notices as its state.
    4. Verify — low-confidence, unavailable, navigation-sensitive, and terminal decisions escalate to the standard VLM tool-calling path; TARGET: reached routes 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 like settings get) audits the final screen/UI against the goal:

    • Released → normal completion.
    • Rejected → verdicts fed back as a tool result; the agent gets another turn with ground truth.
    • Budget exhausted (final_check_max_attempts) → finalized as failed.
    • Checker errors fail-open; honors final_check_enabled / checkpoint_timeout / disable_checker.

    This caught the motivating bug class: an earlier run reported "Dark theme enabled" while ui_night_mode stayed 1. 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)

    • Stateful controls indexed — Switch rows surface as Control: 'Switch (on/off)' with live state, so toggles are verifiable rather than tapped blind.
    • Dead-tap masking — only taps that produced no screen change are masked; navigation taps aren't erased from the menu.
    • Verbatim suppression — an identical call set on an unchanged screen gets an error ToolMessage ("not re-run") + named navigation alternatives instead of another dead tap.
    • Ping-pong detection — re-issuing turn N−2's call on a matching screen raises an "alternating between two screens" notice.
    • Hard stop — a third verbatim re-issue of a suppressed call ends the task as an honest failure (observed: 30+ turns of the same suppressed click before this).
    • Degenerate-hierarchy retry — a status-bar-only window set while an app is foreground re-snapshots once after 600 ms.
    • Same-turn re-ask — narration-without-tool-call turns get pushed once; mlx_vlm intermittently ignores 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 expose clickable=false, so they never reach the element menu.

    Tests

    • Full suite: 2635 passed, 9 skipped (GOOGLE_API_KEY=dummy — tests construct ChatGoogleGenerativeAI at import).
    • Agent-focused: 561 passed.

    All model lifecycle stays under artemis model ... (pull/serve/status/stop/list); the managed laya alias spins up a dedicated laya-serve venv.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions