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
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,17 @@
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)). 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

Expand Down
7 changes: 4 additions & 3 deletions doc/litert_lm_templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<id>.jinja`
Expand Down
66 changes: 39 additions & 27 deletions lib/src/backends/llama_cpp/llama_cpp_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<LlamaContentPart> 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
Expand All @@ -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(
Expand Down Expand Up @@ -4776,10 +4792,7 @@ class LlamaCppService {
);
}
if (hasMediaParts) {
_checkLlamaCppMediaParts(
parts!,
projectorLoaded: _modelToMtmd[modelHandle] != null,
);
_checkLlamaCppMediaParts(parts!, mmHandle: _modelToMtmd[modelHandle]);
}
final thinkingBudgetConfig = _resolveLlamaCppThinkingBudgetConfig(
params,
Expand Down Expand Up @@ -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.
Expand All @@ -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<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'),
);
}
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.
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 @@ -1543,6 +1543,11 @@ class LlamaEngine {
/// parse compatible best-effort tool-call text, but it does not currently
/// enforce arbitrary JSON-schema constraints.
///
/// 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
/// final messages = [
Expand Down Expand Up @@ -1783,6 +1788,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]
Expand Down
97 changes: 67 additions & 30 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 @@ -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<LlamaChatMessage> messages,
Expand Down Expand Up @@ -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);
Expand All @@ -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(
Expand All @@ -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) {
Expand All @@ -335,6 +347,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
15 changes: 12 additions & 3 deletions lib/src/core/template/jinja/jinja_analyzer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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([
Expand All @@ -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([
Expand Down Expand Up @@ -181,6 +188,8 @@ class JinjaAnalyzer {
supportsTypedContent: supportsTypedContent,
supportsThinking: supportsThinking,
supportsObjectArguments: supportsObjectArguments,
supportsImageParts: supportsImageParts,
supportsAudioParts: supportsAudioParts,
);
}

Expand Down
11 changes: 11 additions & 0 deletions lib/src/core/template/template_caps.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
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 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.
Expand Down
Loading
Loading