Skip to content

[FEATURE] Vision annotation pipeline: let cheaper/text-only models understand screen and camera frames #895

Description

Summary

A general-purpose vision annotation pipeline so a cheaper model - text-only (DeepSeek, etc.) or weak-vision - can understand what a screen or camera sees. Three pieces:

  1. Pluggable annotator: a one-off side-call to any configured vision-capable model routed through the existing gateway (the same mechanism conversation-title generation already uses). Image in -> scene summary + numbered element list (label, text, bounding box) out. Source-agnostic: screenshots, robot camera frames, arbitrary images. The backend is just a provider/model string: a local VLM (e.g. ollama/qwen3-vl:4b, or FastVLM self-hosted behind an OpenAI-compatible server) or a cloud model (e.g. anthropic/claude-sonnet-5).
  2. Pull-based perception tool: the model asks for the latest frame from a named frame source - screen (the computer-use ring buffer) or a directory source (camera frames on disk, e.g. from a robotics camera daemon, with optional retention) - in regular (raw image) or annotated (structured text) form. Text-only sessions default to annotated automatically.
  3. ImageDecode tool (image -> text; naming consistent with ImageEdit/ImageGeneration/ImageVariation): the session model asks a question about any local image file - ImageDecode(image: <path>, prompt?: <question>). The annotator answers with a summary (or the answer to prompt) plus classifications - the same structured element list. This is what makes a text-only model like DeepSeek effectively vision-capable on demand.

No sidecar, no new protocol, no new dependencies.

Motivation

Today the CLI embeds images as base64 parts unconditionally:

  • GetLatestScreenshot returns the frame via ToolExecutionResult.Images, and createImageMessageFromToolResults (internal/agent/agent.go:1278) injects it as a hidden multipart user message without checking IsVisionModel - a text-only model receives a useless (and token-expensive) base64 blob.
  • User-attached images get only a soft warning (internal/handlers/chat_message_processor.go:72-84) and are sent anyway.
  • No code anywhere turns an image into text (no OCR, captioning, or element detection).

