Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
116 changes: 97 additions & 19 deletions lib/src/backends/llama_cpp/llama_cpp_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -8834,22 +8826,108 @@ 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<mtmd_context> 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<mtmd_context> mmCtx,
List<LlamaContentPart> parts,
) {
final kinds = parts.map(_isAudioRatherThanImage).toList(growable: false);
for (final (kind, audio) in const [('Image', false), ('Audio', true)]) {
if (kinds.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 [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: 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),
_ => (null, null),
};
final List<int> 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;
}
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;
}

if (head.length >= 12 &&
(has('RIFF') && has('WAVE', 8) ||
has('ID3') ||
head[0] == 0xFF && head[1] & 0xE0 == 0xE0 ||
has('fLaC'))) {
return true;
}
return fallback.supportsAudio(mmCtx);
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.
Expand Down
8 changes: 8 additions & 0 deletions lib/src/core/engine/engine.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down Expand Up @@ -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
Expand Down
63 changes: 48 additions & 15 deletions lib/src/core/template/chat_template_engine.dart
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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) {
Expand All @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion skills/llamadart-multimodal/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading
Loading