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

- Native LiteRT-LM `generate()` now sends the prompt unchanged, like other backends, instead of wrapping it in the bundle's chat turn, so `create()` requests that fall back to a rendered prompt (a trailing system message, `parallelToolCalls: true`) are no longer templated twice. A prompt that starts with the model's start token, such as Gemma's `<bos>`, no longer gets a second one; an empty prompt throws `LlamaArgumentException`; and pre-1.0 LiteRT-LM runtime overrides without the conversation template setter refuse raw `generate()` with `LlamaUnsupportedException` ([#1853](https://github.com/leehack/llamadart/issues/1853)).
- Native `.litertlm` `getMetadata()['tokenizer.chat_template']` and `engine.chatTemplate(...)` now show the template the LiteRT-LM runtime renders, such as the embedded Qwen3.5 or Gemma bundle template; format detection and parsing keep the file-name template, now reported as `llamadart.chat_template.parsing`, so code that detects the format from `tokenizer.chat_template` should read that key first. Native JSON Schema chat now refuses bundles whose text chats the runtime renders with their own template, matching generation ([#1836](https://github.com/leehack/llamadart/issues/1836)).
- Fix native LiteRT-LM chat failing with "Failed to apply template" on a bundle whose chat template concatenates message content as a string: llamadart now adapts such a template on the bundled C API 1.0 runtime too, as documented ([#1867](https://github.com/leehack/llamadart/issues/1867)).

## 0.19.1

Expand Down
8 changes: 7 additions & 1 deletion lib/src/backends/litert_lm/litert_lm_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1010,13 +1010,17 @@ class LiteRtLmService {
if (!client.supportsMessageRendering) {
return;
}
// A failed native render is a StateError from the legacy client and a
// LlamaModelException from the C API 1.0 client.
bool rendersProbeText() {
try {
return liteRtLmRendersProbeText(
client.renderMessageToString(liteRtLmContentShapeProbeMessage),
);
} on StateError {
return false;
} on LlamaModelException {
return false;
}
}

Expand All @@ -1034,7 +1038,9 @@ class LiteRtLmService {
return;
}
} on StateError {
// The runtime rejected the adapted template.
// The legacy runtime rejected the adapted template.
} on LlamaModelException {
// The C API 1.0 runtime rejected the adapted template.
} on LlamaUnsupportedException {
// The runtime takes no conversation template.
}
Expand Down
65 changes: 43 additions & 22 deletions test/e2e/backends/litert_lm_bundle_template_e2e_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -54,17 +54,18 @@ const _partsContentTemplate =
"{{ '<|im_end|>\\n' }}{%- endfor -%}"
'$_generationPrompt';

/// Writes every key the service or a caller can put on a message.
/// Writes every key the service can put on a message.
const _messageKeysTemplate =
'{%- for message in messages -%}<{{ message.role }}'
'|name={{ message.name }}|id={{ message.tool_call_id }}'
'|reasoning={{ message.reasoning_content }}'
'|custom={%- if message.custom -%}{{ message.custom.a }}{%- endif -%}'
'|calls={%- for call in message.tool_calls or [] -%}'
'{{ call.function.name }}({{ call.function.arguments.city }})'
'{%- endfor -%}'
'|content={%- if message.content is string -%}{{ message.content }}'
'{%- else -%}{%- for part in message.content -%}{{ part.text }}'
'{%- else -%}{%- for part in message.content -%}'
"{%- if part.type == 'tool_response' -%}"
'{{ part.name }}={{ part.response }}'
'{%- else -%}{{ part.text }}{%- endif -%}'
'{%- endfor -%}{%- endif -%}>\n'
'{% endfor -%}';

Expand Down Expand Up @@ -152,7 +153,7 @@ class _RecordingClient extends LiteRtLmRuntimeClient {
sentPrompts.add(
renderMessageToString(jsonDecode(messageJson) as Map<String, dynamic>),
);
} on StateError catch (error) {
} on LlamaModelException catch (error) {
sentPrompts.add('render failed: ${error.message}');
}
return super.generateMessageJson(
Expand Down Expand Up @@ -206,6 +207,10 @@ String _bundleWithTemplate(
Process.runSync('cp', ['-c', model, path]).exitCode != 0) {
File(model).copySync(path);
}
// Both copies keep the mode of a read-only cached model.
if (!Platform.isWindows) {
expect(Process.runSync('chmod', ['u+w', path]).exitCode, 0);
}
final copy = File(path).openSync(mode: FileMode.append);
try {
copy.setPositionSync(offset);
Expand Down Expand Up @@ -280,9 +285,16 @@ void main() {
messages: history,
);

// A template that reads content parts renders the same prompt either
// way; one that interpolates a string differs only in each serialized
// part list.
if (liteRtLmRendersProbeText(rendered) &&
!liteRtLmRendersProbeText(adapted)) {
// A template that reads content only as parts, such as Qwen3's, loses
// the text the adapter gives it as a string. The service adapts only a
// template that does not render the text, so it keeps this one.
return;
}
// A template that reads content parts and strings renders the same
// prompt either way; one that interpolates a string differs only in
// each serialized part list.
expect(liteRtLmRendersProbeText(adapted), isTrue);
expect(
adapted,
Expand All @@ -300,7 +312,7 @@ void main() {
bool rendersText() {
try {
return liteRtLmRendersProbeText(render(template));
} on StateError {
} on LlamaModelException {
return false;
}
}
Expand Down Expand Up @@ -348,8 +360,10 @@ void main() {
});

test('keeps every other message key through the adapter', () {
// The message keys and tool result parts the service sends, the only
// ones the C API 1.0 client accepts.
const messages = [
{'role': 'user', 'content': 'Weather?', 'name': 'bob'},
{'role': 'user', 'content': 'Weather?'},
{
'role': 'assistant',
'content': 'Checking.',
Expand All @@ -366,29 +380,27 @@ void main() {
},
{
'role': 'tool',
'content': 'sunny',
'name': 'get_weather',
'tool_call_id': 'call_1',
'content': [
{
'type': 'tool_response',
'name': 'get_weather',
'response': 'sunny',
},
],
},
];
const message = {
'role': 'user',
'content': 'Thanks',
'custom': {'a': 'kept'},
};
const message = {'role': 'user', 'content': 'Thanks'};
final rendered = render(
_messageKeysTemplate,
messages: messages,
message: message,
);

for (final value in [
'<user|name=bob|',
'|reasoning=needs a tool|',
'|calls=get_weather(Paris)|content=Checking.>',
'<tool|name=get_weather|id=call_1|',
'|content=sunny>',
'|custom=kept|calls=|content=Thanks>',
'|content=get_weather=sunny>',
'|content=Thanks>',
]) {
expect(rendered, contains(value));
}
Expand Down Expand Up @@ -559,11 +571,20 @@ void main() {
final service = LiteRtLmService(clientFactory: () => client);
final params = ModelParams(
contextSize: 1024,
numberOfThreads: 2,
liteRtLmBackend: LiteRtLmBackendPreference.cpu,
liteRtLmCacheDir: cache.path,
);
try {
final handle = await service.loadModel(path, params);
if (service.getMetadata(handle)['tokenizer.chat_template'] !=
embedded) {
// Such as Qwen3, whose text chats render a built-in template.
markTestSkipped(
'Text chats on this bundle use a built-in template.',
);
return;
}
final context = service.createContext(handle, params);
for (var request = 0; request < 2; request++) {
await service
Expand Down
8 changes: 5 additions & 3 deletions test/support/litert_lm_content_templates.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'package:dinja/dinja.dart';
import 'package:llamadart/src/core/exceptions.dart';

/// Bundle templates that read message content as a string, as bundles built
/// for LiteRT-LM runtimes before v0.18 do, keyed by how they read it.
Expand Down Expand Up @@ -39,8 +40,9 @@ const String liteRtLmPartsContentTemplate =
'{% endfor -%}';

/// Renders [template] for one message with [content], as a LiteRT-LM runtime
/// renders the single message of a conversation. Throws a [StateError] when
/// the template fails, as the runtime client does.
/// renders the single message of a conversation. Throws a
/// [LlamaModelException] when the template fails, as the C API 1.0 runtime
/// client does.
String renderLiteRtLmContent(String template, Object? content) {
try {
return Template(template).render({
Expand All @@ -49,6 +51,6 @@ String renderLiteRtLmContent(String template, Object? content) {
],
});
} on Exception catch (error) {
throw StateError('template failed: $error');
throw LlamaModelException('template failed: $error');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import 'dart:typed_data';

import 'package:dinja/dinja.dart';
import 'package:llamadart/src/backends/litert_lm/litert_lm_bundle_template.dart';
import 'package:llamadart/src/core/exceptions.dart';
import 'package:test/test.dart';

import '../../../support/litert_lm_content_templates.dart';
Expand Down Expand Up @@ -456,7 +457,7 @@ void main() {
return liteRtLmRendersProbeText(
renderLiteRtLmContent(template, probeParts),
);
} on StateError {
} on LlamaModelException {
return false;
}
}
Expand Down
100 changes: 81 additions & 19 deletions test/unit/backends/litert_lm/litert_lm_service_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,37 @@ void main() {
});
}

for (final (name, nativeError) in [
('legacy', StateError.new),
('C API 1.0', LlamaModelException.new),
]) {
test('adapts a template the $name runtime fails to render', () async {
final concatenating = liteRtLmStringContentTemplates['concatenating']!;
client.onRenderMessage = (template) => template == null
? throw nativeError(
'render_message_to_string failed: tried to use + operator '
'on unsupported types string and sequence',
)
: renderLiteRtLmContent(template, probeParts);
final adapter = liteRtLmTextContentAdapter(concatenating);
final service = serviceReading(concatenating);
try {
final model = await service.loadModel(modelFile.path, params);
final context = service.createContext(model, params);

await chat(service, context);
expect(client.conversations, [
(template: null, seeded: false),
(template: adapter, seeded: false),
(template: adapter, seeded: true),
]);
expect(records, isEmpty);
} finally {
service.dispose();
}
});
}

test('keeps a template that reads content parts', () async {
renderLikeTheRuntime(liteRtLmPartsContentTemplate);
final service = serviceReading(liteRtLmPartsContentTemplate);
Expand Down Expand Up @@ -790,6 +821,11 @@ void main() {

final interpolating = liteRtLmStringContentTemplates['interpolating']!;
final concatenating = liteRtLmStringContentTemplates['concatenating']!;
// How each runtime client reports a failed native call.
final nativeErrors = <(String, Object Function(String))>[
('legacy', StateError.new),
('C API 1.0', LlamaModelException.new),
];
for (final (name, template, configure) in [
(
'a bundle whose template it cannot read',
Expand All @@ -811,25 +847,27 @@ void main() {
(_FakeLiteRtLmRuntimeClient client) =>
client.onRenderMessage = (_) => '<|im_start|>\n<|im_end|>\n',
),
(
'a template that fails to render with the adapter too',
concatenating,
(_FakeLiteRtLmRuntimeClient client) =>
client.onRenderMessage = (_) =>
renderLiteRtLmContent(concatenating, probeParts),
),
(
'an adapted template the runtime rejects',
interpolating,
(_FakeLiteRtLmRuntimeClient client) {
client.onRenderMessage = (_) => '';
client.onCreateConversation = () {
if (client.lastPromptTemplate != null) {
throw StateError('litert_lm_conversation_create returned null');
}
};
},
),
for (final (client, nativeError) in nativeErrors) ...[
(
'a template that fails to render with the adapter too ($client)',
concatenating,
(_FakeLiteRtLmRuntimeClient client) =>
client.onRenderMessage = (_) =>
throw nativeError('render_message_to_string failed'),
),
(
'an adapted template the $client runtime rejects',
interpolating,
(_FakeLiteRtLmRuntimeClient client) {
client.onRenderMessage = (_) => '';
client.onCreateConversation = () {
if (client.lastPromptTemplate != null) {
throw nativeError('litert_lm_conversation_create failed');
}
};
},
),
],
(
'a runtime that takes no conversation template',
interpolating,
Expand Down Expand Up @@ -1041,6 +1079,30 @@ void main() {
}
});

test('does not decide when the probe render fails for another '
'reason', () async {
final disposed = LlamaStateException('C API 1.0 adapter is disposed.');
final adapter = liteRtLmTextContentAdapter(interpolating);
client.onRenderMessage = (_) => throw disposed;
final service = serviceReading(interpolating);
try {
final model = await service.loadModel(modelFile.path, params);
final context = service.createContext(model, params);

await expectLater(chat(service, context), throwsA(same(disposed)));
expect(
records.where((record) => record.message.contains('adapt')),
isEmpty,
);

renderLikeTheRuntime(interpolating);
await chat(service, context);
expect(client.conversations.last, (template: adapter, seeded: true));
} finally {
service.dispose();
}
});

test('probes each loaded model', () async {
renderLikeTheRuntime(interpolating);
final service = serviceReading(interpolating);
Expand Down
1 change: 1 addition & 0 deletions website/docs/changelog/recent-releases.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ validate against the exact release tag notes.

- Native LiteRT-LM `generate()` now sends the prompt unchanged, like other backends, instead of wrapping it in the bundle's chat turn, so `create()` requests that fall back to a rendered prompt (a trailing system message, `parallelToolCalls: true`) are no longer templated twice. A prompt that starts with the model's start token, such as Gemma's `<bos>`, no longer gets a second one; an empty prompt throws `LlamaArgumentException`; and pre-1.0 LiteRT-LM runtime overrides without the conversation template setter refuse raw `generate()` with `LlamaUnsupportedException` ([#1853](https://github.com/leehack/llamadart/issues/1853)).
- Native `.litertlm` `getMetadata()['tokenizer.chat_template']` and `engine.chatTemplate(...)` now show the template the LiteRT-LM runtime renders, such as the embedded Qwen3.5 or Gemma bundle template; format detection and parsing keep the file-name template, now reported as `llamadart.chat_template.parsing`, so code that detects the format from `tokenizer.chat_template` should read that key first. Native JSON Schema chat now refuses bundles whose text chats the runtime renders with their own template, matching generation ([#1836](https://github.com/leehack/llamadart/issues/1836)).
- Fix native LiteRT-LM chat failing with "Failed to apply template" on a bundle whose chat template concatenates message content as a string: llamadart now adapts such a template on the bundled C API 1.0 runtime too, as documented ([#1867](https://github.com/leehack/llamadart/issues/1867)).

## 0.19.1

Expand Down
Loading