So none of the target loops can run on a cheap text-only planner today:

  • Computer use: the planner cannot perceive the screen at all.
  • Robotics / ambient camera: a camera daemon continuously writes frames to disk (with a retention policy); a cheap reasoning model - typically running headless under the heartbeat/scheduler/channels daemon - should be able to ask "what does the camera see right now". Same annotation need, different frame source. Worse: frame access is currently wired only in the chat TUI (cmd/chat.go:477 is the sole SetScreenshotServer call site), so headless infer agent has no frame access even for screens.
  • Image tools: ImageGeneration/ImageEdit/ImageVariation write their results to .infer/tmp, and @-referenced images are passed as paths by design (no inlined bytes) - so a text-only planner cannot inspect or verify what it just produced, and cannot author region masks for ImageEdit ([FEATURE] Add optional mask parameter to the ImageEdit tool #988) without a way to see the image.

GUI-agent research (Set-of-Mark prompting, OmniParser, M3A, UI-TARS) converged on the answer this issue adopts: give the planner a numbered element list (index, label, text, bounding box) plus a short scene summary, and resolve indices/coordinates to actions in post-processing - the planner never does pixel math. The same structure describes a warehouse camera frame just as well as a login form.

Proposed design

1. Frame sources (refactor: generalize ScreenshotProvider)

domain.ScreenshotProvider (internal/domain/interfaces.go:57) is already the right single-method shape, just screen-named and chat-only. Rename it:

type FrameSource interface {
    GetLatestFrame() (*Frame, error) // Frame = today's domain.Screenshot struct, renamed
}

Implementations:

  • screen - the existing ScreenshotServer/circular buffer (internal/services/screenshot_server.go), registered when computer_use.enabled && screenshot.streaming_enabled. Rename-only refactor.
  • directory (new) - for robotics and anything else that drops frames on disk: returns the newest image file (same extension set as ImageService: png/jpg/jpeg/gif/webp) under a configured path, loaded via the existing internal/services/image_service.go. Optional retention enforcement (max_files / max_age sweep of that directory, opt-in - omit it if the camera daemon already manages cleanup). This covers any camera pipeline without binding the CLI to camera SDKs.

A named-source registry (map[string]domain.FrameSource) lives in the service container and is wired for both chat and headless infer agent - fixing the chat-only wiring gap, which is a hard requirement for robotics (those loops run headless under the channels-manager/heartbeat daemon).

2. Perception tools

Replace the existing zero-parameter GetLatestScreenshot (internal/agent/tools/get_latest_screenshot.go) with one general frame tool, plus a decode tool for arbitrary images:

  • GetLatestFrame(source?: string, format?: "regular" | "annotated") - registered whenever at least one frame source exists. source defaults to the only configured source (or screen when present). format omitted -> resolved automatically: annotated iff the annotator is configured and the session model is not vision-capable (the tool reads the session model from context via domain.GetModel(ctx), already populated every turn); otherwise regular. For text-only sessions the base64 attachment is omitted entirely.
  • GetLatestScreenshot is removed, not aliased. Pre-stable (0.x), it is wired only in the chat TUI and effectively unused; a compat shim would be maintenance for nobody. This ships as a breaking change (feat!), renaming the tool everywhere it appears (registry, IsComputerUseTool bypass list, prompts.yaml description key, docs).
  • The existing min-interval rate limiter and IsComputerUseTool approval bypass carry over; directory-source reads are read-only.
  • ImageDecode(image: string, prompt?: string) (new) - the on-demand counterpart for arbitrary local images: image-tool outputs under .infer/tmp, @-referenced files, downloaded artifacts. Same annotator service and strict-JSON contract; when prompt is given it is passed through so the returned summary answers the model's question - the classified element list (label, text, bbox) is returned either way. Validation reuses ImageService.IsImageFile; read-only; registered whenever vision.annotator is configured.

One parameterized frame tool rather than per-source or per-format tools: the auto-default only works reliably in one place (a text-only model cannot be trusted to pick the right tool from a description), and it keeps prompts.yaml descriptions, approval-bypass lists, and registry wiring to a single entry.

Annotated output rendered for the LLM - screen source:

Frame summary: Login form of the Acme dashboard, username field focused.
Elements:
1. text_field "Username" - center (512,300) bbox [400,280,624,320]
2. text_field "Password" - center (512,360) bbox [400,340,624,380]
3. button "Sign in" - center (512,420) bbox [470,402,554,438]
To interact: pass an element's center (x,y) to MouseClick.

Directory (camera) source:

Frame summary: Warehouse aisle; a person walking toward the loading dock, forklift parked on the left.
Elements:
1. person - center (412,300) bbox [372,180,452,420]
2. forklift - center (150,340) bbox [60,260,240,420]

Coordinates need no new plumbing: screen frames are already downscaled to screenshot.target_width x target_height (default 1024x768), which is exactly the space MouseClick/MouseMove accept before ScaleAPIToScreen (internal/agent/tools/coordinate_scaler.go) - so element centers are directly clickable. Camera-frame coordinates are in the frame's own pixel space (informational, or for the robot's own actuation mapping).

3. Annotator: side-call to a configured vision model (no sidecar)

New internal/services/image_annotator.go, modeled 1:1 on conversation_title_generator.go (generateTitle, lines 129-194): shared sdk.Client from the container, provider/model split on /, WithOptions(&{MaxTokens}).WithMiddlewareOptions(&{SkipMCP: true}).GenerateContent(...); user message = short instruction + one image content part (sdk.NewImageContentPart, same composition as agent.go:1298).

  • Interface in internal/domain (required by the existing services -> tools import direction; follows the domain.ScreenshotProvider convention; triggers the standard counterfeiter mock regen):

    AnnotateImage(ctx context.Context, img ImageAttachment, opts AnnotateOptions) (*ImageAnnotation, error)
    // AnnotateOptions{Prompt string; Width, Height int}   // Prompt: per-source override
    // ImageAnnotation{Summary string; Elements []AnnotatedElement}
    // AnnotatedElement{Index int; Label, Text string; BBox [4]int}
  • Prompt contract: strict JSON {"summary": "...", "elements": [{"index": 1, "label": "button", "text": "Sign in", "bbox": [x1, y1, x2, y2]}]} with the image's width/height stated in the prompt. The parser strips code fences; on parse failure it degrades to ImageAnnotation{Summary: rawText} - it never fails the tool call.

  • Two built-in system prompts (prompts.yaml, mirroring Conversation.TitleGeneration.SystemPrompt): UI-element detection for the screen source, general scene/object description for everything else; each directory source can override with its own prompt.

