From efe4b97383246f7304ef1ca81071da92f8f832ff Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Mon, 9 Nov 2026 12:57:53 -0500 Subject: [PATCH] Adapt LiteRT-LM bundle templates the C API 1.0 runtime fails to render (#1867) The C API 1.0 client reports a failed render or a rejected conversation template as LlamaModelException, not StateError, so the bundle template probe let it escape and the first chat failed instead of adopting the content adapter. Treat it as a failed probe; other failures such as a disposed client still propagate. Unit fakes now throw what each client throws. The bundle template e2e suite catches the v1 failure, uses only message keys the v1 client accepts, skips adapter checks the service never applies (part-only and Qwen3 built-in templates), and makes cloned read-only bundles writable. Co-Authored-By: Claude --- CHANGELOG.md | 1 + .../backends/litert_lm/litert_lm_service.dart | 8 +- .../litert_lm_bundle_template_e2e_test.dart | 65 ++++++++---- test/support/litert_lm_content_templates.dart | 8 +- .../litert_lm_bundle_template_test.dart | 3 +- .../litert_lm/litert_lm_service_test.dart | 100 ++++++++++++++---- website/docs/changelog/recent-releases.md | 1 + 7 files changed, 140 insertions(+), 46 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ea6d0086..63f0fb5f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 ``, 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 diff --git a/lib/src/backends/litert_lm/litert_lm_service.dart b/lib/src/backends/litert_lm/litert_lm_service.dart index 3e7739710..a3d7d96b3 100644 --- a/lib/src/backends/litert_lm/litert_lm_service.dart +++ b/lib/src/backends/litert_lm/litert_lm_service.dart @@ -1010,6 +1010,8 @@ 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( @@ -1017,6 +1019,8 @@ class LiteRtLmService { ); } on StateError { return false; + } on LlamaModelException { + return false; } } @@ -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. } diff --git a/test/e2e/backends/litert_lm_bundle_template_e2e_test.dart b/test/e2e/backends/litert_lm_bundle_template_e2e_test.dart index b96850b04..95bce1911 100644 --- a/test/e2e/backends/litert_lm_bundle_template_e2e_test.dart +++ b/test/e2e/backends/litert_lm_bundle_template_e2e_test.dart @@ -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 -%}'; @@ -152,7 +153,7 @@ class _RecordingClient extends LiteRtLmRuntimeClient { sentPrompts.add( renderMessageToString(jsonDecode(messageJson) as Map), ); - } on StateError catch (error) { + } on LlamaModelException catch (error) { sentPrompts.add('render failed: ${error.message}'); } return super.generateMessageJson( @@ -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); @@ -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, @@ -300,7 +312,7 @@ void main() { bool rendersText() { try { return liteRtLmRendersProbeText(render(template)); - } on StateError { + } on LlamaModelException { return false; } } @@ -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.', @@ -366,16 +380,16 @@ 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, @@ -383,12 +397,10 @@ void main() { ); for (final value in [ - '', - '', - '|custom=kept|calls=|content=Thanks>', + '|content=get_weather=sunny>', + '|content=Thanks>', ]) { expect(rendered, contains(value)); } @@ -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 diff --git a/test/support/litert_lm_content_templates.dart b/test/support/litert_lm_content_templates.dart index 1e78e368d..f7893c125 100644 --- a/test/support/litert_lm_content_templates.dart +++ b/test/support/litert_lm_content_templates.dart @@ -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. @@ -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({ @@ -49,6 +51,6 @@ String renderLiteRtLmContent(String template, Object? content) { ], }); } on Exception catch (error) { - throw StateError('template failed: $error'); + throw LlamaModelException('template failed: $error'); } } diff --git a/test/unit/backends/litert_lm/litert_lm_bundle_template_test.dart b/test/unit/backends/litert_lm/litert_lm_bundle_template_test.dart index b17982642..a766c06b5 100644 --- a/test/unit/backends/litert_lm/litert_lm_bundle_template_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_bundle_template_test.dart @@ -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'; @@ -456,7 +457,7 @@ void main() { return liteRtLmRendersProbeText( renderLiteRtLmContent(template, probeParts), ); - } on StateError { + } on LlamaModelException { return false; } } diff --git a/test/unit/backends/litert_lm/litert_lm_service_test.dart b/test/unit/backends/litert_lm/litert_lm_service_test.dart index 0ead40094..9474b48ed 100644 --- a/test/unit/backends/litert_lm/litert_lm_service_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_service_test.dart @@ -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); @@ -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', @@ -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, @@ -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); diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 0a9353bbe..3a513658e 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -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 ``, 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