From b31ace603e05bf6b205603b944de447888852db2 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 07:02:11 -0400 Subject: [PATCH 1/2] fix: throw typed errors for media parts a chat template or projector does not take An audio or video part sent to a chat template that takes typed image parts only (Qwen3.5, Devstral-Small-2507, Apriel 1.6) failed in the Dart template render with the template's own raw `Exception`. `JinjaAnalyzer` cleared typed content only when a template rejected both image and audio parts, so a vision-only template stayed on the typed route and was handed the audio part; a video part next to an image was handed over as JSON. - `JinjaAnalyzer` keeps which media kinds the template renders as typed parts, and `ChatTemplateEngine` uses typed parts only when the template takes every media part of the request. Otherwise each part is the media marker in text, as llama.cpp gives templates. - `LlamaEngine.create` and `generate` probe the loaded projector and throw `LlamaUnsupportedException` naming the missing encoder for an image or audio part it cannot encode, instead of an untyped native failure. - A chat template that fails to render, by raising or through invalid syntax, throws `LlamaInferenceException` with the template's message. Closes #963 --- CHANGELOG.md | 9 + doc/litert_lm_templates.md | 7 +- lib/src/core/engine/engine.dart | 54 +++++- .../core/template/chat_template_engine.dart | 95 ++++++---- .../core/template/jinja/jinja_analyzer.dart | 15 +- lib/src/core/template/template_caps.dart | 11 ++ skills/llamadart-multimodal/SKILL.md | 2 +- ...wen35_multimodal_macos_repro_e2e_test.dart | 35 ++++ ...e_multimodal_browser_integration_test.dart | 32 ++++ test/unit/core/engine/engine_test.dart | 166 +++++++++++++++++- .../template/chat_template_engine_test.dart | 155 ++++++++++++++++ .../template/jinja/jinja_analyzer_test.dart | 12 +- .../template_caps_cache_fixtures_test.dart | 100 +++++++++++ website/docs/changelog/recent-releases.md | 9 + website/docs/guides/multimodal.md | 3 +- .../docs/guides/template-engine-internals.md | 7 +- 16 files changed, 665 insertions(+), 47 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 213632ec7..d141c0400 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -87,6 +87,15 @@ llama.cpp `v0.6.0@d81235049384534c167caea52b85a694f6103d14` parity; Web LiteRT-LM is `@litert-lm/core@0.18.0`. Immutable Web asset manifest: `f823b10417b212ff1f66aa1c46bf78af7d9c393497dfcf0fa3a4f77adeb260eb`. +- Fix an audio or video part sent to a chat template that takes typed image + parts only (Qwen3.5 and others) failing with a raw `Exception` from the + template ([#963](https://github.com/leehack/llamadart/issues/963)). + `LlamaEngine.create` and `generate` now throw `LlamaUnsupportedException` + naming the missing encoder when the loaded GGUF projector does not take an + image or audio part, where an untyped runtime failure surfaced as + `LlamaInferenceException` before. `chatTemplate` renders a part the + template rejects as the media marker, and a chat template that fails to + render throws `LlamaInferenceException` with the template's message. ## 0.11.1 diff --git a/doc/litert_lm_templates.md b/doc/litert_lm_templates.md index 66e4d7a75..f1ff4bef0 100644 --- a/doc/litert_lm_templates.md +++ b/doc/litert_lm_templates.md @@ -209,9 +209,10 @@ Templates are committed as jinja under `tool/litert_lm_templates/` and embedded into `lib/src/backends/litert_lm/litert_lm_chat_templates.dart` by a generator. Start from the canonical template llama.cpp uses. Keep any runtime content-shape adapter in this source and cover it with prompt-parity tests. -An adapter that reads content part lists either renders image and audio parts -or rejects both: the Dart renderer gives a template that reads part lists -media as typed parts unless it rejects both kinds. Pin the result in +The Dart renderer gives an adapter that reads content part lists media as +typed parts only when it renders every media kind in the request, and the +media marker in text otherwise, so an adapter may render image parts, audio +parts, both or neither. Pin the result in `test/unit/core/template/template_caps_cache_fixtures_test.dart`. 1. Copy the canonical jinja into `tool/litert_lm_templates/.jinja` diff --git a/lib/src/core/engine/engine.dart b/lib/src/core/engine/engine.dart index cc6b4a40e..e7786cd59 100644 --- a/lib/src/core/engine/engine.dart +++ b/lib/src/core/engine/engine.dart @@ -1543,6 +1543,12 @@ class LlamaEngine { /// parse compatible best-effort tool-call text, but it does not currently /// enforce arbitrary JSON-schema constraints. /// + /// An image or audio part that the loaded multimodal projector reports no + /// encoder for throws [LlamaUnsupportedException] before the chat template + /// is rendered. A template that fails to render, by raising or through + /// invalid syntax, throws [LlamaInferenceException] with the template's + /// message. + /// /// Example: /// ```dart /// final messages = [ @@ -1615,9 +1621,9 @@ class LlamaEngine { return _generationCancellation.request((request) { Stream chunks() async* { _ensureReady(); - await _rejectUnsupportedVideoInput( - messages.expand((message) => message.parts), - ); + final requestParts = messages.expand((message) => message.parts); + await _rejectUnsupportedVideoInput(requestParts); + await _rejectMediaInputWithoutEncoder(requestParts); // Keep tools available to template routing even with toolChoice.none, // matching llama.cpp behavior. @@ -1783,6 +1789,9 @@ class LlamaEngine { /// Use [LlamaStructuredOutput.responseFormat] to avoid hand-writing these /// maps in application code. /// + /// A template that fails to render, by raising or through invalid syntax, + /// throws [LlamaInferenceException] with the template's message. + /// /// [jsonSchema] is a legacy shortcut for /// `responseFormat: {'type': 'json_schema', 'json_schema': {'schema': ...}}`. /// If both [responseFormat] and [jsonSchema] are provided, [responseFormat] @@ -1932,7 +1941,9 @@ class LlamaEngine { required GenerationRequest request, }) async* { _ensureReady(); - await _rejectUnsupportedVideoInput(parts ?? const []); + final requestParts = parts ?? const []; + await _rejectUnsupportedVideoInput(requestParts); + await _rejectMediaInputWithoutEncoder(requestParts); if (request.isCancelled()) return; final resolvedParams = await _resolveDraftModel(params, request); if (resolvedParams == null) return; @@ -2590,6 +2601,41 @@ class LlamaEngine { ); } + /// Rejects an image or audio part that the loaded multimodal projector + /// reports no encoder for. + /// + /// Without a projector, or when a probe cannot run, the backend's own media + /// check answers the request. + Future _rejectMediaInputWithoutEncoder( + Iterable parts, + ) async { + final mmContextHandle = _mmContextHandle; + if (mmContextHandle == null) return; + + final candidate = backend; + Future require(String kind, Future Function() probe) async { + final bool supported; + try { + supported = await probe(); + } catch (_) { + return; + } + if (supported) return; + throw LlamaUnsupportedException( + '$kind input is not supported by the loaded multimodal projector: it ' + 'reports no ${kind.toLowerCase()} encoder. Load a projector that has ' + 'one, or leave ${kind.toLowerCase()} parts out of the request.', + ); + } + + if (parts.any((part) => part is LlamaImageContent)) { + await require('Image', () => candidate.supportsVision(mmContextHandle)); + } + if (parts.any((part) => part is LlamaAudioContent)) { + await require('Audio', () => candidate.supportsAudio(mmContextHandle)); + } + } + /// Returns the optional [GenerationParams] controls that the loaded model's /// runtime applies. /// diff --git a/lib/src/core/template/chat_template_engine.dart b/lib/src/core/template/chat_template_engine.dart index 7d14ace77..900d37ce5 100644 --- a/lib/src/core/template/chat_template_engine.dart +++ b/lib/src/core/template/chat_template_engine.dart @@ -1,5 +1,6 @@ import 'dart:convert'; +import '../exceptions.dart'; import '../grammar/tool_grammar_generator.dart' as grammar; import '../llama_logger.dart'; import '../models/chat/chat_message.dart'; @@ -122,6 +123,9 @@ class ChatTemplateEngine { /// If the template source is null/empty, uses the ChatML fallback. /// [responseFormat] takes the shapes documented on `LlamaEngine.create`; /// any other shape throws `LlamaUnsupportedException`. + /// + /// A template that fails to render, by raising or through invalid syntax, + /// throws `LlamaInferenceException` with the template's message. static LlamaChatTemplateResult render({ required String? templateSource, required List messages, @@ -249,32 +253,41 @@ class ChatTemplateEngine { ); } - // Templates that also read string content get media as typed parts. - // Templates that read only typed parts (e.g. SmolVLM's - // `message['content'][0]['type']`) get the media marker in a text part, as - // llama.cpp gives them. - final hasMediaParts = effectiveMessages.any( - (message) => message.parts.any( - (part) => part is LlamaImageContent || part is LlamaAudioContent, - ), - ); + bool isTransport(LlamaContentPart part) => + part is LlamaImageContent || + part is LlamaAudioContent || + part is LlamaVideoContent; + bool takenAsTypedPart(LlamaContentPart part) => + part is LlamaImageContent && caps.supportsImageParts || + part is LlamaAudioContent && caps.supportsAudioParts; + final mediaParts = effectiveMessages + .expand((message) => message.parts) + .where(isTransport); + + // Templates that also read string content get media as typed parts when + // they take every media part of the request that way. Templates that read + // only typed parts (e.g. SmolVLM's `message['content'][0]['type']`) get + // the media marker in a text part, as llama.cpp gives them. final needsTypedContent = caps.supportsTypedContent && caps.supportsStringContent && - hasMediaParts; + mediaParts.isNotEmpty && + mediaParts.every(takenAsTypedPart); if (needsTypedContent) { LlamaLogger.instance.debug( 'ChatTemplateEngine: Using multimodal content format ' 'for template that accesses content as list', ); - var rendered = handler.renderWithMultimodalContent( - templateSource: effectiveTemplate ?? GenericHandler.chatMlTemplate, - messages: effectiveMessages, - metadata: handlerMetadata, - addAssistant: addAssistant, - tools: effectiveTools, - enableThinking: enableThinking, + var rendered = _renderTemplate( + () => handler.renderWithMultimodalContent( + templateSource: effectiveTemplate ?? GenericHandler.chatMlTemplate, + messages: effectiveMessages, + metadata: handlerMetadata, + addAssistant: addAssistant, + tools: effectiveTools, + enableThinking: enableThinking, + ), ); if (effectiveFormat == ChatFormat.contentOnly) { rendered = _withFormat(rendered, ChatFormat.contentOnly.index); @@ -289,14 +302,11 @@ class ChatTemplateEngine { return _normalizeGrammarLazyForToolChoice(withGrammar, toolChoice); } - // Other templates cannot consume transport objects. Keep media in the + // Other templates cannot consume transport objects, and neither can a + // template for a media kind it rejects or for video. Keep media in the // original request for the backend and render only its placeholder here, // in content order, as llama.cpp does for media_marker parts. - bool isTransport(LlamaContentPart part) => - part is LlamaImageContent || - part is LlamaAudioContent || - part is LlamaVideoContent; - if (effectiveMessages.any((message) => message.parts.any(isTransport))) { + if (mediaParts.isNotEmpty) { effectiveMessages = effectiveMessages .map((message) { return message.copyWith( @@ -312,13 +322,15 @@ class ChatTemplateEngine { .toList(growable: false); } - var baseResult = handler.render( - templateSource: effectiveTemplate ?? GenericHandler.chatMlTemplate, - messages: effectiveMessages, - metadata: handlerMetadata, - addAssistant: addAssistant, - tools: effectiveTools, - enableThinking: enableThinking, + var baseResult = _renderTemplate( + () => handler.render( + templateSource: effectiveTemplate ?? GenericHandler.chatMlTemplate, + messages: effectiveMessages, + metadata: handlerMetadata, + addAssistant: addAssistant, + tools: effectiveTools, + enableThinking: enableThinking, + ), ); if (effectiveFormat == ChatFormat.contentOnly) { @@ -335,6 +347,29 @@ class ChatTemplateEngine { return _normalizeGrammarLazyForToolChoice(withGrammar, toolChoice); } + /// Runs a handler [render], turning a failure that is not already a + /// [LlamaException] (a template's own `raise_exception`, a Jinja runtime + /// error, invalid template syntax) into a [LlamaInferenceException]. + static LlamaChatTemplateResult _renderTemplate( + LlamaChatTemplateResult Function() render, + ) { + try { + return render(); + } on LlamaException { + rethrow; + } on Exception catch (error, stackTrace) { + final cause = error.toString(); + const prefix = 'Exception: '; + Error.throwWithStackTrace( + LlamaInferenceException( + 'The chat template failed to render: ' + '${cause.startsWith(prefix) ? cause.substring(prefix.length) : cause}', + ), + stackTrace, + ); + } + } + /// Apply grammar constraints based on tool definitions and response format. static LlamaChatTemplateResult _applyGrammar( LlamaChatTemplateResult result, diff --git a/lib/src/core/template/jinja/jinja_analyzer.dart b/lib/src/core/template/jinja/jinja_analyzer.dart index 11c0d5a26..6e151612b 100644 --- a/lib/src/core/template/jinja/jinja_analyzer.dart +++ b/lib/src/core/template/jinja/jinja_analyzer.dart @@ -24,7 +24,8 @@ class JinjaAnalyzer { /// /// The media-part probe is not llama.cpp's: a template that reads both /// strings and part lists is rendered with an image part and with an audio - /// part, and `supportsTypedContent` is cleared when it rejects both. The + /// part. `supportsImageParts` and `supportsAudioParts` report which it + /// renders, and `supportsTypedContent` is cleared when it rejects both. The /// only part lists `ChatTemplateEngine` gives such a template carry media. /// /// A probe render that throws is one of llama.cpp's outcomes, not a @@ -108,8 +109,10 @@ class JinjaAnalyzer { // A template that reads strings too is given a part list only to carry // media. One that reads text part lists but rejects both media kinds is // given strings, with the media marker in the text. + var supportsImageParts = true; + var supportsAudioParts = true; if (supportsTypedContent && supportsStringContent) { - bool rejects(String type) => !_render( + bool renders(String type) => _render( probe, '$type-content', _Probe.messages([ @@ -121,7 +124,11 @@ class JinjaAnalyzer { }, ]), ).success; - if (rejects('image') && rejects('audio')) supportsTypedContent = false; + supportsImageParts = renders('image'); + supportsAudioParts = renders('audio'); + if (!supportsImageParts && !supportsAudioParts) { + supportsTypedContent = false; + } } final system = _Probe.messages([ @@ -181,6 +188,8 @@ class JinjaAnalyzer { supportsTypedContent: supportsTypedContent, supportsThinking: supportsThinking, supportsObjectArguments: supportsObjectArguments, + supportsImageParts: supportsImageParts, + supportsAudioParts: supportsAudioParts, ); } diff --git a/lib/src/core/template/template_caps.dart b/lib/src/core/template/template_caps.dart index a2161cac4..7b9191dfd 100644 --- a/lib/src/core/template/template_caps.dart +++ b/lib/src/core/template/template_caps.dart @@ -34,6 +34,15 @@ class TemplateCaps { /// earlier tool calls are rendered with their arguments parsed from JSON. final bool supportsObjectArguments; + /// Whether the template renders a typed image part (`{type: 'image'}`) + /// without raising. Probed only for a template that reads both string and + /// typed content, and `true` for every other template. + final bool supportsImageParts; + + /// Whether the template renders a typed audio part (`{type: 'audio'}`) + /// without raising, under the same conditions as [supportsImageParts]. + final bool supportsAudioParts; + /// Creates a [TemplateCaps] with the specified capabilities. const TemplateCaps({ this.supportsSystemRole = true, @@ -44,6 +53,8 @@ class TemplateCaps { this.supportsTypedContent = false, this.supportsThinking = false, this.supportsObjectArguments = false, + this.supportsImageParts = true, + this.supportsAudioParts = true, }); /// Detects capabilities with llama.cpp's capability probes, as diff --git a/skills/llamadart-multimodal/SKILL.md b/skills/llamadart-multimodal/SKILL.md index 1369050da..018782346 100644 --- a/skills/llamadart-multimodal/SKILL.md +++ b/skills/llamadart-multimodal/SKILL.md @@ -42,7 +42,7 @@ description: >- values as `capabilities`. - Always check before sending media to a GGUF model. With no projector loaded, image or audio parts throw `LlamaUnsupportedException` on llama.cpp, native - and WebGPU. + and WebGPU, and so does a part the loaded projector reports no encoder for. - Put media in a message with `LlamaChatMessage.withContent(role: ..., content: [...])`, or pass the parts to `ChatSession.create`. Place media before the text that refers to it. diff --git a/test/e2e/tooling/qwen35_multimodal_macos_repro_e2e_test.dart b/test/e2e/tooling/qwen35_multimodal_macos_repro_e2e_test.dart index ee10c6524..dc872e891 100644 --- a/test/e2e/tooling/qwen35_multimodal_macos_repro_e2e_test.dart +++ b/test/e2e/tooling/qwen35_multimodal_macos_repro_e2e_test.dart @@ -10,6 +10,7 @@ library; import 'dart:convert'; import 'dart:io'; +import 'dart:typed_data'; import 'package:llamadart/llamadart.dart'; import 'package:path/path.dart' as path; @@ -122,6 +123,8 @@ Future _runScenario({ reason: 'Expected Qwen3.5 0.8B + mmproj to report vision support.', ); + await _expectAudioRejected(engine, prompt); + final GenerationParams generationParams = GenerationParams( maxTokens: maxTokens, temp: 0.2, @@ -169,6 +172,38 @@ Future _runScenario({ } } +/// The Qwen3.5 template takes typed image parts only and its projector has no +/// audio encoder: an audio part is refused by name, and still renders. +Future _expectAudioRejected(LlamaEngine engine, String prompt) async { + expect(await engine.supportsAudio, isFalse); + final List messages = [ + LlamaChatMessage.withContent( + role: LlamaChatRole.user, + content: [ + LlamaAudioContent(samples: Float32List(16000)), + LlamaTextContent(prompt), + ], + ), + ]; + + stdout.writeln('Sending an audio part to the vision-only projector...'); + await expectLater( + engine.create(messages).drain(), + throwsA( + isA().having( + (LlamaUnsupportedException error) => error.message, + 'message', + contains('it reports no audio encoder'), + ), + ), + ); + final LlamaChatTemplateResult rendered = await engine.chatTemplate( + messages, + includeTokenCount: false, + ); + expect(rendered.prompt, contains('<__media__>')); +} + Future _runSessionTurn({ required ChatSession session, required List parts, diff --git a/test/integration/backends/webgpu/webgpu_engine_multimodal_browser_integration_test.dart b/test/integration/backends/webgpu/webgpu_engine_multimodal_browser_integration_test.dart index 89577fdbd..e828a6f0c 100644 --- a/test/integration/backends/webgpu/webgpu_engine_multimodal_browser_integration_test.dart +++ b/test/integration/backends/webgpu/webgpu_engine_multimodal_browser_integration_test.dart @@ -17,6 +17,7 @@ void main() { late LlamaEngine engine; late bool mmLoaded; late bool sawAudioPart; + late int completionCalls; String? lastStateSavePath; List? lastStateSaveTokens; String? lastStateLoadPath; @@ -36,6 +37,7 @@ void main() { bridge = JSObject(); mmLoaded = false; sawAudioPart = false; + completionCalls = 0; lastStateSavePath = null; lastStateSaveTokens = null; lastStateLoadPath = null; @@ -93,6 +95,7 @@ void main() { bridge.setProperty( 'createCompletion'.toJS, ((String prompt, JSObject opts) { + completionCalls += 1; final parts = opts.getProperty('parts'.toJS); if (parts.isA()) { final jsParts = parts as JSArray; @@ -449,6 +452,35 @@ void main() { expect(sawAudioPart, isTrue); }); + test('LlamaEngine create rejects an image part for a projector with no ' + 'image encoder before the bridge', () async { + await engine.loadModelFromUrl( + 'https://example.com/model.gguf', + modelParams: const ModelParams(contextSize: 1024), + ); + await engine.loadMultimodalProjector('https://example.com/mmproj.gguf'); + + await expectLater( + engine.create([ + LlamaChatMessage.withContent( + role: LlamaChatRole.user, + content: [ + const LlamaTextContent('Describe this image.'), + LlamaImageContent(bytes: Uint8List.fromList([1, 2, 3])), + ], + ), + ], params: const GenerationParams(maxTokens: 8)).drain(), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('it reports no image encoder'), + ), + ), + ); + expect(completionCalls, 0); + }); + test('LlamaEngine embed and embedBatch work via web bridge', () async { await engine.loadModelFromUrl( 'https://example.com/model.gguf', diff --git a/test/unit/core/engine/engine_test.dart b/test/unit/core/engine/engine_test.dart index 5b7ca1339..877219129 100644 --- a/test/unit/core/engine/engine_test.dart +++ b/test/unit/core/engine/engine_test.dart @@ -35,6 +35,8 @@ class MockLlamaBackend this.contextFreeDelay, this.nativeVideoRuntimeSupported = false, this.videoProbeError, + this.projectorSupportsAudio = false, + this.audioProbeError, }); Object? modelLoadError; @@ -74,6 +76,8 @@ class MockLlamaBackend Future? contextFreeDelay; final bool? nativeVideoRuntimeSupported; final Object? videoProbeError; + final bool projectorSupportsAudio; + final Object? audioProbeError; int? lastVideoProbeHandle; @override @@ -256,7 +260,12 @@ class MockLlamaBackend Future supportsVision(int mmContextHandle) async => true; @override - Future supportsAudio(int mmContextHandle) async => false; + Future supportsAudio(int mmContextHandle) async { + if (audioProbeError case final error?) { + throw error; + } + return projectorSupportsAudio; + } @override Future supportsVideoRuntime(int mmContextHandle) async { @@ -2486,6 +2495,161 @@ void main() { } }); + group('media the loaded projector has no encoder for', () { + const visionOnlyTemplate = + '{% for message in messages %}' + '{% if message.content is string %}{{ message.content }}' + '{% else %}{% for part in message.content %}' + "{% if part.type == 'text' %}{{ part.text }}" + "{% elif part.type == 'image' %}[image part]" + "{% else %}{{ raise_exception('Unexpected item type in content.') }}" + '{% endif %}{% endfor %}{% endif %}' + '{% endfor %}'; + const audio = LlamaAudioContent(path: '/tmp/clip.wav'); + const image = LlamaImageContent(path: '/tmp/page.png'); + + Future loaded(MockLlamaBackend backend) async { + final engine = LlamaEngine(backend); + addTearDown(engine.dispose); + await engine.loadModel('qwen-test.gguf'); + await engine.loadMultimodalProjector('proj.gguf'); + return engine; + } + + List request(List media) => [ + LlamaChatMessage.withContent( + role: LlamaChatRole.user, + content: [const LlamaTextContent('Describe:'), ...media], + ), + ]; + + final noAudioEncoder = throwsA( + isA().having( + (error) => error.message, + 'message', + 'Audio input is not supported by the loaded multimodal projector: ' + 'it reports no audio encoder. Load a projector that has one, or ' + 'leave audio parts out of the request.', + ), + ); + + for (final MapEntry(key: label, value: media) in { + 'an audio part': [audio], + 'an audio part next to an image': [image, audio], + }.entries) { + test('create rejects $label for a vision-only template before ' + 'rendering it', () async { + final backend = MockLlamaBackend( + modelMetadataResponse: { + 'tokenizer.chat_template': visionOnlyTemplate, + }, + ); + final engine = await loaded(backend); + + await expectLater( + engine.create(request(media)).drain(), + noAudioEncoder, + ); + expect(backend.lastGenerationPrompt, isNull); + }); + } + + test('generate rejects an audio part', () async { + final backend = MockLlamaBackend(); + final engine = await loaded(backend); + + await expectLater( + engine.generate('describe', parts: [audio]).drain(), + noAudioEncoder, + ); + expect(backend.lastGenerationPrompt, isNull); + }); + + test('create sends an image part, which the projector encodes, as a ' + 'typed part', () async { + final backend = MockLlamaBackend( + modelMetadataResponse: { + 'tokenizer.chat_template': visionOnlyTemplate, + }, + ); + final engine = await loaded(backend); + + await engine.create(request([image])).drain(); + + expect(backend.lastGenerationPrompt, 'Describe:[image part]'); + }); + + test('create sends audio to a vision-only template as the media ' + 'marker when the projector encodes audio', () async { + final backend = MockLlamaBackend( + projectorSupportsAudio: true, + modelMetadataResponse: { + 'tokenizer.chat_template': visionOnlyTemplate, + }, + ); + final engine = await loaded(backend); + + await engine.create(request([image, audio])).drain(); + + expect(backend.lastGenerationPrompt, 'Describe:<__media__><__media__>'); + }); + + test( + 'a probe that cannot run leaves the request to the backend', + () async { + final backend = MockLlamaBackend( + audioProbeError: LlamaUnsupportedException('probe unavailable'), + ); + final engine = await loaded(backend); + + await engine.generate('describe', parts: [audio]).drain(); + + expect(backend.lastGenerationPrompt, 'describe'); + }, + ); + + test('without a projector the request reaches the backend', () async { + final backend = MockLlamaBackend(); + final engine = LlamaEngine(backend); + addTearDown(engine.dispose); + await engine.loadModel('qwen-test.gguf'); + + await engine.generate('describe', parts: [audio]).drain(); + + expect(backend.lastGenerationPrompt, 'describe'); + }); + }); + + test( + 'create throws a typed exception when the chat template raises', + () async { + final raising = MockLlamaBackend( + modelMetadataResponse: { + 'tokenizer.chat_template': + "{{ raise_exception('Conversation roles must alternate') }}", + }, + ); + final raisingEngine = LlamaEngine(raising); + addTearDown(raisingEngine.dispose); + await raisingEngine.loadModel('qwen-test.gguf'); + + await expectLater( + raisingEngine.create(const [ + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'hi'), + ]).drain(), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The chat template failed to render: ' + 'Conversation roles must alternate', + ), + ), + ); + expect(raising.lastGenerationPrompt, isNull); + }, + ); + test( 'multimodal projector can be unloaded without unloading model', () async { diff --git a/test/unit/core/template/chat_template_engine_test.dart b/test/unit/core/template/chat_template_engine_test.dart index e052bb610..9f95a5d94 100644 --- a/test/unit/core/template/chat_template_engine_test.dart +++ b/test/unit/core/template/chat_template_engine_test.dart @@ -435,6 +435,161 @@ void main() { } }); + group('a template that takes typed parts of one media kind only', () { + String only(String type) => + '{% for message in messages %}' + '{% if message.content is string %}{{ message.content }}' + '{% else %}{% for part in message.content %}' + "{% if part.type == 'text' %}{{ part.text }}" + "{% elif part.type == '$type' %}[$type part]" + "{% else %}{{ raise_exception('Unexpected item type in content.') }}" + '{% endif %}{% endfor %}{% endif %}' + '{% endfor %}'; + + const image = LlamaImageContent(path: '/tmp/page.png'); + const audio = LlamaAudioContent(path: '/tmp/clip.wav'); + final video = LlamaVideoContent(path: '/tmp/clip.mp4'); + + String prompt(String type, List media) => + ChatTemplateEngine.render( + templateSource: only(type), + messages: [ + LlamaChatMessage.withContent( + role: LlamaChatRole.user, + content: [const LlamaTextContent('Describe:'), ...media], + ), + ], + metadata: const {}, + ).prompt; + + test('renders the kind it takes as a typed part', () { + expect(prompt('image', [image]), 'Describe:[image part]'); + expect(prompt('audio', [audio]), 'Describe:[audio part]'); + expect( + prompt('image', [image, image]), + 'Describe:[image part][image part]', + ); + }); + + test('gets the media marker in text for a kind it rejects', () { + expect(prompt('image', [audio]), 'Describe:<__media__>'); + expect(prompt('audio', [image]), 'Describe:<__media__>'); + }); + + test('gets one media marker per part, in order, when a request mixes ' + 'a kind it takes with one it rejects', () { + expect( + prompt('image', [image, audio]), + 'Describe:<__media__><__media__>', + ); + expect( + prompt('audio', [image, audio]), + 'Describe:<__media__><__media__>', + ); + }); + + test('gets the media marker in text for a video part next to a kind ' + 'it takes, without the video source', () { + final rendered = prompt('image', [image, video]); + expect(rendered, 'Describe:<__media__><__media__>'); + expect(rendered, isNot(contains('clip.mp4'))); + }); + }); + + group('a chat template that fails to render', () { + const mustAlternate = + '{% for message in messages %}' + '{% if loop.index0 > 0 and ' + 'message.role == messages[loop.index0 - 1].role %}' + "{{ raise_exception('Conversation roles must alternate') }}" + '{% endif %}{{ message.content }}' + '{% endfor %}'; + + Matcher throwsRenderFailure(Object message) => throwsA( + isA().having( + (e) => e.message, + 'message', + message, + ), + ); + + test('throws a typed exception carrying what the template raised', () { + expect( + () => ChatTemplateEngine.render( + templateSource: mustAlternate, + messages: const [ + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'a'), + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'b'), + ], + metadata: const {}, + ), + throwsRenderFailure( + 'The chat template failed to render: ' + 'Conversation roles must alternate', + ), + ); + }); + + test('throws a typed exception when it raises on typed parts', () { + expect( + () => ChatTemplateEngine.render( + templateSource: + '{% for message in messages %}' + '{% if message.content is string %}{{ message.content }}' + '{% else %}{% for part in message.content %}' + "{% if part.type == 'image' %}" + '{% if loop.index0 > 1 %}' + "{{ raise_exception('one image only') }}{% endif %}" + '[image part]{% else %}{{ part.text }}{% endif %}' + '{% endfor %}{% endif %}' + '{% endfor %}', + messages: const [ + LlamaChatMessage.withContent( + role: LlamaChatRole.user, + content: [ + LlamaTextContent('Compare:'), + LlamaImageContent(path: '/tmp/a.png'), + LlamaImageContent(path: '/tmp/b.png'), + ], + ), + ], + metadata: const {}, + ), + throwsRenderFailure( + 'The chat template failed to render: one image only', + ), + ); + }); + + test('throws a typed exception for invalid template syntax', () { + expect( + () => ChatTemplateEngine.render( + templateSource: '{% for message in messages %}{{ message.content', + messages: const [ + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'a'), + ], + metadata: const {}, + ), + throwsRenderFailure( + startsWith('The chat template failed to render: '), + ), + ); + }); + + test('renders the conversation it accepts', () { + final result = ChatTemplateEngine.render( + templateSource: mustAlternate, + messages: const [ + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'a'), + LlamaChatMessage.fromText(role: LlamaChatRole.assistant, text: 'b'), + ], + metadata: const {}, + ); + + expect(result.prompt, 'ab'); + }); + }); + test('keeps GLM-OCR image marker when GLM tool-call policy runs', () { const history = [ LlamaChatMessage.withContent( diff --git a/test/unit/core/template/jinja/jinja_analyzer_test.dart b/test/unit/core/template/jinja/jinja_analyzer_test.dart index 37efe99a1..c5af3c2b6 100644 --- a/test/unit/core/template/jinja/jinja_analyzer_test.dart +++ b/test/unit/core/template/jinja/jinja_analyzer_test.dart @@ -215,22 +215,30 @@ void main() { final caps = JinjaAnalyzer.analyze(template()); expect(caps.supportsStringContent, isTrue); expect(caps.supportsTypedContent, isFalse); + expect(caps.supportsImageParts, isFalse); + expect(caps.supportsAudioParts, isFalse); }); for (final type in ['image', 'audio']) { - test('a template that renders $type parts takes typed content', () { + test('a template that renders $type parts takes typed content, and ' + 'only that media kind as a part', () { final caps = JinjaAnalyzer.analyze( template(otherParts: accepting(type)), ); expect(caps.supportsStringContent, isTrue); expect(caps.supportsTypedContent, isTrue); + expect(caps.supportsImageParts, type == 'image'); + expect(caps.supportsAudioParts, type == 'audio'); }); } - test('a template that skips media parts takes typed content', () { + test('a template that skips media parts takes typed content and both ' + 'media kinds as parts', () { final caps = JinjaAnalyzer.analyze(template(otherParts: '')); expect(caps.supportsStringContent, isTrue); expect(caps.supportsTypedContent, isTrue); + expect(caps.supportsImageParts, isTrue); + expect(caps.supportsAudioParts, isTrue); }); test('a template that reads only part lists takes typed content even ' diff --git a/test/unit/core/template/template_caps_cache_fixtures_test.dart b/test/unit/core/template/template_caps_cache_fixtures_test.dart index 5158e11b0..8717203bf 100644 --- a/test/unit/core/template/template_caps_cache_fixtures_test.dart +++ b/test/unit/core/template/template_caps_cache_fixtures_test.dart @@ -3,7 +3,12 @@ library; import 'dart:io'; +import 'package:llamadart/src/core/models/chat/chat_message.dart'; +import 'package:llamadart/src/core/models/chat/chat_role.dart'; +import 'package:llamadart/src/core/models/chat/content_part.dart'; +import 'package:llamadart/src/core/template/chat_template_engine.dart'; import 'package:llamadart/src/core/template/jinja/jinja_analyzer.dart'; +import 'package:llamadart/src/core/template/media_placeholders.dart'; import 'package:llamadart/src/core/template/template_caps.dart'; import 'package:llamadart/src/core/template/template_caps_cache.dart'; import 'package:test/test.dart'; @@ -122,6 +127,101 @@ void main() { expect(failed, isEmpty); }); + test('pins the fixture templates that reject a typed media part', () { + final rejecting = >{}; + for (final file in _fixtureTemplates()) { + final caps = JinjaAnalyzer.analyze(file.readAsStringSync()); + final rejected = [ + if (!caps.supportsImageParts) 'image', + if (!caps.supportsAudioParts) 'audio', + ]; + if (rejected.isNotEmpty) { + rejecting[file.path.replaceAll(r'\', '/')] = rejected; + } + } + + expect(rejecting, const { + 'test/fixtures/llama_cpp_templates/Apriel-1.6-15b-Thinker-fixed.jinja': [ + 'audio', + ], + 'test/fixtures/llama_cpp_templates/unsloth-mistral-Devstral-Small-2507.jinja': + ['audio'], + 'test/fixtures/templates/Qwen3_5-0_8B.jinja': ['audio'], + 'tool/litert_lm_templates/qwen3.jinja': ['image', 'audio'], + }); + }); + + test('every fixture template renders every mix of media parts', () { + const image = LlamaImageContent(path: '/tmp/page.png'); + const audio = LlamaAudioContent(path: '/tmp/clip.wav'); + final video = LlamaVideoContent(path: '/tmp/clip.mp4'); + final requests = >[ + [image], + [audio], + [video], + [image, audio], + [image, video], + [audio, video], + ]; + + for (final file in _fixtureTemplates()) { + final source = file.readAsStringSync(); + for (final media in requests) { + final kinds = media.map((part) => part.runtimeType).join(' + '); + final prompt = ChatTemplateEngine.render( + templateSource: source, + messages: [ + LlamaChatMessage.withContent( + role: LlamaChatRole.user, + content: [const LlamaTextContent('Describe:'), ...media], + ), + ], + metadata: const {}, + ).prompt; + + expect(prompt, contains('Describe:'), reason: '${file.path} $kinds'); + expect(prompt, isNot(contains('/tmp/')), reason: '${file.path} $kinds'); + } + } + }); + + test('gives a vision-only fixture template one media marker per part for ' + 'a request it cannot take as typed parts', () { + const image = LlamaImageContent(path: '/tmp/page.png'); + const audio = LlamaAudioContent(path: '/tmp/clip.wav'); + final video = LlamaVideoContent(path: '/tmp/clip.mp4'); + + for (final path in const [ + 'test/fixtures/llama_cpp_templates/Apriel-1.6-15b-Thinker-fixed.jinja', + 'test/fixtures/llama_cpp_templates/unsloth-mistral-Devstral-Small-2507.jinja', + 'test/fixtures/templates/Qwen3_5-0_8B.jinja', + ]) { + final source = File(path).readAsStringSync(); + for (final media in >[ + [audio], + [image, audio], + [image, video], + ]) { + final prompt = ChatTemplateEngine.render( + templateSource: source, + messages: [ + LlamaChatMessage.withContent( + role: LlamaChatRole.user, + content: [const LlamaTextContent('Describe:'), ...media], + ), + ], + metadata: const {}, + ).prompt; + + expect( + mtmdMediaMarker.allMatches(prompt), + hasLength(media.length), + reason: '$path ${media.map((part) => part.runtimeType).join(' + ')}', + ); + } + } + }); + test('caches every fixture template', () { for (final file in _fixtureTemplates()) { TemplateCapsCache.shared.clear(); diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 180aee35a..3022a99e2 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -96,6 +96,15 @@ For canonical full release notes, use: llama.cpp `v0.6.0@d81235049384534c167caea52b85a694f6103d14` parity; Web LiteRT-LM is `@litert-lm/core@0.18.0`. Immutable Web asset manifest: `f823b10417b212ff1f66aa1c46bf78af7d9c393497dfcf0fa3a4f77adeb260eb`. +- Fix an audio or video part sent to a chat template that takes typed image + parts only (Qwen3.5 and others) failing with a raw `Exception` from the + template ([#963](https://github.com/leehack/llamadart/issues/963)). + `LlamaEngine.create` and `generate` now throw `LlamaUnsupportedException` + naming the missing encoder when the loaded GGUF projector does not take an + image or audio part, where an untyped runtime failure surfaced as + `LlamaInferenceException` before. `chatTemplate` renders a part the + template rejects as the media marker, and a chat template that fails to + render throws `LlamaInferenceException` with the template's message. ## 0.11.1 diff --git a/website/docs/guides/multimodal.md b/website/docs/guides/multimodal.md index 25437c81b..b909f5983 100644 --- a/website/docs/guides/multimodal.md +++ b/website/docs/guides/multimodal.md @@ -119,7 +119,8 @@ Always prefer these runtime checks over model-card assumptions. Read projector loaded, a GGUF model (native `llama.cpp` or WebGPU) rejects image and audio parts with `LlamaUnsupportedException` instead of answering from the text alone. A loaded projector can expose only a subset of the family-level -modalities. The current Gemma 4 E2B GGUF projector path in native `llama.cpp` +modalities, and a part it reports no encoder for (audio with a vision-only +projector, for example) is rejected the same way. The current Gemma 4 E2B GGUF projector path in native `llama.cpp` mtmd reports both vision and audio support; audio remains experimental upstream. Web continues to rely on the loaded bridge's runtime capability report. diff --git a/website/docs/guides/template-engine-internals.md b/website/docs/guides/template-engine-internals.md index 6f75153d8..ce3654f5e 100644 --- a/website/docs/guides/template-engine-internals.md +++ b/website/docs/guides/template-engine-internals.md @@ -66,8 +66,11 @@ sequenceDiagram the template reads. Thinking support comes from the template's thinking markers. - A template that reads both strings and content part lists gets image and - audio as typed parts, unless a further probe finds that it rejects both - kinds. Every other template gets the media marker in its text. + audio as typed parts when a further probe finds that it renders every media + kind in the request. Every other template, and any request with a kind the + template rejects or with video, gets the media marker in its text. +- A template that fails to render, by raising or through invalid syntax, + throws `LlamaInferenceException` with the template's message. - Routing workarounds mirror llama.cpp behavior for schema mode, tool-choice behavior, and system-message adaptation. From d011b3f20b3e9dabab85c79598396c949edac881 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 07:53:28 -0400 Subject: [PATCH 2/2] fix: refuse media a projector cannot encode inside the llama.cpp service The engine-level check added for #963 trusted every backend's projector probe. The WebGPU bridge reports a stale `false` after its worker falls back to the main thread, until the next media completion restores the projector, so image and audio turns that the bridge answers were refused before it was called. A custom backend that answers `false` and handles media was refused too. - Drop the engine check. `LlamaEngine` hands media to the backend as before. - The llama.cpp service refuses an image or audio part when mtmd reports no encoder for it on the loaded projector, before mtmd decodes the part, and names the encoder. When the runtime lacks the mtmd probe function the check is skipped, so the projector is not blamed for a runtime skew. - Word the template-failure docs for what is wrapped: an `Exception` from the template or the Jinja runtime, and syntax errors. --- CHANGELOG.md | 16 +-- .../backends/llama_cpp/llama_cpp_service.dart | 66 ++++++---- lib/src/core/engine/engine.dart | 54 ++------ .../core/template/chat_template_engine.dart | 8 +- skills/llamadart-multimodal/SKILL.md | 2 +- ...wen35_multimodal_macos_repro_e2e_test.dart | 2 +- ...e_multimodal_browser_integration_test.dart | 50 +++++--- test/support/fake_mtmd.dart | 27 +++- ...llama_cpp_service_native_failure_test.dart | 84 ++++++++++++- .../llama_cpp/llama_cpp_service_test.dart | 25 ++-- test/unit/core/engine/engine_test.dart | 115 +++++++----------- website/docs/changelog/recent-releases.md | 16 +-- website/docs/guides/multimodal.md | 5 +- 13 files changed, 274 insertions(+), 196 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d141c0400..bff8bc37e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -89,13 +89,15 @@ `f823b10417b212ff1f66aa1c46bf78af7d9c393497dfcf0fa3a4f77adeb260eb`. - Fix an audio or video part sent to a chat template that takes typed image parts only (Qwen3.5 and others) failing with a raw `Exception` from the - template ([#963](https://github.com/leehack/llamadart/issues/963)). - `LlamaEngine.create` and `generate` now throw `LlamaUnsupportedException` - naming the missing encoder when the loaded GGUF projector does not take an - image or audio part, where an untyped runtime failure surfaced as - `LlamaInferenceException` before. `chatTemplate` renders a part the - template rejects as the media marker, and a chat template that fails to - render throws `LlamaInferenceException` with the template's message. + template ([#963](https://github.com/leehack/llamadart/issues/963)). On + native llama.cpp, an image or audio part the loaded projector has no + encoder for now throws `LlamaUnsupportedException` naming the encoder, + where `create` and `generate` threw `LlamaInferenceException` or the + template's exception. `chatTemplate` renders as the media marker a media + part the template rejects and a video part beside an image or audio part, + which a template was handed and raised on or dropped. A chat template that + raises or has invalid syntax throws `LlamaInferenceException` with the + template's message. ## 0.11.1 diff --git a/lib/src/backends/llama_cpp/llama_cpp_service.dart b/lib/src/backends/llama_cpp/llama_cpp_service.dart index 1924bcf0f..03615f6b2 100644 --- a/lib/src/backends/llama_cpp/llama_cpp_service.dart +++ b/lib/src/backends/llama_cpp/llama_cpp_service.dart @@ -4242,14 +4242,16 @@ class LlamaCppService { 'use an encoder-only or decoder-only embedding model.'; // Without a projector the prompt would be evaluated as text and the media - // silently dropped; upstream llama-server rejects such requests too. + // silently dropped; upstream llama-server rejects such requests too. With + // one, mtmd refuses a part it has no encoder for while loading or + // tokenizing it, with a result code that does not say so. void _checkLlamaCppMediaParts( List parts, { - required bool projectorLoaded, + required int? mmHandle, }) { - if (!projectorLoaded) { - final hasImage = parts.any((part) => part is LlamaImageContent); - final hasAudio = parts.any((part) => part is LlamaAudioContent); + final hasImage = parts.any((part) => part is LlamaImageContent); + final hasAudio = parts.any((part) => part is LlamaAudioContent); + if (mmHandle == null) { final kind = hasImage && hasAudio ? 'Image and audio' : hasImage @@ -4273,6 +4275,20 @@ class LlamaCppService { ); } } + final mmCtx = _mtmdContexts[mmHandle]; + if (mmCtx == null) return; + for (final (kind, sent, audio) in [ + ('Image', hasImage, false), + ('Audio', hasAudio, true), + ]) { + if (sent && _mtmdHasEncoder(mmCtx, audio: audio) == false) { + throw LlamaUnsupportedException( + '$kind input is not supported by the loaded multimodal projector: ' + 'it has no ${kind.toLowerCase()} encoder. Load a projector that has ' + 'one, or leave ${kind.toLowerCase()} parts out of the request.', + ); + } + } } _LlamaCppThinkingBudgetConfig? _resolveLlamaCppThinkingBudgetConfig( @@ -4776,10 +4792,7 @@ class LlamaCppService { ); } if (hasMediaParts) { - _checkLlamaCppMediaParts( - parts!, - projectorLoaded: _modelToMtmd[modelHandle] != null, - ); + _checkLlamaCppMediaParts(parts!, mmHandle: _modelToMtmd[modelHandle]); } final thinkingBudgetConfig = _resolveLlamaCppThinkingBudgetConfig( params, @@ -8755,17 +8768,7 @@ class LlamaCppService { if (mmCtx == null) { return false; } - - if (!_mtmdPrimarySymbolsUnavailable) { - try { - return mtmd_support_vision(mmCtx); - } on ArgumentError { - _mtmdPrimarySymbolsUnavailable = true; - } - } - - final fallback = _resolveMtmdFallbackApi(); - return fallback?.supportsVision(mmCtx) ?? false; + return _mtmdHasEncoder(mmCtx, audio: false) ?? false; } /// Returns whether the active multimodal projector supports audio input. @@ -8774,22 +8777,31 @@ class LlamaCppService { if (mmCtx == null) { return false; } + return _mtmdHasEncoder(mmCtx, audio: true) ?? + (throw LlamaUnsupportedException( + _mtmdUnavailableMessage('mtmd_support_audio'), + )); + } + /// Whether the projector [mmCtx] has an audio encoder, or with [audio] + /// false a vision encoder, as mtmd reports it. + /// + /// Null when neither the llamadart library nor the fallback mtmd library + /// has the probe function. + bool? _mtmdHasEncoder(Pointer mmCtx, {required bool audio}) { if (!_mtmdPrimarySymbolsUnavailable) { try { - return mtmd_support_audio(mmCtx); + return audio ? mtmd_support_audio(mmCtx) : mtmd_support_vision(mmCtx); } on ArgumentError { _mtmdPrimarySymbolsUnavailable = true; } } final fallback = _resolveMtmdFallbackApi(); - if (fallback == null) { - throw LlamaUnsupportedException( - _mtmdUnavailableMessage('mtmd_support_audio'), - ); - } - return fallback.supportsAudio(mmCtx); + if (fallback == null) return null; + return audio + ? fallback.supportsAudio(mmCtx) + : fallback.supportsVision(mmCtx); } /// Returns whether the active native mtmd build and projector report video. diff --git a/lib/src/core/engine/engine.dart b/lib/src/core/engine/engine.dart index e7786cd59..b83c9f9df 100644 --- a/lib/src/core/engine/engine.dart +++ b/lib/src/core/engine/engine.dart @@ -1543,11 +1543,10 @@ class LlamaEngine { /// parse compatible best-effort tool-call text, but it does not currently /// enforce arbitrary JSON-schema constraints. /// - /// An image or audio part that the loaded multimodal projector reports no - /// encoder for throws [LlamaUnsupportedException] before the chat template - /// is rendered. A template that fails to render, by raising or through - /// invalid syntax, throws [LlamaInferenceException] with the template's - /// message. + /// On native llama.cpp, an image or audio part that the loaded multimodal + /// projector has no encoder for throws [LlamaUnsupportedException]. A + /// template that fails to render, by raising or through invalid syntax, + /// throws [LlamaInferenceException] with the template's message. /// /// Example: /// ```dart @@ -1621,9 +1620,9 @@ class LlamaEngine { return _generationCancellation.request((request) { Stream chunks() async* { _ensureReady(); - final requestParts = messages.expand((message) => message.parts); - await _rejectUnsupportedVideoInput(requestParts); - await _rejectMediaInputWithoutEncoder(requestParts); + await _rejectUnsupportedVideoInput( + messages.expand((message) => message.parts), + ); // Keep tools available to template routing even with toolChoice.none, // matching llama.cpp behavior. @@ -1941,9 +1940,7 @@ class LlamaEngine { required GenerationRequest request, }) async* { _ensureReady(); - final requestParts = parts ?? const []; - await _rejectUnsupportedVideoInput(requestParts); - await _rejectMediaInputWithoutEncoder(requestParts); + await _rejectUnsupportedVideoInput(parts ?? const []); if (request.isCancelled()) return; final resolvedParams = await _resolveDraftModel(params, request); if (resolvedParams == null) return; @@ -2601,41 +2598,6 @@ class LlamaEngine { ); } - /// Rejects an image or audio part that the loaded multimodal projector - /// reports no encoder for. - /// - /// Without a projector, or when a probe cannot run, the backend's own media - /// check answers the request. - Future _rejectMediaInputWithoutEncoder( - Iterable parts, - ) async { - final mmContextHandle = _mmContextHandle; - if (mmContextHandle == null) return; - - final candidate = backend; - Future require(String kind, Future Function() probe) async { - final bool supported; - try { - supported = await probe(); - } catch (_) { - return; - } - if (supported) return; - throw LlamaUnsupportedException( - '$kind input is not supported by the loaded multimodal projector: it ' - 'reports no ${kind.toLowerCase()} encoder. Load a projector that has ' - 'one, or leave ${kind.toLowerCase()} parts out of the request.', - ); - } - - if (parts.any((part) => part is LlamaImageContent)) { - await require('Image', () => candidate.supportsVision(mmContextHandle)); - } - if (parts.any((part) => part is LlamaAudioContent)) { - await require('Audio', () => candidate.supportsAudio(mmContextHandle)); - } - } - /// Returns the optional [GenerationParams] controls that the loaded model's /// runtime applies. /// diff --git a/lib/src/core/template/chat_template_engine.dart b/lib/src/core/template/chat_template_engine.dart index 900d37ce5..252031730 100644 --- a/lib/src/core/template/chat_template_engine.dart +++ b/lib/src/core/template/chat_template_engine.dart @@ -347,9 +347,11 @@ class ChatTemplateEngine { return _normalizeGrammarLazyForToolChoice(withGrammar, toolChoice); } - /// Runs a handler [render], turning a failure that is not already a - /// [LlamaException] (a template's own `raise_exception`, a Jinja runtime - /// error, invalid template syntax) into a [LlamaInferenceException]. + /// Runs a handler [render], turning an [Exception] that is not already a + /// [LlamaException] (a template's own `raise_exception`, a failure the + /// Jinja runtime throws as an `Exception`, invalid template syntax) into a + /// [LlamaInferenceException]. An [Error] the renderer throws, such as an + /// integer division by zero or a stack overflow, is left as it is. static LlamaChatTemplateResult _renderTemplate( LlamaChatTemplateResult Function() render, ) { diff --git a/skills/llamadart-multimodal/SKILL.md b/skills/llamadart-multimodal/SKILL.md index 018782346..dd1a2dfce 100644 --- a/skills/llamadart-multimodal/SKILL.md +++ b/skills/llamadart-multimodal/SKILL.md @@ -42,7 +42,7 @@ description: >- values as `capabilities`. - Always check before sending media to a GGUF model. With no projector loaded, image or audio parts throw `LlamaUnsupportedException` on llama.cpp, native - and WebGPU, and so does a part the loaded projector reports no encoder for. + and WebGPU; on native so does a part the loaded projector cannot encode. - Put media in a message with `LlamaChatMessage.withContent(role: ..., content: [...])`, or pass the parts to `ChatSession.create`. Place media before the text that refers to it. diff --git a/test/e2e/tooling/qwen35_multimodal_macos_repro_e2e_test.dart b/test/e2e/tooling/qwen35_multimodal_macos_repro_e2e_test.dart index dc872e891..aff9b649a 100644 --- a/test/e2e/tooling/qwen35_multimodal_macos_repro_e2e_test.dart +++ b/test/e2e/tooling/qwen35_multimodal_macos_repro_e2e_test.dart @@ -193,7 +193,7 @@ Future _expectAudioRejected(LlamaEngine engine, String prompt) async { isA().having( (LlamaUnsupportedException error) => error.message, 'message', - contains('it reports no audio encoder'), + contains('it has no audio encoder'), ), ), ); diff --git a/test/integration/backends/webgpu/webgpu_engine_multimodal_browser_integration_test.dart b/test/integration/backends/webgpu/webgpu_engine_multimodal_browser_integration_test.dart index e828a6f0c..0138fdacc 100644 --- a/test/integration/backends/webgpu/webgpu_engine_multimodal_browser_integration_test.dart +++ b/test/integration/backends/webgpu/webgpu_engine_multimodal_browser_integration_test.dart @@ -18,6 +18,7 @@ void main() { late bool mmLoaded; late bool sawAudioPart; late int completionCalls; + late bool probesStale; String? lastStateSavePath; List? lastStateSaveTokens; String? lastStateLoadPath; @@ -38,6 +39,7 @@ void main() { mmLoaded = false; sawAudioPart = false; completionCalls = 0; + probesStale = false; lastStateSavePath = null; lastStateSaveTokens = null; lastStateLoadPath = null; @@ -141,7 +143,10 @@ void main() { }).toJS, ); bridge.setProperty('supportsVision'.toJS, (() => false).toJS); - bridge.setProperty('supportsAudio'.toJS, (() => mmLoaded).toJS); + bridge.setProperty( + 'supportsAudio'.toJS, + (() => mmLoaded && !probesStale).toJS, + ); bridge.setProperty( 'tokenize'.toJS, @@ -452,33 +457,44 @@ void main() { expect(sawAudioPart, isTrue); }); - test('LlamaEngine create rejects an image part for a projector with no ' - 'image encoder before the bridge', () async { + // The bridge's probes are a snapshot: after its worker falls back to the + // main thread they report false until the next media completion restores + // the projector. + test('LlamaEngine create forwards media parts when the bridge probes go ' + 'stale after loading the projector', () async { await engine.loadModelFromUrl( 'https://example.com/model.gguf', modelParams: const ModelParams(contextSize: 1024), ); await engine.loadMultimodalProjector('https://example.com/mmproj.gguf'); + expect(await engine.supportsAudio, isTrue); + probesStale = true; + expect(await engine.supportsAudio, isFalse); + expect(await engine.supportsVision, isFalse); - await expectLater( - engine.create([ + for (final LlamaContentPart media in [ + LlamaImageContent(bytes: Uint8List.fromList([1, 2, 3])), + LlamaAudioContent( + samples: Float32List.fromList([0.1, -0.2, 0.3]), + ), + ]) { + final chunks = await engine.create([ LlamaChatMessage.withContent( role: LlamaChatRole.user, content: [ - const LlamaTextContent('Describe this image.'), - LlamaImageContent(bytes: Uint8List.fromList([1, 2, 3])), + const LlamaTextContent('Describe this.'), + media, ], ), - ], params: const GenerationParams(maxTokens: 8)).drain(), - throwsA( - isA().having( - (error) => error.message, - 'message', - contains('it reports no image encoder'), - ), - ), - ); - expect(completionCalls, 0); + ], params: const GenerationParams(maxTokens: 8)).toList(); + + expect( + chunks.map((chunk) => chunk.choices.first.delta.content ?? '').join(), + contains('Hello'), + ); + } + expect(completionCalls, 2); + expect(sawAudioPart, isTrue); }); test('LlamaEngine embed and embedBatch work via web bridge', () async { diff --git a/test/support/fake_mtmd.dart b/test/support/fake_mtmd.dart index aabea0465..2fbe52901 100644 --- a/test/support/fake_mtmd.dart +++ b/test/support/fake_mtmd.dart @@ -12,7 +12,8 @@ import 'package:llamadart/src/backends/llama_cpp/mtmd_chunk_eval.dart'; import 'package:llamadart/src/core/models/chat/content_part.dart'; /// Stands in for libmtmd through [service]'s fallback API: a projector whose -/// one media part evaluates [tokens] as text. +/// one media part evaluates [tokens] as text. It reports an audio encoder and +/// no vision encoder unless told otherwise. /// /// It records the upstream mtmd function behind each call that creates, /// tokenizes with, evaluates with or frees the projector. A service on the @@ -28,6 +29,8 @@ final class FakeMtmd { this.chunkEval = false, this.decode = llama_decode, this.audioBitmap = _audioBitmap, + this.vision = false, + this.audio = true, }) { final owner = reflectClass(LlamaCppService).owner as LibraryMirror; final apiClass = @@ -35,7 +38,7 @@ final class FakeMtmd { as ClassMirror; Never unused([Object? _, Object? _, Object? _, Object? _, Object? _]) => throw StateError('unexpected mtmd call'); - final api = apiClass.newInstance(Symbol.empty, const [], { + _api = apiClass.newInstance(Symbol.empty, const [], { #defaultMarker: () => _marker.cast(), #contextParamsDefault: () => Struct.create(), #initFromFile: @@ -58,8 +61,8 @@ final class FakeMtmd { #helperBitmapInitFromBuf: unused, #bitmapInitFromAudio: (int sampleCount, Pointer _) => audioBitmap(sampleCount), - #supportsVision: (Pointer _) => false, - #supportsAudio: (Pointer _) => true, + #supportsVision: (Pointer _) => vision, + #supportsAudio: (Pointer _) => audio, #supportsVideo: (Pointer _) => false, #bitmapFree: (Pointer bitmap) { freedBitmaps.add(bitmap.address); @@ -95,9 +98,11 @@ final class FakeMtmd { }).reflectee; _setPrivate('_mtmdPrimarySymbolsUnavailable', true); _setPrivate('_mtmdFallbackLookupAttempted', true); - _setPrivate('_mtmdFallbackApi', api); + _setPrivate('_mtmdFallbackApi', _api); } + late final Object _api; + /// The projector the fake `mtmd_init_from_file` returns. static final Pointer projector = Pointer.fromAddress(0x30); @@ -117,6 +122,12 @@ final class FakeMtmd { /// part of a sample count; a null pointer fails that part. final Pointer Function(int sampleCount) audioBitmap; + /// Whether the fake `mtmd_support_vision` reports a vision encoder. + final bool vision; + + /// Whether the fake `mtmd_support_audio` reports an audio encoder. + final bool audio; + /// Upstream mtmd functions called on the projector so far, in order. final List calls = []; @@ -173,6 +184,12 @@ final class FakeMtmd { static Pointer _audioBitmap(int _) => Pointer.fromAddress(0x20); + /// Leaves [service] with neither its own mtmd functions nor a fallback + /// library, as a native runtime that lacks them does, when [present] is + /// false; puts this fake back when it is true. + void setFallback({required bool present}) => + _setPrivate('_mtmdFallbackApi', present ? _api : null); + /// Frees the marker text; call after the service is disposed. void dispose() => malloc.free(_marker); diff --git a/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart index b0d9eae6e..c346ffea7 100644 --- a/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart +++ b/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart @@ -548,7 +548,11 @@ void main() { Future describe() => _generate(service, context, '<__media__>', _greedy, parts: mtmd!.parts); - void attach({bool chunkEval = false}) { + void attach({ + bool chunkEval = false, + bool vision = false, + bool audio = true, + }) { start(); final projectorPath = '${dir.path}/mmproj.gguf'; File(projectorPath).writeAsStringSync('GGUF'); @@ -557,6 +561,8 @@ void main() { tokens: service.tokenize(model, 'ab', true), chunkEval: chunkEval, decode: recorder.api.decode, + vision: vision, + audio: audio, ); addTearDown(fake.dispose); projector = service.createMultimodalContext(model, projectorPath); @@ -576,6 +582,82 @@ void main() { ); }); + group('a media part of a kind the projector has no encoder for', () { + final image = LlamaImageContent(bytes: Uint8List.fromList(const [1])); + final audio = LlamaAudioContent(samples: Float32List(1)); + + Matcher noEncoder(String kind) => throwsA( + isA().having( + (e) => e.message, + 'message', + '$kind input is not supported by the loaded multimodal projector: ' + 'it has no ${kind.toLowerCase()} encoder. Load a projector ' + 'that has one, or leave ${kind.toLowerCase()} parts out of the ' + 'request.', + ), + ); + + Future send(List parts) => + _generate( + service, + context, + '<__media__>' * parts.length, + _greedy, + parts: parts, + ); + + Iterable mediaCalls() => [ + ...barrier.calls, + ...mtmd!.calls, + ].where((call) => call.contains('mtmd_')); + + test('is refused by name before mtmd is given the request, and the ' + 'kind it encodes still generates', () async { + attach(); + barrier.calls.clear(); + mtmd!.calls.clear(); + + await expectLater(send([image]), noEncoder('Image')); + await expectLater(send([audio, image]), noEncoder('Image')); + expect(mediaCalls(), isEmpty); + + expect(await send([audio]), BackendGenerationLimit.maxTokens); + expect(mediaCalls(), isNotEmpty); + }); + + test('is refused by name on a projector with a vision encoder ' + 'only', () async { + attach(vision: true, audio: false); + barrier.calls.clear(); + mtmd!.calls.clear(); + + await expectLater(send([audio]), noEncoder('Audio')); + expect(mediaCalls(), isEmpty); + }); + + test('is not blamed on the projector when the runtime lacks the mtmd ' + 'probe', () async { + attach(); + mtmd!.setFallback(present: false); + // The projector is freed through the fallback. + addTearDown(() => mtmd!.setFallback(present: true)); + + await expectLater( + send([image]), + throwsA( + isA().having( + (e) => '$e', + 'text', + allOf( + contains('lacks an mtmd function'), + isNot(contains('encoder')), + ), + ), + ), + ); + }); + }); + test('builds media bitmaps through the barrier, and a constructor that ' 'throws is a typed error', () async { attach(); diff --git a/test/unit/backends/llama_cpp/llama_cpp_service_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_test.dart index 16d945b15..ef5750495 100644 --- a/test/unit/backends/llama_cpp/llama_cpp_service_test.dart +++ b/test/unit/backends/llama_cpp/llama_cpp_service_test.dart @@ -33,6 +33,7 @@ import 'package:llamadart/src/hook/native_release_pins.dart'; import 'package:path/path.dart' as path; import 'package:test/test.dart'; +import '../../../support/fake_mtmd.dart'; import '../../../support/recording_exit_teardown.dart'; import '../../../support/synthetic_decision_head.dart'; import '../../../support/synthetic_embedding_gguf.dart'; @@ -2952,27 +2953,35 @@ void main() { ); }); - test('accepts local image paths and encoded bytes with a projector', () { - void check(List parts, {required bool projector}) => + test('accepts local image paths and encoded bytes with a projector that ' + 'has both encoders', () { + final fake = FakeMtmd.install( + service, + tokens: const [], + vision: true, + audio: true, + ); + addTearDown(fake.dispose); + registerFakeProjector(); + void check(List parts) => _invokePrivateForTesting( service, '_checkLlamaCppMediaParts', [parts], - {#projectorLoaded: projector}, + {#mmHandle: fakeMtmdHandle}, ); - check(const [LlamaImageContent(path: '/tmp/image.png')], projector: true); + check(const [LlamaImageContent(path: '/tmp/image.png')]); check([ LlamaImageContent( bytes: Uint8List.fromList([1, 2, 3]), url: 'https://example.com/a.png', ), LlamaAudioContent(samples: Float32List(16)), - ], projector: true); + ]); expect( - () => check(const [ - LlamaImageContent(url: 'https://example.com/a.png'), - ], projector: true), + () => + check(const [LlamaImageContent(url: 'https://example.com/a.png')]), throwsA(isA()), ); }); diff --git a/test/unit/core/engine/engine_test.dart b/test/unit/core/engine/engine_test.dart index 877219129..7fdf24adb 100644 --- a/test/unit/core/engine/engine_test.dart +++ b/test/unit/core/engine/engine_test.dart @@ -35,8 +35,7 @@ class MockLlamaBackend this.contextFreeDelay, this.nativeVideoRuntimeSupported = false, this.videoProbeError, - this.projectorSupportsAudio = false, - this.audioProbeError, + this.generationError, }); Object? modelLoadError; @@ -61,6 +60,7 @@ class MockLlamaBackend String generationText = 'response'; List? generationChunks; String? lastGenerationPrompt; + List? lastGenerationParts; GenerationParams? lastGenerationParams; final String backendName; final bool urlLoadingSupported; @@ -76,8 +76,7 @@ class MockLlamaBackend Future? contextFreeDelay; final bool? nativeVideoRuntimeSupported; final Object? videoProbeError; - final bool projectorSupportsAudio; - final Object? audioProbeError; + final Object? generationError; int? lastVideoProbeHandle; @override @@ -153,7 +152,11 @@ class MockLlamaBackend List? parts, }) async* { lastGenerationPrompt = prompt; + lastGenerationParts = parts; lastGenerationParams = params; + if (generationError case final error?) { + throw error; + } if (generationChunks != null) { for (final chunk in generationChunks!) { yield utf8.encode(chunk); @@ -260,12 +263,7 @@ class MockLlamaBackend Future supportsVision(int mmContextHandle) async => true; @override - Future supportsAudio(int mmContextHandle) async { - if (audioProbeError case final error?) { - throw error; - } - return projectorSupportsAudio; - } + Future supportsAudio(int mmContextHandle) async => false; @override Future supportsVideoRuntime(int mmContextHandle) async { @@ -2495,7 +2493,10 @@ void main() { } }); - group('media the loaded projector has no encoder for', () { + // The backend decides whether it takes a media part. A projector probe + // that answers false does not: the WebGPU bridge reports a stale false + // after its worker fallback, and a custom backend may not implement it. + group('media the projector probe reports no encoder for', () { const visionOnlyTemplate = '{% for message in messages %}' '{% if message.content is string %}{{ message.content }}' @@ -2513,6 +2514,7 @@ void main() { addTearDown(engine.dispose); await engine.loadModel('qwen-test.gguf'); await engine.loadMultimodalProjector('proj.gguf'); + expect(await engine.supportsAudio, isFalse); return engine; } @@ -2523,22 +2525,12 @@ void main() { ), ]; - final noAudioEncoder = throwsA( - isA().having( - (error) => error.message, - 'message', - 'Audio input is not supported by the loaded multimodal projector: ' - 'it reports no audio encoder. Load a projector that has one, or ' - 'leave audio parts out of the request.', - ), - ); - for (final MapEntry(key: label, value: media) in { - 'an audio part': [audio], - 'an audio part next to an image': [image, audio], + 'an audio part': [audio], + 'an audio part next to an image': [image, audio], }.entries) { - test('create rejects $label for a vision-only template before ' - 'rendering it', () async { + test('create sends $label to the backend, as media markers for a ' + 'vision-only template', () async { final backend = MockLlamaBackend( modelMetadataResponse: { 'tokenizer.chat_template': visionOnlyTemplate, @@ -2546,27 +2538,28 @@ void main() { ); final engine = await loaded(backend); - await expectLater( - engine.create(request(media)).drain(), - noAudioEncoder, + await engine.create(request(media)).drain(); + + expect( + backend.lastGenerationPrompt, + 'Describe:${'<__media__>' * media.length}', ); - expect(backend.lastGenerationPrompt, isNull); + expect(backend.lastGenerationParts, containsAll(media)); }); } - test('generate rejects an audio part', () async { + test('generate sends an audio part to the backend', () async { final backend = MockLlamaBackend(); final engine = await loaded(backend); - await expectLater( - engine.generate('describe', parts: [audio]).drain(), - noAudioEncoder, - ); - expect(backend.lastGenerationPrompt, isNull); + await engine.generate('describe', parts: [audio]).drain(); + + expect(backend.lastGenerationPrompt, 'describe'); + expect(backend.lastGenerationParts, [audio]); }); - test('create sends an image part, which the projector encodes, as a ' - 'typed part', () async { + test('create sends an image part to a vision-only template as a typed ' + 'part', () async { final backend = MockLlamaBackend( modelMetadataResponse: { 'tokenizer.chat_template': visionOnlyTemplate, @@ -2577,46 +2570,26 @@ void main() { await engine.create(request([image])).drain(); expect(backend.lastGenerationPrompt, 'Describe:[image part]'); + expect(backend.lastGenerationParts, contains(image)); }); - test('create sends audio to a vision-only template as the media ' - 'marker when the projector encodes audio', () async { + test('create passes on the typed error of a backend that refuses the ' + 'part', () async { final backend = MockLlamaBackend( - projectorSupportsAudio: true, - modelMetadataResponse: { - 'tokenizer.chat_template': visionOnlyTemplate, - }, + generationError: LlamaUnsupportedException('no audio encoder'), ); final engine = await loaded(backend); - await engine.create(request([image, audio])).drain(); - - expect(backend.lastGenerationPrompt, 'Describe:<__media__><__media__>'); - }); - - test( - 'a probe that cannot run leaves the request to the backend', - () async { - final backend = MockLlamaBackend( - audioProbeError: LlamaUnsupportedException('probe unavailable'), - ); - final engine = await loaded(backend); - - await engine.generate('describe', parts: [audio]).drain(); - - expect(backend.lastGenerationPrompt, 'describe'); - }, - ); - - test('without a projector the request reaches the backend', () async { - final backend = MockLlamaBackend(); - final engine = LlamaEngine(backend); - addTearDown(engine.dispose); - await engine.loadModel('qwen-test.gguf'); - - await engine.generate('describe', parts: [audio]).drain(); - - expect(backend.lastGenerationPrompt, 'describe'); + await expectLater( + engine.create(request([audio])).drain(), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'no audio encoder', + ), + ), + ); }); }); diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 3022a99e2..aa1a31e5e 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -98,13 +98,15 @@ For canonical full release notes, use: `f823b10417b212ff1f66aa1c46bf78af7d9c393497dfcf0fa3a4f77adeb260eb`. - Fix an audio or video part sent to a chat template that takes typed image parts only (Qwen3.5 and others) failing with a raw `Exception` from the - template ([#963](https://github.com/leehack/llamadart/issues/963)). - `LlamaEngine.create` and `generate` now throw `LlamaUnsupportedException` - naming the missing encoder when the loaded GGUF projector does not take an - image or audio part, where an untyped runtime failure surfaced as - `LlamaInferenceException` before. `chatTemplate` renders a part the - template rejects as the media marker, and a chat template that fails to - render throws `LlamaInferenceException` with the template's message. + template ([#963](https://github.com/leehack/llamadart/issues/963)). On + native llama.cpp, an image or audio part the loaded projector has no + encoder for now throws `LlamaUnsupportedException` naming the encoder, + where `create` and `generate` threw `LlamaInferenceException` or the + template's exception. `chatTemplate` renders as the media marker a media + part the template rejects and a video part beside an image or audio part, + which a template was handed and raised on or dropped. A chat template that + raises or has invalid syntax throws `LlamaInferenceException` with the + template's message. ## 0.11.1 diff --git a/website/docs/guides/multimodal.md b/website/docs/guides/multimodal.md index b909f5983..8adc177f7 100644 --- a/website/docs/guides/multimodal.md +++ b/website/docs/guides/multimodal.md @@ -119,8 +119,9 @@ Always prefer these runtime checks over model-card assumptions. Read projector loaded, a GGUF model (native `llama.cpp` or WebGPU) rejects image and audio parts with `LlamaUnsupportedException` instead of answering from the text alone. A loaded projector can expose only a subset of the family-level -modalities, and a part it reports no encoder for (audio with a vision-only -projector, for example) is rejected the same way. The current Gemma 4 E2B GGUF projector path in native `llama.cpp` +modalities, and on native `llama.cpp` a part it has no encoder for (audio +with a vision-only projector, for example) is rejected the same way. The +current Gemma 4 E2B GGUF projector path in native `llama.cpp` mtmd reports both vision and audio support; audio remains experimental upstream. Web continues to rely on the loaded bridge's runtime capability report.