Deployment is just model registration - vision.annotator.model is an ordinary provider/model string routed through the gateway, so the backend is a pure config choice:

  • Local: every mainstream runtime (Ollama, llama.cpp llama-server, LM Studio, vLLM, mlx-based servers) exposes OpenAI-compatible vision endpoints. Recommended documented example: ollama/qwen3-vl:4b (Apache-2.0, native bounding-box grounding). FastVLM works here too, self-hosted behind an OpenAI-compatible server (weights are research-only licensed - see the rejected-sidecar note below).
  • Cloud: any hosted vision model, e.g. anthropic/claude-sonnet-5 or openai/gpt-5.2 - identical code path, no special casing.

4. Config (config.yaml - the pipeline is not a computer-use concern)

vision:
  annotator:
    enabled: false
    model: "" # provider/model, e.g. ollama/qwen3-vl:4b - any vision model reachable through the gateway
    max_tokens: 1024
  sources:
    camera-front:
      type: directory
      path: ~/frames/front
      prompt: "" # optional per-source annotation instruction override
      retention: # optional; omit if the camera daemon manages cleanup
        max_files: 500
        max_age: 24h

The screen source keeps its existing configuration in computer_use.yaml and is registered implicitly. Annotator system prompts live in prompts.yaml like every other prompt (config/prompts.go); the tool description there documents sources and formats.

5. Fallback semantics

  • Annotator unconfigured or disabled: the auto-default never fires; an explicit format=annotated degrades to a regular frame plus a note ("annotation unavailable: set vision.annotator.model"). For a text-only session it returns the frame metadata plus "[image omitted: model has no vision; configure vision.annotator to enable annotated frames]".
  • Annotator errors at runtime: same graceful degrade. A broken annotator must never strand a session.

6. IsVisionModel fixes (enabler)

The auto-default gate is IsVisionModel (internal/services/model.go:178), a case-insensitive substring match against a hardcoded pattern list (model.go:15-40) that is stale in a way that matters here: "qwen-vl" does not match qwen3-vl, so the recommended annotator-class models are misclassified as text-only. Move it into internal/domain as a pure function (required by the import direction anyway; HTTPModelService.IsVisionModel delegates), refresh the patterns, and add an additive config override (extra patterns appended to built-ins) so users can extend the list without waiting for a release.

End-to-end robotics flow (target)

  1. A camera daemon writes frames to ~/frames/front (retention via its own policy or vision.sources.camera-front.retention).
  2. The heartbeat daemon fires infer agent on its interval (headless - sources now wired there too).
  3. The agent (e.g. DeepSeek) calls GetLatestFrame(source="camera-front"); format auto-resolves to annotated.
  4. The annotator (small local VLM through the gateway) returns the summary + element list as text.
  5. The agent reasons over it and acts (notify a channel, call an A2A agent, schedule follow-up).

Phased plan

Phase 1 - Perception pipeline on the screen source (breaking: replaces GetLatestScreenshot)

  • internal/domain: rename ScreenshotProvider/Screenshot -> FrameSource/Frame (ScreenshotServer implements it unchanged); add ImageAnnotation/AnnotatedElement types + ImageAnnotator interface; move IsVisionModel to domain as a pure function with refreshed patterns (one mock regen for all of it)
  • internal/services/image_annotator.go: side-call service, strict-JSON parse with raw-text degrade
  • GetLatestFrame tool replaces get_latest_screenshot.go: source + format params, auto-default from session model, attachment omission for text-only models, graceful-degrade notes; rename in the registry, IsComputerUseTool bypass list, and prompts.yaml
  • ImageDecode tool: arbitrary local image + optional question -> summary/answer + classifications (prompts.yaml description; unit tests with fake annotator + fake image service)
  • Config: vision.annotator in config/config.go + prompts (two system prompts, new tool description)
  • Named-source registry in the container (screen from the existing ScreenshotServer), wired in chat and headless agent (fixes the chat-only gap at cmd/chat.go:477)
  • Tests: tool unit tests (fake annotator + fake source; explicit/auto/unconfigured/failing; attachment omission), annotator unit tests (fake SDK client: clean JSON / fenced JSON / garbage degrade / bad model format), headless registration test, one mock-gateway scenario + integration test driving format=annotated

