Skip to content
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

- Load the best Linux arm64 CPU variant module a native bundle ships in every backend mode, falling back to the baseline, so mixed `auto` and explicit loads share one CPU backend.
- Native LiteRT-LM under `ComputeDevice.auto` retries a GPU engine that fails to start on the CPU with a warning, and reports `LiteRT-LM cpu`; explicit `gpu` and `npu` still fail ([#1034](https://github.com/leehack/llamadart/issues/1034)).
- Requests with an image or audio part and tools honor `ToolChoice.auto` instead of forcing a tool call on templates such as Qwen3-VL and Qwen3.5, and use the same tool-call grammar, triggers, parser and stops as text requests ([#1463](https://github.com/leehack/llamadart/issues/1463)).
- A boolean `enable_thinking` or `thinking` chat template kwarg now overrides `enableThinking`, as in llama-server, and DeepSeek V3.1 forces its thought open from `enableThinking` alone ([#750](https://github.com/leehack/llamadart/issues/750)).

## 0.16.5
Expand Down
91 changes: 54 additions & 37 deletions lib/src/core/template/chat_template_handler.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import 'dart:async';
import 'dart:convert';

import 'package:dinja/dinja.dart';

import '../exceptions.dart';
import '../models/chat/chat_message.dart';
import '../models/chat/chat_template_result.dart';
import '../models/chat/content_part.dart';
import '../models/inference/tool_choice.dart';
import '../models/tools/tool_definition.dart';
import 'chat_format.dart';
Expand Down Expand Up @@ -198,7 +200,10 @@ abstract class ChatTemplateHandler {
/// Each image, audio or video part becomes [mediaMarker] in the message
/// text, where the part was, as llama.cpp renders it. The template's own
/// placeholder for a typed media part is not written, and a placeholder
/// string in message text stays text.
/// string in message text stays text. The request then goes through
/// [render], so it gets the grammar, triggers, preserved tokens, parser and
/// stops of the same text request: llama-server applies one chat format to
/// both.
LlamaChatTemplateResult renderWithMultimodalContent({
required String templateSource,
required List<LlamaChatMessage> messages,
Expand All @@ -208,46 +213,58 @@ abstract class ChatTemplateHandler {
bool enableThinking = true,
String mediaMarker = mtmdMediaMarker,
}) {
final template = Template(templateSource);
var prompt = renderTemplate(
template,
metadata: metadata,
context: {
'messages': templateMessages(
messages,
multimodal: true,
mediaMarker: mediaMarker,
templateSource: templateSource,
),
'add_generation_prompt': addAssistant,
'tools': tools?.map((t) => t.toJson()).toList(),
'enable_thinking': enableThinking,
'bos_token': metadata['tokenizer.ggml.bos_token'] ?? '',
'eos_token': metadata['tokenizer.ggml.eos_token'] ?? '',
bool isMedia(LlamaContentPart part) =>
part is LlamaImageContent ||
part is LlamaAudioContent ||
part is LlamaVideoContent;
final result = render(
templateSource: templateSource,
messages: [
for (final message in messages)
message.parts.any(isMedia)
? message.copyWith(
parts: [
for (final part in message.parts)
isMedia(part) ? LlamaTextContent(mediaMarker) : part,
],
)
: message,
],
// llama.cpp gives every template `enable_thinking`; most handlers' own
// contexts leave it out.
metadata: {
...metadata,
internalChatTemplateKwargsMetadataKey: jsonEncode({
...chatTemplateKwargsFromMetadata(metadata),
'enable_thinking': enableThinking,
}),
},
addAssistant: addAssistant,
tools: tools,
enableThinking: enableThinking,
);

var thinkingForcedOpen = false;
if (isThinkingForcedOpen(prompt, startTag: thinkingStartTag.trimRight())) {
if (!enableThinking) {
prompt = '${prompt.trimRight()}$thinkingEndTag\n';
} else {
thinkingForcedOpen = true;
}
// Handlers that do not track a thought the template opened, such as the
// generic one, still get it handled for media requests.
if (result.thinkingForcedOpen ||
!isThinkingForcedOpen(
result.prompt,
startTag: thinkingStartTag.trimRight(),
)) {
return result;
}

final hasTools = tools != null && tools.isNotEmpty;

return LlamaChatTemplateResult(
prompt: prompt,
format: format.index,
grammar: buildGrammar(tools),
grammarLazy: hasTools,
additionalStops: getStops(
hasTools: hasTools,
enableThinking: enableThinking,
),
thinkingForcedOpen: thinkingForcedOpen,
prompt: enableThinking
? result.prompt
: '${result.prompt.trimRight()}$thinkingEndTag\n',
format: result.format,
grammar: result.grammar,
grammarLazy: result.grammarLazy,
additionalStops: result.additionalStops,
preservedTokens: result.preservedTokens,
grammarTriggers: result.grammarTriggers,
thinkingForcedOpen: enableThinking,
parser: result.parser,
tokenCount: result.tokenCount,
);
}

Expand Down
135 changes: 135 additions & 0 deletions test/e2e/backends/multimodal_tool_choice_e2e_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
@TestOn('vm')
@Tags(['local-only', 'e2e'])
@Timeout(Duration(minutes: 10))
library;

import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:llamadart/llamadart.dart';
import 'package:test/test.dart';

/// Qualifies `tool_choice: auto` for a request with a user image and tools
/// on a real vision model through native llama.cpp: the tool grammar stays
/// lazy, so the model can answer in text.
///
/// Set LLAMADART_MM_TOOLS_MODEL and LLAMADART_MM_TOOLS_MMPROJ to a GGUF
/// vision model and its projector, such as Qwen3.5-0.8B.
/// LLAMADART_MM_TOOLS_CHAT_TEMPLATE optionally names a template file used as
/// `ModelParams.chatTemplate`. LLAMADART_MM_TOOLS_BACKEND picks a
/// `GpuBackend` (default `cpu`).
void main() {
final env = Platform.environment;
final model = env['LLAMADART_MM_TOOLS_MODEL'];
final mmproj = env['LLAMADART_MM_TOOLS_MMPROJ'];
final templatePath = env['LLAMADART_MM_TOOLS_CHAT_TEMPLATE'];
final backend = GpuBackend.values.byName(
env['LLAMADART_MM_TOOLS_BACKEND'] ?? 'cpu',
);
late LlamaEngine engine;

setUpAll(() async {
expect(model, isNotNull, reason: 'Set LLAMADART_MM_TOOLS_MODEL');
expect(mmproj, isNotNull, reason: 'Set LLAMADART_MM_TOOLS_MMPROJ');
engine = LlamaEngine(LlamaBackend());
await engine.loadModel(
model!,
modelParams: ModelParams(
contextSize: 4096,
gpuLayers: backend == GpuBackend.cpu ? 0 : 99,
preferredBackend: backend,
chatTemplate: templatePath == null
? null
: File(templatePath).readAsStringSync(),
),
);
await engine.loadMultimodalProjector(mmproj!);
});

tearDownAll(() => engine.dispose());

test('a user image with tools is answered in text', () async {
final reply = await engine.complete(
[
LlamaChatMessage.withContent(
role: LlamaChatRole.user,
content: [
LlamaImageContent(bytes: _solidPng(20, 40, 220)),
const LlamaTextContent(
'What is the main color of this image? Answer in one word.',
),
],
),
],
tools: [
ToolDefinition(
name: 'take_photo',
description: 'Take a new photo with the camera.',
parameters: [],
),
],
enableThinking: false,
params: const GenerationParams(
temp: 0,
penalty: 1,
seed: 1,
maxTokens: 48,
),
);
stdout.writeln(
jsonEncode({
'text': reply.text,
'tool_calls': [for (final call in reply.toolCalls) call.name],
'finish': reply.finishReason?.name,
'prompt_tokens': reply.usage?.promptTokens,
'backend': backend.name,
}),
);

expect(reply.toolCalls, isEmpty);
expect(reply.text.toLowerCase(), contains('blue'));
});
}

Uint8List _solidPng(int r, int g, int b) {
const size = 128;
final raw = BytesBuilder();
for (var y = 0; y < size; y++) {
raw.addByte(0);
for (var x = 0; x < size; x++) {
raw.add([r, g, b]);
}
}
Uint8List chunk(String type, List<int> data) {
final body = [...ascii.encode(type), ...data];
return (BytesBuilder()
..add(_uint32(data.length))
..add(body)
..add(_uint32(_crc32(body))))
.toBytes();
}

return (BytesBuilder()
..add(const [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])
..add(
chunk('IHDR', [..._uint32(size), ..._uint32(size), 8, 2, 0, 0, 0]),
)
..add(chunk('IDAT', ZLibEncoder().convert(raw.toBytes())))
..add(chunk('IEND', const [])))
.toBytes();
}

List<int> _uint32(int value) =>
(ByteData(4)..setUint32(0, value)).buffer.asUint8List();

int _crc32(List<int> bytes) {
var crc = 0xFFFFFFFF;
for (final byte in bytes) {
crc ^= byte;
for (var bit = 0; bit < 8; bit++) {
crc = crc & 1 == 1 ? (crc >> 1) ^ 0xEDB88320 : crc >> 1;
}
}
return crc ^ 0xFFFFFFFF;
}
36 changes: 36 additions & 0 deletions test/unit/core/engine/chat_session_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -919,6 +919,42 @@ void main() {
expect(backend.lastParams?.grammar, contains('test_tool'));
});

test('an image with tools keeps the tool grammar lazy', () async {
backend.chatTemplate = '''
{%- if tools %}<|im_start|>system
<tools>{% for tool in tools %}{{ tool | tojson }}{% endfor %}</tools>
Return each call in <tool_call></tool_call> tags.<|im_end|>
{% endif %}
{%- for message in messages %}<|im_start|>{{ message.role }}
{% if message.content is string %}{{ message.content }}{% else %}{% for part in message.content %}{% if part.type == 'text' %}{{ part.text }}{% endif %}{% endfor %}{% endif %}<|im_end|>
{% endfor %}
{%- if add_generation_prompt %}<|im_start|>assistant
{% endif %}''';
final tools = [
ToolDefinition(
name: 'take_photo',
description: 'Take a photo',
handler: (p) async => 'result',
parameters: [],
),
];
backend.queueResponse('Blue.');

await session.create([
LlamaImageContent(bytes: Uint8List.fromList([1, 2, 3])),
const LlamaTextContent('What color is it?'),
], tools: tools).drain();

expect(backend.lastPrompt, contains('<__media__>What color is it?'));
expect(backend.lastParams?.grammar, contains('take_photo'));
expect(backend.lastParams?.grammarLazy, isTrue);
expect(
backend.lastParams?.grammarTriggers.map((trigger) => trigger.value),
contains(contains('<tool_call>')),
);
expect(backend.lastParams?.preservedTokens, contains('<tool_call>'));
});

test('send returns the reply and records both turns', () async {
backend.queueResponse('<think>\nPlan.\n</think>\n\nSure.');

Expand Down
35 changes: 35 additions & 0 deletions test/unit/core/template/chat_template_handler_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,41 @@ void main() {
expect(result.prompt, 'user:[Weather?];assistant:[];');
});

test('a media request closes a thought the template opens only when '
'thinking is off', () {
const template =
'{%- for message in messages -%}'
'{%- for part in message.content -%}{{ part.text }}{%- endfor -%}'
'{%- endfor -%}'
'<think>';
const messages = <LlamaChatMessage>[
LlamaChatMessage.withContent(
role: LlamaChatRole.user,
content: <LlamaContentPart>[
LlamaImageContent(path: '/tmp/photo.png'),
LlamaTextContent('look'),
],
),
];
LlamaChatTemplateResult render({required bool enableThinking}) =>
ChatTemplateEngine.handlerFor(
ChatFormat.contentOnly,
).renderWithMultimodalContent(
templateSource: template,
messages: messages,
metadata: const <String, String>{},
enableThinking: enableThinking,
);

final on = render(enableThinking: true);
expect(on.prompt, '<__media__>look<think>');
expect(on.thinkingForcedOpen, isTrue);

final off = render(enableThinking: false);
expect(off.prompt, '<__media__>look<think></think>\n');
expect(off.thinkingForcedOpen, isFalse);
});

group('required calls after a forced-open thought', () {
final tools = [
ToolDefinition(
Expand Down
Loading
Loading