Repository navigation
Return images from tools on native llama.cpp (#1008) - #1462
Merged
Merged
Conversation
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.
…/1008-multimodal-tool-results
Contributor
|
Chat app preview removed for |
This was referenced Oct 28, 2026
Merged
13 tasks done
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
LlamaToolResultContentgains orderedcontentparts and handlers oronToolCallcan returnLlamaToolOutput(output:, content:).ChatSession.sendWithTools/completeWithToolsstore it as a typed result. ALlamaToolOutputpassed asresultin a manual loop throwsLlamaArgumentException; the docs show how to unwrap it.620d2225crenders an arraytoolmessage ([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 getsabcx), and string-only templates joined by\n. Images go to llama.cpp in prompt order.toJsonemits 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 SPIBackendToolResultMedia(inpackage:llamadart/backend.dart) declares what a backend places;LlamaCppBackenddeclares images andNativeAutoBackenddelegates.<tool_call>format carries arendersToolResultContentregistry 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
sendWithToolshandlers,onToolCall, or interrupt/resume with app-added results.LlamaCppBackend,NativeAutoBackendon a GGUF), images withpathorbytes, chat formats withrendersToolResultContent(Hermes only).LlamaUnsupportedExceptionfor other formats (Qwen3.5 XML, Gemma 4, Llama 3, generic routing from a response schema with tools), even with text-onlycontent;LlamaUnsupportedExceptionfor WebGPU, LiteRT-LM (native chat), a backend without the SPI, or a missing vision projector;LlamaUnsupportedExceptionfor audio, video, URL-only images (the URL is never echoed), and templates that render a tool result's marker other than once;LlamaArgumentExceptionfor nested tool calls, tool results and thinking parts, and for aLlamaToolOutputresult.LlamaToolResultContentstill throw (Image parts in tool-role messages are silently moved to another turn on llama.cpp #1445); the message now points tocontent.content, and anulloutput renders nothing. Q3,LlamaToolOutputis optional and theObject?handler convention is unchanged.tool-result-mediapoints to Design multimodal tool-result content with preserved tool identity #1008.mainby Render media requests through the format handler so tool grammars stay lazy #1464, merged here.Completeness checklist
mainby Render media requests through the format handler so tool grammars stay lazy #1464.PR type guidance
lib/llamadart.dart, SPI fromlib/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.Test Plan
dart run tool/prepare_workspace.dartdart format --output=none --set-exit-if-changed .dart analyzedart test -p vm -j 1 --exclude-tags local-onlydart test -p chrome --exclude-tags local-onlytool-result-image-smoke(CPU and Metal),./tool/testing/run_template_parity_suites.sh,dart test -p vm test/unit/tooling/, docs build.Matrix Evidence
root-vm-j 1 --exclude-tags local-only:+8611 ~5at 0cc98e5; at c417f1ftest/unit/core,test/unit/tooling,test/unit/backends/{llama_cpp,native}:+6339 ~5, all passed; full suite in CIroot-chrome+3870 ~1at 0cc98e5; touched Chrome-eligible tests pass at e6d49db; full suite in CItool-result-image-smokeLlamaToolOutputphoto reaches the nextsendWithToolsroundbd258782…) + mmproj F16 (56e4c6cf…,qwen3vl_merger), Qwen3-VL-2B-Instruct template (3636d0f0…), llama.cpp CPU and MetalThe 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./tool/testing/run_template_parity_suites.sh: all passed at c417f1fhigh-risk-exact-head-independent-qac417f1f40/41b9f33a7llamadart-evidence/pr-1462/r2/evidence-1462-c417f1f.json;high_risk_readiness.dartexits 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 typedabcxand Qwen3-4B string-onlyabc\nx, captured from Homebrew llama-server b11669-620d2225c). Rendering throughChatTemplateEngine.renderandLlamaEngine.chatTemplateis byte-identical to them.Mutation check (each mutant fails the named tests; all restored):
rendersToolResultContentofftool-result media keep the Hermes lazy tool grammarLlamaToolOutputonToolCallloop testsis empty for a template format not qualifiedcontentbackends that take chat natively refuse text contentcontentnot flattenedLlamaCppBackenddeclares no mediaplaces only images at tool-result markerstoJsonkeeps the raw resulttool result with content is llama-server array contenttoolResultWithMediaMarkers)returns a result without media unchangedreports audio only when the projector takes audioLlamaToolOutputresultacceptedrejects a LlamaToolOutput resultOne equivalent mutant: the render-context fast path for text-only content (the inner helper returns the same result).
Review Notes
main45dd8c8 (Let a boolean thinking template kwarg override enableThinking #1461;engine.dartimports and both changelogs, both sides kept) and addresses the audit's P2 (text-only join) and P3s (audio guard test, two-color tool loop,LlamaToolOutputin manual loops,LLAMADART_TOOL_MEDIA_CHAT_TEMPLATEpass-through).main41b9f33 (Render media requests through the format handler so tool grammars stay lazy #1464, clean) and pinsQwen3-VL-2B-Instruct.jinjain Render media requests through the format handler so tool grammars stay lazy #1464's media-marker parity inventory; its 8 render-parity cases pass.High-risk regression review
backendRuntime,regressionPolicy,structuredOutput)qwen3vl_mergerprojector, running the pinned Qwen3-VL template, plus llama-server 620d2225c emissions