Phase 2 - Camera/directory sources (robotics)

  • directory source: newest-image-by-mtime + optional retention sweep (max_files/max_age)
  • vision.sources config (config/config.go) + per-source prompt override
  • Tests: directory source unit tests (selection, empty dir, retention sweep), camera-flavored mock-gateway scenario

Phase 3 - Auto-annotation for images the model did not ask for

  • Gate createImageMessageFromToolResults (agent.go:1278) on IsVisionModel: text-only -> annotation text (or an "[image omitted...]" note when unconfigured) instead of unconditional base64 - this also makes Read on an image file readable for text-only models for free
  • Upgrade the soft warning in chat_message_processor.go: when the session model is not vision-capable, user-attached images are decoded automatically through the annotator (same path as ImageDecode) and the resulting summary + classifications replace the base64 part - covers clipboard paste ([Image 1] annotations), @path references, and --files, which all merge into one list at chat_message_processor.go:70. Vision models keep receiving the raw image as today.
  • Additive vision-model config patterns
  • Tests: gating unit tests; mock-gateway scenario asserting no image parts reach a text-only request

Follow-ups (separate issues, not committed here)

  • Set-of-Mark overlay (format=marked: numbered boxes drawn on the frame with stdlib image/draw) for weak-vision models
  • Click-by-element-index (session element cache + MouseClick element param)
  • Alternative annotator backends: macOS accessibility (AX) tree (exact and VLM-free, native apps only), OmniParser V2 endpoint (best-in-class UI parsing, but its icon detector is AGPL - external opt-in service only, never embedded or redistributed)
  • Native camera capture drivers (V4L2/RTSP) only if directory sources prove insufficient
  • Auto-generate ImageEdit masks from ImageDecode grounding output (bounding boxes -> transparent-region mask PNG) - unblocks region-targeted edits for text-only planners ([FEATURE] Add optional mask parameter to the ImageEdit tool #988)

Explicitly out of scope / rejected

  • FastVLM sidecar, ghcr.io/inference-gateway/fastvlm image, sidecar lifecycle management, custom annotation REST protocol - unnecessary (OpenAI-compatible vision endpoints are ubiquitous) and undistributable: FastVLM's weights ship under Apple's ML Research Model License (research-only, non-commercial, revocable), not "MIT-style" as previously stated here. FastVLM remains usable by self-hosting it behind an OpenAI-compatible server for research use.
  • Annotation caching / perceptual hashing - the ring buffer, the tool's min-interval rate limit, and pull-based semantics already bound annotator calls; add caching only if real usage shows cost.
  • Camera SDK integrations - the directory contract (files on disk) is the integration surface.
  • New VisionManager subsystem, streaming region diffs, OCR-only pipeline, new Go dependencies.

Open questions

  1. Force-annotation for vision-capable-but-poor-grounding models (annotator.auto: always | text_only | never)? v1 proposal: text-only detection only; explicit format=annotated is the manual escape hatch.
  2. Retention ownership: should the CLI's optional sweep be the recommended default, or should camera daemons own cleanup and the sweep stay strictly opt-in (current proposal)?
  3. Is ollama/qwen3-vl:4b the right documented default example for the annotator?

References

Activity

  1. changed the title [-]feat: VLM-based image annotation pipeline (FastVLM) for text-only model support[/-] [+][FEATURE] Vision annotation pipeline: let cheaper/text-only models understand screen and camera frames[/+] on Jul 13, 2026
  2. moved this to Todo in 2026on Jul 13, 2026
  3. moved this from Todo to QA in 2026on Aug 2, 2026
  4. inference-gateway-releaser commented on Aug 3, 2026

    @inference-gateway-releaser
    Contributor

    🎉 This issue has been resolved in version 0.159.0 🎉

    The release is available on:

    Your semantic-release bot 📦🚀

  5. moved this from QA to Done in 2026on Aug 4, 2026
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

    enhancementreleased

    Projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions