Skip to content

Return images from tools on native llama.cpp (#1008) - #1462

Merged
leehack merged 6 commits into
mainfrom
feat/1008-multimodal-tool-results
Oct 27, 2026
Merged

leehack merged 6 commits into
mainfrom
feat/1008-multimodal-tool-results

Conversation

@leehack

@leehack leehack commented Oct 27, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Tools can return images: LlamaToolResultContent gains ordered content parts and handlers or onToolCall can return LlamaToolOutput(output:, content:). ChatSession.sendWithTools/completeWithTools store it as a typed result. A LlamaToolOutput passed as result in a manual loop throws LlamaArgumentException; the docs show how to unwrap it.
  • The tool turn renders as llama-server 620d2225c renders an array tool message ([result text] + content, text joined by \n, a marker at each image, no newline around markers). As upstream, the parts are joined only when they carry media; text-only parts reach typed-content templates typed (Qwen3-VL gets abcx), and string-only templates joined by \n. Images go to llama.cpp in prompt order. toJson emits the llama-server array shape.
  • LlamaEngineCapabilities.toolResultMedia (LlamaToolResultMedia {image, audio}) reports {image} for native llama.cpp with a vision projector and a model template in a qualified format. The new backend SPI BackendToolResultMedia (in package:llamadart/backend.dart) declares what a backend places; LlamaCppBackend declares images and NativeAutoBackend delegates.
  • Qualification follows the maintainer decision ("qualify image tool results first on Qwen3-VL"): the Hermes <tool_call> format carries a rendersToolResultContent registry trait. It is the only format with the trait.

Refs #1008. Does not close it: Qwen3-VL weights were not available here, and the tools-pack case on real Qwen3-VL is still open (see below).

Production-readiness scope

Completeness checklist

  • Declared scope is fully implemented, or explicitly reduced above.
  • Unsupported platform/option combinations fail loudly with actionable diagnostics or are clearly documented as unavailable.
  • Public API docs, README/website docs, examples, support matrices, and changelog entries are updated where relevant.
  • Regression coverage covers the original issue plus key negative/version-skew paths where relevant.
  • Public capability changes update the validation coverage registry with a pack or a reasoned, issue-linked exemption; inventory checks pass (or N/A with scope).
  • Security/privacy review completed: no secrets, bearer tokens, signed URLs, or raw secret-bearing paths leak through logs, cache keys, metadata, errors, or snapshots. URL-only image refusals do not echo the URL; a test pins it.
  • Follow-up work that is useful but not required for this PR is tracked in GitHub Issues, or explicitly marked "None" above. The pre-existing multimodal grammar bug (Native multimodal requests with tools force a tool call (no lazy grammar triggers on the multimodal render path) #1463) is fixed on main by Render media requests through the format handler so tool grammars stay lazy #1464.

PR type guidance

  • Feature PR: API + Dartdoc (exported from lib/llamadart.dart, SPI from lib/backend.dart), README, tool-calling/multimodal/generation guides, support matrix row, basic_app README, both changelogs, both SKILL.md files, testing matrix, and a local-only scenario. Happy and negative paths are tested.
  • Bugfix PR: N/A, feature.
  • Docs-only PR: N/A.

Test Plan

  • dart run tool/prepare_workspace.dart
  • dart format --output=none --set-exit-if-changed .
  • dart analyze
  • dart test -p vm -j 1 --exclude-tags local-only
  • dart test -p chrome --exclude-tags local-only
  • Other targeted/local-only validation: tool-result-image-smoke (CPU and Metal), ./tool/testing/run_template_parity_suites.sh, dart test -p vm test/unit/tooling/, docs build.

Matrix Evidence

Matrix row Scope covered Platform / model / backend Result Evidence / notes
root-vm full VM suite incl. new render/engine/tool-loop tests macOS arm64, VM PASS -j 1 --exclude-tags local-only: +8611 ~5 at 0cc98e5; at c417f1f test/unit/core, test/unit/tooling, test/unit/backends/{llama_cpp,native}: +6339 ~5, all passed; full suite in CI
root-chrome Chrome suite macOS arm64, Chrome PASS +3870 ~1 at 0cc98e5; touched Chrome-eligible tests pass at e6d49db; full suite in CI
tool-result-image-smoke real model reads tool-turn photos; handler LlamaToolOutput photo reaches the next sendWithTools round macOS arm64, Qwen3.5-0.8B-Q4_K_M (bd258782…) + mmproj F16 (56e4c6cf…, qwen3vl_merger), Qwen3-VL-2B-Instruct template (3636d0f0…), llama.cpp CPU and Metal PASS At c417f1f, CPU and Metal. Red/blue history: The main color of the photo is **Red**. / **blue**.; tool loop per color: 1 call, completed, The main color of the photo is red. / ... blue. History texts are identical to llama-server 620d2225c on the same prompts. Closest family only: Qwen3-VL weights unavailable.
structured-output-adversarial template/parser parity for touched render path VM PASS ./tool/testing/run_template_parity_suites.sh: all passed at c417f1f
high-risk-exact-head-independent-qa independent audit c417f1f40 / 41b9f33a7 PASS CLEAR at 0cc98e5 (one P2, fixed) and delta re-audit CLEAR at c417f1f: Qwen3-VL 32/32 byte-identical to llama-server 620d2225c, 1132/1132 no-regression cases identical to base, real model 5/5 CPU+Metal, 38/44 mutants killed (survivors equivalent or P3). Evidence llamadart-evidence/pr-1462/r2/evidence-1462-c417f1f.json; high_risk_readiness.dart exits 2.

Upstream emissions: test/fixtures/qwen3_vl_tool_media_upstream.{json,md} (/apply-template, LLAMA_MEDIA_MARKER=<__media__>, two media cases: multiple results with text+image and image-only; user image then tool image with text after; two text-only cases: Qwen3-VL typed abcx and Qwen3-4B string-only abc\nx, captured from Homebrew llama-server b11669-620d2225c). Rendering through ChatTemplateEngine.render and LlamaEngine.chatTemplate is byte-identical to them.

Mutation check (each mutant fails the named tests; all restored):

Mutant Killed by
Hermes rendersToolResultContent off 19 tests (parity, capability, refusals)
Newline before a marker 13 tests (upstream prompt parity)
Planner drops nested media 5 tests (prompt-order dispatch, tool loop)
Engine skips modality gate refusal: image on a backend that places none
Nested media take the typed-content render tool-result media keep the Hermes lazy tool grammar
Marker-count check skipped drop/repeat template tests
Tool loop ignores LlamaToolOutput handler and onToolCall loop tests
Capability ignores template format is empty for a template format not qualified
Native-chat backends accept content backends that take chat natively refuse text content
URL-only image accepted URL refusal tests (engine and unit)
content not flattened 15 tests
LlamaCppBackend declares no media places only images at tool-result markers
toJson keeps the raw result tool result with content is llama-server array content
Text-only parts joined anyway (toolResultWithMediaMarkers) returns a result without media unchanged
Text-only parts always joined / never joined text-only upstream parity (typed / string-only case)
Handler ignores typed-content support string-only parity case
Capability ignores projector audio reports audio only when the projector takes audio
LlamaToolOutput result accepted rejects a LlamaToolOutput result

One equivalent mutant: the render-context fast path for text-only content (the inner helper returns the same result).

Review Notes

High-risk regression review

  • Classification: high-risk (backendRuntime, regressionPolicy, structuredOutput)
  • Implementation task: Design multimodal tool-result content with preserved tool identity #1008 lane (this PR)
  • Independent blocking QA task: CLEAR at 0cc98e5; delta re-audit CLEAR at c417f1f
  • Exact head / current base: c417f1f / 41b9f33
  • Production-branch deletion, bypass, or miswire proof: mutation table above
  • Affected-family real-model/artifact evidence: closest family Qwen3.5-0.8B with the qwen3vl_merger projector, running the pinned Qwen3-VL template, plus llama-server 620d2225c emissions
  • Explicit unavailable-family or other N/A evidence: Qwen3-VL GGUF weights unavailable locally (not downloaded); primary upstream emissions + durable fixtures used
  • Known PR-caused P1 regressions: 0
  • Unresolved review threads: 0

leehack and others added 2 commits October 27, 2026 10:40
Add LlamaToolResultContent.content, LlamaToolOutput and
LlamaEngineCapabilities.toolResultMedia. Hermes-format tool turns render
as llama-server 620d2225c does, with media at their markers in prompt
order; qualified on Qwen3-VL. Other formats, runtimes, audio, video and
URL-only images throw LlamaUnsupportedException.

Co-Authored-By: Claude <noreply@anthropic.com>
They read upstream fixture files.

Co-Authored-By: Claude <noreply@anthropic.com>
…/1008-multimodal-tool-results

# Conflicts:
#	lib/src/core/engine/engine.dart
…esult

llama.cpp joins tool-result parts into one string only when they carry
media; text-only parts stay typed for typed-content templates (fixture from
llama-server 620d2225). A LlamaToolOutput passed as result now throws, and
the tool-calling docs show how to unwrap it in a manual loop. Adds the audio
projector guard test, a red and blue tool-loop E2E, and passes
LLAMADART_TOOL_MEDIA_CHAT_TEMPLATE through the smoke scenario.
@leehack
leehack marked this pull request as ready for review October 27, 2026 17:53
@leehack
leehack merged commit 63a2b3f into main Oct 27, 2026
39 checks passed
@leehack
leehack deleted the feat/1008-multimodal-tool-results branch October 27, 2026 17:53
@github-actions

Copy link
Copy Markdown
Contributor

Chat app preview removed for leehack/llamadart-chat-pr-1462.

leehack added a commit that referenced this pull request Nov 26, 2026
## Summary
- Map Genkit `MediaPart` values in tool results to
`LlamaToolResultContent.content` (ordered with text parts; `result` is
null so `output` stays Genkit-history-only, as with text). Text-only
results keep their joined form.
- Pre-flight `LlamaEngineCapabilities.toolResultMedia` (image/audio), so
an unsupported runtime/template/backend fails `UNIMPLEMENTED` before the
next model turn. Thinking-budget/speculation guards and usage counts now
include tool-result media.
- Remote HTTP(S) images in tool results go through the application
`LlamaDartMediaResolver` (same limits, cancellation, sanitized errors);
without one they are rejected with a redacted `INVALID_ARGUMENT`. Audio,
resource, data, video, PDF and other non-image parts fail
`UNIMPLEMENTED` (remote audio and non-image remote media are never
fetched); malformed image data URLs and remote images without a resolver
stay `INVALID_ARGUMENT`.
- New example `genkit_llamadart_tool_media_example.dart`,
docs/skill/README/CONTRIBUTING updates, opt-in real-model test.
- Closes #1212 (core delivered by #1462). `genkit_llamadart` is
independently versioned: this adds only an `## Unreleased` entry; no
pubspec bump and no release prep (3.13.0 is left for a separate two-file
prep PR).

## Changelog
- [packages/genkit_llamadart] Forward image `MediaPart` values in Genkit
tool results to the next model turn on native llama.cpp vision models
with a qualified template, and reject audio and unsupported runtimes
with `UNIMPLEMENTED`.

## Production-readiness scope
- **User-facing scope:** Genkit tools can return images that the model
reads on the next turn.
- **Supported platforms/paths:** native llama.cpp with a loaded
projector and a tool-result-media-qualified template (Qwen3-VL;
Qwen3.5-0.8B with the Qwen3-VL template); local path, `file://`, `data:`
and resolver-fetched HTTP(S) images.
- **Unsupported or intentionally unavailable paths:** audio (no runtime
reports it), video/resource/data parts, LiteRT-LM, Web, unqualified
templates: `UNIMPLEMENTED` before the next model call (redacted); remote
images without a resolver: `INVALID_ARGUMENT`.
- **Out of scope / follow-ups:** None (#1008 stays open for core's other
families).

## Completeness checklist
- [x] Declared scope is fully implemented.
- [x] Unsupported combinations fail loudly (see above).
- [x] Dartdoc/docs, README, example, skill and changelog updated.
- [x] Regression coverage: ordered mixed text/media, both roles,
multiple calls, interrupt/resume, capability rejection, remote resolver
success/failure/cancellation, redaction.
- [x] Validation coverage registry: N/A, adapter-only (no core public
capability change).
- [x] Security/privacy: tests assert URLs/tokens never appear in errors;
resolver errors drop causes.
- [x] Follow-ups: None.

## PR type guidance
- **Feature PR:** API behavior, docs, example, unsupported paths and
happy/negative tests included.

## Test Plan
From `packages/genkit_llamadart` (Flutter 3.47.1 SDK):
- [x] `dart format --output=none --set-exit-if-changed .`; `dart analyze
--fatal-infos`; `python3 .github/check_docs.py`
- [x] `dart test -x real-model`: 504 pass, hosted llamadart 0.21.0
(lower bound) and checkout-core override
- [x] `dart test -p chrome` on converter/media/remote-media suites: 128
pass
- [x] Staged archive `dart pub publish --dry-run`: 0 warnings
- [x] Root `python3 tool/ci/check_format.py`
- [x] Real model (below)

## Matrix Evidence
| Matrix row | Scope covered | Platform / model / backend | Result |
Evidence / notes |
| --- | --- | --- | --- | --- |
| `genkit-contracts` | package suites, docs, staging | macOS arm64, Dart
| PASS | see Test Plan; CI to confirm |
| `genkit-native-cpu` | Genkit tool returns red/blue PNG; model names
the color on the next turn | macOS arm64 CPU, Qwen3-VL-2B-Instruct
Q4_K_M (sha256 `089d75c5…ca6c2ae`, rev `52d6c8ff…eb503`) + F16 mmproj
(`c3d5afbe…6aea5`), 2 threads | PASS (red, blue) |
`real_model_tool_result_media_test.dart`; also passes on Qwen3.5-0.8B +
Qwen3-VL template; hosted 0.21.0 and checkout core |
| `tool-result-image-smoke` | core scenario | N/A | N/A | core is
unchanged; the adapter test reuses its env vars instead (the scenario
runs a core test) |
| Example | `genkit_llamadart_tool_media_example.dart` with the Qwen3-VL
pair and a red PNG | same | PASS | printed "A solid red square image." |

Mutation checks (10 mutants: result non-null, reversed order, no remote
rejection, no image/audio capability check, no resolver collection, no
nested replacement, dropped text, top-level-only media for guards/usage)
are all killed; the new tests fail against the base `lib/`.

## Review Notes
- Independent review status: pending, exact-head auditor required
(high-risk).
- CI status / head SHA: pending / 2ac130c

## High-risk regression review
- **Classification:** high-risk (backendRuntime, regressionPolicy,
structuredOutput)
- **Implementation task:** this PR (worker)
- **Independent blocking QA task:** pending
- **Exact head / current base:** 2ac130c / 4809d67
- **Production-branch deletion, bypass, or miswire proof:** reverting
the four `lib/` files fails 10 new tests; mutants above
- **Affected-family real-model/artifact evidence:** Qwen3-VL-2B-Instruct
Q4_K_M + F16 projector, native llama.cpp CPU (see matrix)
- **Explicit unavailable-family or other N/A evidence:** audio tool
results: no runtime reports them; LiteRT-LM/Web: unsupported by core
- **Known PR-caused P1 regressions:** 0 known
- **Unresolved review threads:** 0

**Delta (audit B1 fix, 2ac130c):** non-image tool-result media now
fails `UNIMPLEMENTED` regardless of resolver config; the resolver queues
only `image/*` tool-result media. Rejected-case tests assert
`StatusCode`; they fail against 12c5334 (8 failures) and 4 delta
mutants are killed. Package `dart test -x real-model` 508 pass, Chrome
suites 174 pass, analyze/format/check_docs clean. Docs note that
tool-returned local paths are read as given.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant