From 9f6d531920c41b31fca95686c1c69258280f9ff7 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 11:58:57 -0400 Subject: [PATCH 1/2] fix: type the errors for media a projector cannot encode and for chat template failures On native llama.cpp, image or audio input that the loaded projector has no encoder for failed with an untyped `Failed to load media part N` or `mtmd_tokenize failed: 2`. A chat template that raised or had invalid syntax threw a raw `Exception` or dinja `ParserException`. - When mtmd fails to load or tokenize media, the llama.cpp service asks the projector which encoders it has and throws `LlamaUnsupportedException` naming the missing one. The kind of a path or of encoded bytes is read from the content, as mtmd reads it, not from the type of the part, and every part reaches mtmd as before. A runtime without the probe function keeps the mtmd error. - `ChatTemplateEngine.render` turns an `Exception` from a handler render into `LlamaInferenceException` with the template's message. Closes #963 --- CHANGELOG.md | 6 + .../backends/llama_cpp/llama_cpp_service.dart | 102 ++++++-- lib/src/core/engine/engine.dart | 8 + .../core/template/chat_template_engine.dart | 63 +++-- skills/llamadart-multimodal/SKILL.md | 2 +- ...wen35_multimodal_macos_repro_e2e_test.dart | 96 +++++++ test/support/fake_mtmd.dart | 58 ++++- .../llama_cpp_service_media_encoder_test.dart | 245 ++++++++++++++++++ test/unit/core/engine/engine_test.dart | 30 +++ .../template/chat_template_engine_test.dart | 105 ++++++++ website/docs/changelog/recent-releases.md | 6 + website/docs/guides/multimodal.md | 4 +- .../docs/guides/template-engine-internals.md | 2 + 13 files changed, 679 insertions(+), 48 deletions(-) create mode 100644 test/unit/backends/llama_cpp/llama_cpp_service_media_encoder_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 076c565b4..eccf41551 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -118,6 +118,12 @@ `package:llamadart/backend.dart` now exports. A prompt written for `generate` keeps its placeholders, and `chatTemplate` output for messages without media is unchanged. +- On native llama.cpp, image or audio input that the loaded projector has no + encoder for throws `LlamaUnsupportedException` naming the encoder, where + `create` and `generate` threw `LlamaInferenceException`. A chat template + that raises or has invalid syntax throws `LlamaInferenceException` with the + template's message instead of a raw `Exception` + ([#963](https://github.com/leehack/llamadart/issues/963)). ## 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 fdf0f8aed..4f5dfe13d 100644 --- a/lib/src/backends/llama_cpp/llama_cpp_service.dart +++ b/lib/src/backends/llama_cpp/llama_cpp_service.dart @@ -5828,7 +5828,8 @@ class LlamaCppService { LlamaInferenceException.new, windowsFreeOnly: [mmCtx], ); - throw Exception("Failed to load media part $i"); + throw _missingEncoderFor(mmCtx, [p]) ?? + Exception("Failed to load media part $i"); } } @@ -5913,7 +5914,8 @@ class LlamaCppService { malloc.free(newPast); } } else { - throw Exception("mtmd_tokenize failed: $res"); + throw _missingEncoderFor(mmCtx, mediaParts) ?? + Exception("mtmd_tokenize failed: $res"); } } finally { // Free in finally so a tokenize/eval failure above does not leak the @@ -8815,17 +8817,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. @@ -8834,22 +8826,94 @@ 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'), - ); + if (fallback == null) return null; + return audio + ? fallback.supportsAudio(mmCtx) + : fallback.supportsVision(mmCtx); + } + + /// The error for [parts] that mtmd failed to load or tokenize when the + /// projector [mmCtx] reports no encoder for the kind of one of them, and + /// null otherwise, as when the runtime lacks the probe function. + LlamaUnsupportedException? _missingEncoderFor( + Pointer mmCtx, + List parts, + ) { + final readAsAudio = parts.map(_mtmdReadsAsAudio).toList(growable: false); + for (final (kind, audio) in const [('Image', false), ('Audio', true)]) { + if (readAsAudio.contains(audio) && + _mtmdHasEncoder(mmCtx, audio: audio) == false) { + return 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()} input out of the request.', + ); + } + } + return null; + } + + /// Whether mtmd reads [part] as audio rather than as an image, or null + /// when its source cannot be read. + /// + /// mtmd decides by content for a path or encoded bytes, whatever the type + /// of the part: this is `is_audio_file` of llama.cpp's `mtmd-helper.cpp`. + static bool? _mtmdReadsAsAudio(LlamaContentPart part) { + final (path, bytes) = switch (part) { + LlamaImageContent() => (part.path, part.bytes), + LlamaAudioContent() => (part.path, part.bytes), + _ => (null, null), + }; + final List head; + if (path != null) { + try { + final file = File(path).openSync(); + try { + head = file.readSync(12); + } finally { + file.closeSync(); + } + } on FileSystemException { + return null; + } + } else if (bytes != null) { + head = bytes; + } else { + return part is LlamaAudioContent ? true : null; } - return fallback.supportsAudio(mmCtx); + if (head.length < 12) return false; + bool has(String magic, [int offset = 0]) { + for (var i = 0; i < magic.length; i++) { + if (head[offset + i] != magic.codeUnitAt(i)) return false; + } + return true; + } + + return has('RIFF') && has('WAVE', 8) || + has('ID3') || + head[0] == 0xFF && head[1] & 0xE0 == 0xE0 || + has('fLaC'); } /// 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 9b9de4f93..de0ed6fa0 100644 --- a/lib/src/core/engine/engine.dart +++ b/lib/src/core/engine/engine.dart @@ -1544,6 +1544,11 @@ class LlamaEngine { /// parse compatible best-effort tool-call text, but it does not currently /// enforce arbitrary JSON-schema constraints. /// + /// On native llama.cpp, image or audio input 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 /// final messages = [ @@ -1787,6 +1792,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. + /// /// For messages that carry image, audio or video parts the prompt has /// `<__media__>` where each part was, and [generate] takes it with those /// parts. A string in a message that [generate] would also read as a part diff --git a/lib/src/core/template/chat_template_engine.dart b/lib/src/core/template/chat_template_engine.dart index 7ea0bbe84..70233e66a 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'; @@ -123,6 +124,9 @@ class ChatTemplateEngine { /// [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. + /// /// [mediaMarker] is written where each image, audio or video part was. /// Pass one that message text cannot hold to tell the parts from a /// placeholder string a message quotes. @@ -274,14 +278,16 @@ class ChatTemplateEngine { '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, - mediaMarker: mediaMarker, + var rendered = _renderTemplate( + () => handler.renderWithMultimodalContent( + templateSource: effectiveTemplate ?? GenericHandler.chatMlTemplate, + messages: effectiveMessages, + metadata: handlerMetadata, + addAssistant: addAssistant, + tools: effectiveTools, + enableThinking: enableThinking, + mediaMarker: mediaMarker, + ), ); if (effectiveFormat == ChatFormat.contentOnly) { rendered = _withFormat(rendered, ChatFormat.contentOnly.index); @@ -319,13 +325,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) { @@ -342,6 +350,31 @@ class ChatTemplateEngine { return _normalizeGrammarLazyForToolChoice(withGrammar, toolChoice); } + /// 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, + ) { + 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/skills/llamadart-multimodal/SKILL.md b/skills/llamadart-multimodal/SKILL.md index 1369050da..fbfeccadf 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; on native so does input 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 ee10c6524..84e703810 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,9 @@ Future _runScenario({ reason: 'Expected Qwen3.5 0.8B + mmproj to report vision support.', ); + await _expectAudioRefusedByName(engine, prompt); + await _expectImageSentAsAudioAnswered(engine, imageFile, prompt); + final GenerationParams generationParams = GenerationParams( maxTokens: maxTokens, temp: 0.2, @@ -169,6 +173,98 @@ Future _runScenario({ } } +/// The Qwen3.5 projector has no audio encoder: audio is refused by name, +/// from PCM samples at mtmd's tokenize and from an encoded file at its load. +Future _expectAudioRefusedByName( + LlamaEngine engine, + String prompt, +) async { + expect(await engine.supportsAudio, isFalse); + final File wav = File( + path.join(Directory.systemTemp.path, 'llamadart_qwen35_repro_tone.wav'), + )..writeAsBytesSync(_silentWav(seconds: 1)); + + for (final LlamaAudioContent audio in [ + LlamaAudioContent(samples: Float32List(16000)), + LlamaAudioContent(bytes: wav.readAsBytesSync()), + LlamaAudioContent(path: wav.path), + ]) { + stdout.writeln('Sending audio to the vision-only projector...'); + await expectLater( + engine.create([ + LlamaChatMessage.withContent( + role: LlamaChatRole.user, + content: [audio, LlamaTextContent(prompt)], + ), + ]).drain(), + throwsA( + isA().having( + (LlamaUnsupportedException error) => error.message, + 'message', + contains('it has no audio encoder'), + ), + ), + ); + } +} + +/// mtmd reads encoded bytes by content, so an image sent as an audio part is +/// an image to the projector and is answered. +Future _expectImageSentAsAudioAnswered( + LlamaEngine engine, + File imageFile, + String prompt, +) async { + stdout.writeln('Sending the image as an audio part...'); + final String answer = await engine + .create( + [ + LlamaChatMessage.withContent( + role: LlamaChatRole.user, + content: [ + LlamaAudioContent(bytes: imageFile.readAsBytesSync()), + LlamaTextContent(prompt), + ], + ), + ], + params: const GenerationParams(maxTokens: 16, temp: 0), + enableThinking: false, + ) + .map( + (LlamaCompletionChunk chunk) => chunk.choices.first.delta.content ?? '', + ) + .join(); + stdout.writeln(' imageAsAudio.outputPreview: ${_truncateForLog(answer)}'); + expect(answer.trim(), isNotEmpty); +} + +/// A mono 16 kHz PCM16 WAV of silence. +Uint8List _silentWav({required int seconds}) { + const int sampleRate = 16000; + final int dataBytes = sampleRate * seconds * 2; + final ByteData header = ByteData(44) + ..setUint32(4, 36 + dataBytes, Endian.little) + ..setUint32(16, 16, Endian.little) + ..setUint16(20, 1, Endian.little) + ..setUint16(22, 1, Endian.little) + ..setUint32(24, sampleRate, Endian.little) + ..setUint32(28, sampleRate * 2, Endian.little) + ..setUint16(32, 2, Endian.little) + ..setUint16(34, 16, Endian.little) + ..setUint32(40, dataBytes, Endian.little); + final Uint8List wav = Uint8List(44 + dataBytes) + ..setAll(0, header.buffer.asUint8List()); + for (final (int offset, String tag) in <(int, String)>[ + (0, 'RIFF'), + (8, 'WAVE'), + (12, 'fmt '), + (36, 'data'), + ]) { + wav.setAll(offset, tag.codeUnits); + } + return wav; +} + Future _runSessionTurn({ required ChatSession session, required List parts, diff --git a/test/support/fake_mtmd.dart b/test/support/fake_mtmd.dart index c11a337cb..7b1b8d74c 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,14 +29,20 @@ 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 = owner.declarations[MirrorSystem.getSymbol('_MtmdApi', owner)] as ClassMirror; - Never unused([Object? _, Object? _, Object? _, Object? _, Object? _]) => - throw StateError('unexpected mtmd call'); - final api = apiClass.newInstance(Symbol.empty, const [], { + mtmd_helper_bitmap_wrapper encodedBitmap() { + final wrapper = Struct.create(); + if (encodedBitmapLoads) wrapper.bitmap = _encodedBitmap; + return wrapper; + } + + _api = apiClass.newInstance(Symbol.empty, const [], { #defaultMarker: () => _marker.cast(), #contextParamsDefault: () => Struct.create(), #initFromFile: @@ -54,7 +61,13 @@ final class FakeMtmd { #inputChunksInit: () => Pointer.fromAddress(0x10), #inputChunksFree: (Pointer _) {}, #helperInitOptDefault: () => Struct.create(), - #helperBitmapInitFromFile: unused, + #helperBitmapInitFromFile: + ( + Pointer _, + Pointer _, + bool _, + mtmd_helper_init_opt _, + ) => encodedBitmap(), #helperBitmapInitFromBuf: ( Pointer _, @@ -62,13 +75,11 @@ final class FakeMtmd { int _, bool _, mtmd_helper_init_opt _, - ) => - Struct.create() - ..bitmap = _encodedBitmap, + ) => encodedBitmap(), #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); @@ -87,7 +98,7 @@ final class FakeMtmd { length: text.ref.text_len, ), ); - return 0; + return tokenizeResult; }, #helperEvalChunks: ( @@ -109,9 +120,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); @@ -131,6 +144,21 @@ 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; + + /// Whether the fake bitmap helpers load a path or encoded bytes; when + /// false they return a null bitmap, as mtmd does for a source it cannot + /// decode and for audio on a projector without an audio encoder. + bool encodedBitmapLoads = true; + + /// What the fake `mtmd_tokenize` returns; mtmd returns 2 for a bitmap the + /// projector has no encoder for. + int tokenizeResult = 0; + /// Upstream mtmd functions called on the projector so far, in order. final List calls = []; @@ -193,6 +221,12 @@ final class FakeMtmd { /// The bitmap the fake gives an encoded image or audio part. static final Pointer _encodedBitmap = Pointer.fromAddress(0x21); + /// 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_media_encoder_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_media_encoder_test.dart new file mode 100644 index 000000000..36219322a --- /dev/null +++ b/test/unit/backends/llama_cpp/llama_cpp_service_media_encoder_test.dart @@ -0,0 +1,245 @@ +@TestOn('vm') +library; + +import 'dart:ffi'; +import 'dart:io'; +import 'dart:mirrors'; +import 'dart:typed_data'; + +import 'package:ffi/ffi.dart'; +import 'package:llamadart/src/backends/llama_cpp/exit_teardown_api.dart'; +import 'package:llamadart/src/backends/llama_cpp/llama_cpp_service.dart'; +import 'package:llamadart/src/core/exceptions.dart'; +import 'package:llamadart/src/core/models/chat/content_part.dart'; +import 'package:llamadart/src/core/models/inference/generation_params.dart'; +import 'package:llamadart/src/core/models/inference/model_params.dart'; +import 'package:test/test.dart'; + +import '../../../support/fake_mtmd.dart'; +import '../../../support/synthetic_embedding_gguf.dart'; + +const _params = ModelParams(gpuLayers: 0, contextSize: 64); +const _greedy = GenerationParams(maxTokens: 1, temp: 0, topK: 1, seed: 1); + +// The first bytes mtmd reads to tell audio from an image. +final Uint8List _png = Uint8List.fromList([ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0x0d, // + 0x49, 0x48, 0x44, 0x52, +]); +final Uint8List _wav = Uint8List.fromList( + 'RIFF\x24\x00\x00\x00WAVEfmt '.codeUnits, +); +final Uint8List _mp3 = Uint8List.fromList([0xff, 0xfb, ...List.filled(12, 0)]); +final Uint8List _flac = Uint8List.fromList( + 'fLaC\x00\x00\x00\x22data'.codeUnits, +); + +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()} input out of the request.', + ), +); + +Matcher _untyped(String text) => throwsA( + isA() + .having((e) => e, 'type', isNot(isA())) + .having((e) => '$e', 'text', 'Exception: $text'), +); + +// Runs the real llama.cpp runtime on the CPU with a fake projector whose +// encoders, bitmap loading and tokenize result each test sets. +void main() { + late Directory dir; + late LlamaCppService service; + late FakeMtmd fake; + late int context; + + void attach({required bool vision, required bool audio}) { + dir = Directory.systemTemp.createTempSync('llamadart_media_encoder_'); + addTearDown(() => dir.deleteSync(recursive: true)); + final modelPath = writeSyntheticLlamaGguf('${dir.path}/model.gguf').path; + service = LlamaCppService(objectCalls: LlamaCppObjectCalls.upstream) + ..initializeBackend(); + final model = service.loadModel(modelPath, _params); + fake = FakeMtmd.install( + service, + tokens: service.tokenize(model, 'ab', true), + vision: vision, + audio: audio, + ); + addTearDown(fake.dispose); + addTearDown(service.dispose); + context = service.createContext(model, _params); + final projectorPath = '${dir.path}/mmproj.gguf'; + File(projectorPath).writeAsStringSync('GGUF'); + service.createMultimodalContext(model, projectorPath); + fake.calls.clear(); + } + + String file(String name, List bytes) => + (File('${dir.path}/$name')..writeAsBytesSync(bytes)).path; + + Future send(List parts) async { + final cancel = calloc(); + try { + await service + .generate( + context, + '<__media__>' * parts.length, + _greedy, + cancel.address, + parts: parts, + ) + .drain(); + } finally { + calloc.free(cancel); + } + } + + group('a projector with a vision encoder only', () { + setUp(() => attach(vision: true, audio: false)); + + test('names the audio encoder when mtmd cannot load encoded audio, ' + 'whatever the type of the part', () async { + fake.encodedBitmapLoads = false; + + for (final audio in [_wav, _mp3, _flac]) { + await expectLater( + send([LlamaAudioContent(bytes: audio)]), + _noEncoder('Audio'), + ); + } + await expectLater( + send([LlamaAudioContent(path: file('clip.wav', _wav))]), + _noEncoder('Audio'), + ); + await expectLater( + send([LlamaImageContent(bytes: _wav)]), + _noEncoder('Audio'), + ); + await expectLater( + send([LlamaAudioContent(bytes: _wav), LlamaImageContent(bytes: _png)]), + _noEncoder('Audio'), + ); + expect(fake.calls, isNot(contains('mtmd_tokenize'))); + }); + + test('names the audio encoder when mtmd refuses PCM samples', () async { + fake.tokenizeResult = 2; + + await expectLater( + send([LlamaAudioContent(samples: Float32List(1))]), + _noEncoder('Audio'), + ); + expect(fake.calls, contains('mtmd_tokenize')); + }); + + test('hands mtmd an image sent as an audio part, by bytes and by ' + 'path', () async { + await send([LlamaAudioContent(bytes: _png)]); + await send([LlamaAudioContent(path: file('page.png', _png))]); + + expect(fake.calls.where((call) => call == 'mtmd_tokenize'), hasLength(2)); + expect(fake.evaluations, 2); + }); + + test('keeps the load error of an image mtmd cannot decode', () async { + fake.encodedBitmapLoads = false; + + await expectLater( + send([LlamaAudioContent(bytes: _png)]), + _untyped('Failed to load media part 0'), + ); + await expectLater( + send([LlamaImageContent(path: '${dir.path}/missing.png')]), + _untyped('Failed to load media part 0'), + ); + }); + + test('keeps the tokenize error of an image request', () async { + fake.tokenizeResult = 2; + + await expectLater( + send([LlamaImageContent(bytes: _png)]), + _untyped('mtmd_tokenize failed: 2'), + ); + }); + }); + + group('a projector with an audio encoder only', () { + setUp(() => attach(vision: false, audio: true)); + + test('names the image encoder when mtmd refuses an image, whatever the ' + 'type of the part', () async { + fake.tokenizeResult = 2; + + await expectLater( + send([LlamaImageContent(bytes: _png)]), + _noEncoder('Image'), + ); + await expectLater( + send([LlamaImageContent(path: file('page.png', _png))]), + _noEncoder('Image'), + ); + await expectLater( + send([LlamaAudioContent(bytes: _png)]), + _noEncoder('Image'), + ); + await expectLater( + send([LlamaAudioContent(bytes: _wav), LlamaImageContent(bytes: _png)]), + _noEncoder('Image'), + ); + }); + + test('hands mtmd audio sent as an image part, by bytes and by ' + 'path', () async { + await send([LlamaImageContent(bytes: _wav)]); + await send([LlamaImageContent(path: file('clip.wav', _wav))]); + + expect(fake.calls.where((call) => call == 'mtmd_tokenize'), hasLength(2)); + expect(fake.evaluations, 2); + }); + + test('keeps the errors of an audio request', () async { + fake.tokenizeResult = 2; + await expectLater( + send([LlamaAudioContent(samples: Float32List(1))]), + _untyped('mtmd_tokenize failed: 2'), + ); + + fake + ..tokenizeResult = 0 + ..encodedBitmapLoads = false; + await expectLater( + send([LlamaAudioContent(bytes: _wav)]), + _untyped('Failed to load media part 0'), + ); + }); + }); + + test('a runtime without the mtmd encoder probe leaves the mtmd error as it ' + 'is', () { + attach(vision: false, audio: false); + final owner = reflectClass(LlamaCppService).owner as LibraryMirror; + Object? missingEncoder() => reflect(service).invoke( + MirrorSystem.getSymbol('_missingEncoderFor', owner), + [ + FakeMtmd.projector, + [ + LlamaImageContent(bytes: _png), + LlamaAudioContent(samples: Float32List(1)), + ], + ], + ).reflectee; + + expect(missingEncoder(), isA()); + fake.setFallback(present: false); + // The projector is freed through the fallback. + addTearDown(() => fake.setFallback(present: true)); + expect(missingEncoder(), isNull); + }); +} diff --git a/test/unit/core/engine/engine_test.dart b/test/unit/core/engine/engine_test.dart index cd9e2d986..1827b7c32 100644 --- a/test/unit/core/engine/engine_test.dart +++ b/test/unit/core/engine/engine_test.dart @@ -2486,6 +2486,36 @@ void main() { } }); + 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 242aa25fa..212588c5e 100644 --- a/test/unit/core/template/chat_template_engine_test.dart +++ b/test/unit/core/template/chat_template_engine_test.dart @@ -520,6 +520,111 @@ void main() { } }); + 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 %}'; + const twoUserTurns = [ + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'a'), + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'b'), + ]; + + 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: twoUserTurns, + metadata: const {}, + ), + throwsRenderFailure( + 'The chat template failed to render: ' + 'Conversation roles must alternate', + ), + ); + }); + + test('throws a typed exception when it raises in a request with ' + 'media', () { + // Reads strings and part lists, so a request with media takes the + // other handler call. + const alternatingPartLists = + '{% for message in messages %}' + '{% if loop.index0 > 0 and ' + 'message.role == messages[loop.index0 - 1].role %}' + "{{ raise_exception('Conversation roles must alternate') }}" + '{% endif %}' + '{% if message.content is string %}{{ message.content }}' + '{% else %}{% for part in message.content %}{{ part.text }}' + '{% endfor %}{% endif %}' + '{% endfor %}'; + const image = LlamaChatMessage.withContent( + role: LlamaChatRole.user, + content: [ + LlamaTextContent('Describe:'), + LlamaImageContent(path: '/tmp/page.png'), + ], + ); + + expect( + ChatTemplateEngine.render( + templateSource: alternatingPartLists, + messages: const [image], + metadata: const {}, + ).prompt, + 'Describe:<__media__>', + ); + expect( + () => ChatTemplateEngine.render( + templateSource: alternatingPartLists, + messages: const [image, image], + metadata: const {}, + ), + throwsRenderFailure( + 'The chat template failed to render: ' + 'Conversation roles must alternate', + ), + ); + }); + + test('throws a typed exception for invalid template syntax', () { + expect( + () => ChatTemplateEngine.render( + templateSource: '{% for message in messages %}{{ message.content', + messages: twoUserTurns, + metadata: const {}, + ), + throwsRenderFailure( + startsWith('The chat template failed to render: ParserException'), + ), + ); + }); + + 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/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index d62514541..8647ec499 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -127,6 +127,12 @@ For canonical full release notes, use: `package:llamadart/backend.dart` now exports. A prompt written for `generate` keeps its placeholders, and `chatTemplate` output for messages without media is unchanged. +- On native llama.cpp, image or audio input that the loaded projector has no + encoder for throws `LlamaUnsupportedException` naming the encoder, where + `create` and `generate` threw `LlamaInferenceException`. A chat template + that raises or has invalid syntax throws `LlamaInferenceException` with the + template's message instead of a raw `Exception` + ([#963](https://github.com/leehack/llamadart/issues/963)). ## 0.11.1 diff --git a/website/docs/guides/multimodal.md b/website/docs/guides/multimodal.md index 25437c81b..a125b487c 100644 --- a/website/docs/guides/multimodal.md +++ b/website/docs/guides/multimodal.md @@ -119,7 +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. The current Gemma 4 E2B GGUF projector path in native `llama.cpp` +modalities, and on native `llama.cpp` input 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. diff --git a/website/docs/guides/template-engine-internals.md b/website/docs/guides/template-engine-internals.md index fd2729715..d300b1158 100644 --- a/website/docs/guides/template-engine-internals.md +++ b/website/docs/guides/template-engine-internals.md @@ -84,6 +84,8 @@ sequenceDiagram `generate`. They have `<__media__>` where each part was and the zero-width space in every other string `generate` reads as a part. Messages without media render as they are. +- 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 cfe26a0deca1a1307e779dca94e5f8fe307bb2e9 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 12:44:09 -0400 Subject: [PATCH 2/2] fix: name a missing encoder only for media whose kind is established A load failure of an audio part that mtmd does not read as audio (m4a, Ogg, short or arbitrary bytes) was reported as missing image support on a projector without a vision encoder, because every source without audio magic counted as an image. No image had been sent, and the original `Failed to load media part N` was lost. Content without audio magic is an image only when it has the magic of an image format or the caller typed the part as an image. An audio part of any other content and a source that cannot be read have no established kind and keep mtmd's error. --- .../backends/llama_cpp/llama_cpp_service.dart | 36 ++++-- .../llama_cpp_service_media_encoder_test.dart | 107 ++++++++++++++---- 2 files changed, 108 insertions(+), 35 deletions(-) diff --git a/lib/src/backends/llama_cpp/llama_cpp_service.dart b/lib/src/backends/llama_cpp/llama_cpp_service.dart index 4f5dfe13d..eae1a2741 100644 --- a/lib/src/backends/llama_cpp/llama_cpp_service.dart +++ b/lib/src/backends/llama_cpp/llama_cpp_service.dart @@ -8860,9 +8860,9 @@ class LlamaCppService { Pointer mmCtx, List parts, ) { - final readAsAudio = parts.map(_mtmdReadsAsAudio).toList(growable: false); + final kinds = parts.map(_isAudioRatherThanImage).toList(growable: false); for (final (kind, audio) in const [('Image', false), ('Audio', true)]) { - if (readAsAudio.contains(audio) && + if (kinds.contains(audio) && _mtmdHasEncoder(mmCtx, audio: audio) == false) { return LlamaUnsupportedException( '$kind input is not supported by the loaded multimodal projector: ' @@ -8874,12 +8874,17 @@ class LlamaCppService { return null; } - /// Whether mtmd reads [part] as audio rather than as an image, or null - /// when its source cannot be read. + /// Whether [part] is audio (true) or an image (false) to mtmd, or null + /// when neither is established. /// /// mtmd decides by content for a path or encoded bytes, whatever the type - /// of the part: this is `is_audio_file` of llama.cpp's `mtmd-helper.cpp`. - static bool? _mtmdReadsAsAudio(LlamaContentPart part) { + /// of the part: audio by the magic of `is_audio_file` in llama.cpp's + /// `mtmd-helper.cpp`, and anything else is tried as an image. Other content + /// is an image here when it has the magic of an image format, or when the + /// caller typed the part as an image too. An audio part that mtmd does not + /// read as audio, such as an m4a or Ogg file, and a source that cannot be + /// read are neither, so their mtmd error is kept. + static bool? _isAudioRatherThanImage(LlamaContentPart part) { final (path, bytes) = switch (part) { LlamaImageContent() => (part.path, part.bytes), LlamaAudioContent() => (part.path, part.bytes), @@ -8902,18 +8907,27 @@ class LlamaCppService { } else { return part is LlamaAudioContent ? true : null; } - if (head.length < 12) return false; bool has(String magic, [int offset = 0]) { + if (head.length < offset + magic.length) return false; for (var i = 0; i < magic.length; i++) { if (head[offset + i] != magic.codeUnitAt(i)) return false; } return true; } - return has('RIFF') && has('WAVE', 8) || - has('ID3') || - head[0] == 0xFF && head[1] & 0xE0 == 0xE0 || - has('fLaC'); + if (head.length >= 12 && + (has('RIFF') && has('WAVE', 8) || + has('ID3') || + head[0] == 0xFF && head[1] & 0xE0 == 0xE0 || + has('fLaC'))) { + return true; + } + final imageMagic = + has('\x89PNG\r\n\x1a\n') || + has('\xff\xd8\xff') || + has('GIF8') || + has('BM'); + return imageMagic || part is LlamaImageContent ? false : null; } /// Returns whether the active native mtmd build and projector report video. diff --git a/test/unit/backends/llama_cpp/llama_cpp_service_media_encoder_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_media_encoder_test.dart index 36219322a..e232110a7 100644 --- a/test/unit/backends/llama_cpp/llama_cpp_service_media_encoder_test.dart +++ b/test/unit/backends/llama_cpp/llama_cpp_service_media_encoder_test.dart @@ -21,18 +21,29 @@ import '../../../support/synthetic_embedding_gguf.dart'; const _params = ModelParams(gpuLayers: 0, contextSize: 64); const _greedy = GenerationParams(maxTokens: 1, temp: 0, topK: 1, seed: 1); -// The first bytes mtmd reads to tell audio from an image. -final Uint8List _png = Uint8List.fromList([ - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0x0d, // - 0x49, 0x48, 0x44, 0x52, -]); -final Uint8List _wav = Uint8List.fromList( - 'RIFF\x24\x00\x00\x00WAVEfmt '.codeUnits, -); -final Uint8List _mp3 = Uint8List.fromList([0xff, 0xfb, ...List.filled(12, 0)]); -final Uint8List _flac = Uint8List.fromList( - 'fLaC\x00\x00\x00\x22data'.codeUnits, -); +Uint8List _bytes(String head) => + Uint8List.fromList('$head${'\x00' * 16}'.codeUnits); + +// What mtmd reads as audio, by the first bytes. +final Uint8List _wav = _bytes('RIFF\x24\x00\x00\x00WAVEfmt '); +final Uint8List _mp3 = _bytes('\xff\xfb\x90\x00'); +final Uint8List _id3 = _bytes('ID3\x03\x00'); +final Uint8List _flac = _bytes('fLaC\x00\x00\x00\x22'); + +// Image formats by their magic. +final Uint8List _png = _bytes('\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR'); +final Uint8List _jpeg = _bytes('\xff\xd8\xff\xe0\x00\x10JFIF'); +final Uint8List _gif = _bytes('GIF89a'); +final Uint8List _bmp = _bytes('BM'); + +// Neither to mtmd, which tries them as images and fails. +final Uint8List _m4a = _bytes('\x00\x00\x00\x20ftypM4A '); +final Uint8List _ogg = _bytes('OggS'); +final Uint8List _webp = _bytes('RIFF\x24\x00\x00\x00WEBPVP8 '); +final Uint8List _tiff = _bytes('II*\x00'); +final Uint8List _random = _bytes('\x12\x34\x56\x78\x9a\xbc'); +// Audio magic in fewer than the 12 bytes mtmd asks for. +final Uint8List _shortFlac = Uint8List.fromList('fLaC'.codeUnits); Matcher _noEncoder(String kind) => throwsA( isA().having( @@ -107,7 +118,7 @@ void main() { 'whatever the type of the part', () async { fake.encodedBitmapLoads = false; - for (final audio in [_wav, _mp3, _flac]) { + for (final audio in [_wav, _mp3, _id3, _flac]) { await expectLater( send([LlamaAudioContent(bytes: audio)]), _noEncoder('Audio'), @@ -147,17 +158,26 @@ void main() { expect(fake.evaluations, 2); }); - test('keeps the load error of an image mtmd cannot decode', () async { + test('keeps the load error of a source mtmd does not read as ' + 'audio', () async { fake.encodedBitmapLoads = false; - await expectLater( - send([LlamaAudioContent(bytes: _png)]), - _untyped('Failed to load media part 0'), - ); - await expectLater( - send([LlamaImageContent(path: '${dir.path}/missing.png')]), - _untyped('Failed to load media part 0'), - ); + for (final part in [ + LlamaAudioContent(bytes: _png), + LlamaAudioContent(bytes: _m4a), + LlamaAudioContent(bytes: _ogg), + LlamaAudioContent(bytes: _webp), + LlamaAudioContent(bytes: _random), + LlamaAudioContent(bytes: _shortFlac), + LlamaAudioContent(path: file('note.m4a', _m4a)), + LlamaImageContent(bytes: _tiff), + LlamaImageContent(path: '${dir.path}/missing.png'), + ]) { + await expectLater( + send([part]), + _untyped('Failed to load media part 0'), + ); + } }); test('keeps the tokenize error of an image request', () async { @@ -185,16 +205,55 @@ void main() { send([LlamaImageContent(path: file('page.png', _png))]), _noEncoder('Image'), ); + for (final image in [_png, _jpeg, _gif, _bmp]) { + await expectLater( + send([LlamaAudioContent(bytes: image)]), + _noEncoder('Image'), + ); + } await expectLater( - send([LlamaAudioContent(bytes: _png)]), + send([LlamaAudioContent(bytes: _wav), LlamaImageContent(bytes: _png)]), _noEncoder('Image'), ); + }); + + test('names the image encoder for an image part mtmd cannot ' + 'decode', () async { + fake.encodedBitmapLoads = false; + await expectLater( - send([LlamaAudioContent(bytes: _wav), LlamaImageContent(bytes: _png)]), + send([LlamaImageContent(bytes: _tiff)]), + _noEncoder('Image'), + ); + await expectLater( + send([LlamaImageContent(path: file('page.tiff', _tiff))]), _noEncoder('Image'), ); }); + test('keeps the load error of an audio part mtmd does not read as audio ' + 'and of a source it cannot read', () async { + fake.encodedBitmapLoads = false; + + for (final part in [ + LlamaAudioContent(bytes: _m4a), + LlamaAudioContent(path: file('note.m4a', _m4a)), + LlamaAudioContent(path: file('note.wav', _m4a)), + LlamaAudioContent(bytes: _ogg), + LlamaAudioContent(bytes: _webp), + LlamaAudioContent(bytes: _random), + LlamaAudioContent(bytes: _shortFlac), + LlamaAudioContent(bytes: Uint8List(0)), + LlamaAudioContent(path: '${dir.path}/missing.wav'), + LlamaImageContent(path: '${dir.path}/missing.png'), + ]) { + await expectLater( + send([part]), + _untyped('Failed to load media part 0'), + ); + } + }); + test('hands mtmd audio sent as an image part, by bytes and by ' 'path', () async { await send([LlamaImageContent(bytes: _wav)]);