diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a12e6bc6..1ea6d0086 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ ## Unreleased +- 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)). ## 0.19.1 diff --git a/example/chat_app/lib/litert_lm_benchmark_app.dart b/example/chat_app/lib/litert_lm_benchmark_app.dart index 3fca9c2eb..028d89d5e 100644 --- a/example/chat_app/lib/litert_lm_benchmark_app.dart +++ b/example/chat_app/lib/litert_lm_benchmark_app.dart @@ -384,16 +384,7 @@ class _LiteRtLmBenchmarkAppState extends State { ); for (var i = 0; i < _warmups; i++) { - await engine - .generate( - _promptController.text, - params: GenerationParams( - maxTokens: _outputTokens, - seed: 1, - speculativeDecoding: _speculative, - ), - ) - .drain(); + await _liteRtChat(engine).drain(); } var lastText = ''; @@ -403,14 +394,7 @@ class _LiteRtLmBenchmarkAppState extends State { for (var i = 0; i < _runs; i++) { final buffer = StringBuffer(); final sw = Stopwatch()..start(); - await for (final chunk in engine.generate( - _promptController.text, - params: GenerationParams( - maxTokens: _outputTokens, - seed: 1, - speculativeDecoding: _speculative, - ), - )) { + await for (final chunk in _liteRtChat(engine)) { buffer.write(chunk); } sw.stop(); @@ -501,6 +485,27 @@ class _LiteRtLmBenchmarkAppState extends State { }; } + // LiteRT-LM generate() sends the prompt raw, so the benchmark sends it as a + // user turn, which the bundle template renders as in a chat app. + Stream _liteRtChat(LlamaEngine engine) => engine + .create( + [ + LlamaChatMessage.fromText( + role: LlamaChatRole.user, + text: _promptController.text, + ), + ], + params: GenerationParams( + maxTokens: _outputTokens, + seed: 1, + speculativeDecoding: _speculative, + ), + ) + .map((chunk) { + final delta = chunk.choices.first.delta; + return '${delta.thinking ?? ''}${delta.content ?? ''}'; + }); + Future _runLlamaDartBenchmark( String modelPath, { String? draftModelPath, diff --git a/lib/src/backends/litert_lm/litert_lm_bundle_template.dart b/lib/src/backends/litert_lm/litert_lm_bundle_template.dart index 39efb55ba..63c450465 100644 --- a/lib/src/backends/litert_lm/litert_lm_bundle_template.dart +++ b/lib/src/backends/litert_lm/litert_lm_bundle_template.dart @@ -15,6 +15,24 @@ const int _jinjaPromptTemplateField = 7; // `LlmMetadata.channels` in `runtime/proto/llm_metadata.proto`. const int _channelsField = 8; +/// A conversation template that renders the text of each message unchanged, +/// so a raw prompt sent as one user message reaches the model as it is, +/// instead of inside the bundle's chat turn. +/// +/// It reads content both as a string and as a list of parts, the form +/// LiteRT-LM v0.18 and later pass. All of its literal whitespace sits inside +/// tags, so the runtime's block trimming cannot change the prompt. +const String liteRtLmRawPromptTemplate = + '{%- for message in messages -%}' + '{%- if message.content is string -%}' + '{{ message.content }}' + '{%- else -%}' + '{%- for part in message.content -%}' + "{%- if part.type == 'text' -%}{{ part.text }}{%- endif -%}" + '{%- endfor -%}' + '{%- endif -%}' + '{%- endfor -%}'; + /// The text of [liteRtLmContentShapeProbeMessage]. const String liteRtLmContentShapeProbeText = 'llamadart-content-shape-probe'; diff --git a/lib/src/backends/litert_lm/litert_lm_runtime.dart b/lib/src/backends/litert_lm/litert_lm_runtime.dart index b0dd13a83..becc420cb 100644 --- a/lib/src/backends/litert_lm/litert_lm_runtime.dart +++ b/lib/src/backends/litert_lm/litert_lm_runtime.dart @@ -1388,8 +1388,12 @@ class _LegacyLiteRtLmRuntimeClient extends LiteRtLmRuntimeClient { 'litert_lm_conversation_config_set_prompt_template', )) { throw LlamaUnsupportedException( - 'The LiteRT-LM runtime does not support conversation prompt templates. ' - 'Use the packaged runtime or a compatible newer runtime.', + 'This LiteRT-LM runtime lacks ' + 'litert_lm_conversation_config_set_prompt_template, so llamadart ' + 'cannot set a conversation template: raw prompt generation, ' + 'ModelParams.chatTemplate and the built-in family templates, such as ' + 'Qwen3 text chat, need one. Use the packaged litert-lm-native ' + '$_litertLmReleaseTag runtime or a newer one.', ); } final sessionConfig = bindings.sessionConfigCreate(); diff --git a/lib/src/backends/litert_lm/litert_lm_service.dart b/lib/src/backends/litert_lm/litert_lm_service.dart index 4592f3c60..3e7739710 100644 --- a/lib/src/backends/litert_lm/litert_lm_service.dart +++ b/lib/src/backends/litert_lm/litert_lm_service.dart @@ -243,6 +243,7 @@ class LiteRtLmService { bool _bundleTemplateProbed = false; String? _bundleTemplateAdapter; bool _bundleTemplateMisreadsContent = false; + ({List tokens, String text, bool plainText})? _startToken; ({bool penalties, bool thinkingBudget})? _runtimeGenerationControls; bool? _runtimeFinishReasons; BackendGenerationLimit? _lastGenerationLimit; @@ -319,6 +320,7 @@ class LiteRtLmService { _bundleTemplateProbed = false; _bundleTemplateAdapter = null; _bundleTemplateMisreadsContent = false; + _startToken = null; _bundleDeclaresThinkingChannel = null; _modelHandle = _nextModelHandle++; _contextHandle = null; @@ -346,6 +348,7 @@ class LiteRtLmService { _bundleTemplateProbed = false; _bundleTemplateAdapter = null; _bundleTemplateMisreadsContent = false; + _startToken = null; _bundleDeclaresThinkingChannel = null; _modelHandle = null; _contextHandle = null; @@ -539,6 +542,16 @@ class LiteRtLmService { if (_cancelRequested) { return; } + final rawPrompt = _withoutLeadingStartToken(client, prompt); + if (rawPrompt.isEmpty) { + throw LlamaArgumentException( + 'LiteRtLmBackend raw prompt generation needs prompt text: the ' + 'LiteRT-LM runtime cannot prefill an empty prompt or one that holds ' + "only the model's start token.", + name: 'prompt', + invalidValue: prompt, + ); + } final backend = _activeBackend ?? _backendNameFor(_modelParams ?? const ModelParams()); final loraPath = _activeTextLoraPath(); @@ -552,11 +565,7 @@ class LiteRtLmService { npuBackend: backend == 'npu', loraPath: loraPath, ); - _createBundleTemplateConversation( - client, - create: createConversation, - createProbe: createConversation, - ); + createConversation(liteRtLmRawPromptTemplate); if (_cancelRequested) { client.cancel(); return; @@ -566,20 +575,14 @@ class LiteRtLmService { .where((sequence) => sequence.isNotEmpty) .toList(growable: false); final sw = Stopwatch()..start(); - var outputStarted = false; try { final stream = _applyStopSequences( - client - .generate( - prompt, - maxOutputTokens: params.maxTokens, - repetitionPenalty: controls.repetitionPenalty, - presencePenalty: controls.presencePenalty, - ) - .map((chunk) { - outputStarted = true; - return chunk; - }), + client.generate( + rawPrompt, + maxOutputTokens: params.maxTokens, + repetitionPenalty: controls.repetitionPenalty, + presencePenalty: controls.presencePenalty, + ), stopSequences, onStop: cancelGeneration, ); @@ -590,8 +593,6 @@ class LiteRtLmService { yield chunk; } _lastGenerationLimit = _generationLimitOf(client); - } on StateError catch (error, stackTrace) { - _throwSendFailure(error, stackTrace, outputStarted: outputStarted); } finally { sw.stop(); try { @@ -604,6 +605,51 @@ class LiteRtLmService { } } + /// Returns [prompt] without a leading start token, which the runtime adds + /// before every prompt, so that a prompt holding one does not get two. As + /// llama.cpp does, this compares tokens: ordinary text that tokenizes to the + /// start token is removed only when the rest of the prompt keeps its tokens. + /// Special-token text, such as Gemma's ``, which the runtime reads as + /// the token but [LiteRtLmRuntimeClientContract.tokenize] does not, is + /// removed as text. + String _withoutLeadingStartToken( + LiteRtLmRuntimeClientContract client, + String prompt, + ) { + final start = _startToken ??= () { + final tokens = client.tokenize('', addSpecial: true); + final text = tokens.isEmpty ? '' : client.detokenize(tokens); + return ( + tokens: tokens, + text: text, + plainText: _sameTokens( + client.tokenize(text, addSpecial: false), + tokens, + ), + ); + }(); + if (start.text.isEmpty || !prompt.startsWith(start.text)) { + return prompt; + } + final rest = prompt.substring(start.text.length); + if (!start.plainText) { + return rest; + } + final keepsTokens = _sameTokens( + client.tokenize(prompt, addSpecial: false), + [...start.tokens, ...client.tokenize(rest, addSpecial: false)], + ); + return keepsTokens ? rest : prompt; + } + + static bool _sameTokens(List a, List b) { + if (a.length != b.length) return false; + for (var i = 0; i < a.length; i++) { + if (a[i] != b[i]) return false; + } + return true; + } + /// Admits the actual native provider, rather than relying on setter exports. Future prepareJsonSchemaChat() async { if (_jsonSchemaAdmitted) return; diff --git a/skills/llamadart-chat-streaming/SKILL.md b/skills/llamadart-chat-streaming/SKILL.md index fe66ed48b..57465468b 100644 --- a/skills/llamadart-chat-streaming/SKILL.md +++ b/skills/llamadart-chat-streaming/SKILL.md @@ -36,7 +36,8 @@ modalities and speculative strategies before offering them. one-shot tasks, edited or persisted histories). Pass the full message list every call and append the assistant reply yourself. - `engine.generate(prompt)` only for an already-rendered raw prompt; it skips - the chat template. + the chat template, except on LiteRT-LM Web, which sends the prompt as one + user turn through the bundle's template. - Opt in with the portable `LlamaBackend.withTextHistory()` factory, or the direct Web `LiteRtLmBackend.withTextHistory()` factory, for ordered system/user/assistant text through 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 3729c6621..b96850b04 100644 --- a/test/e2e/backends/litert_lm_bundle_template_e2e_test.dart +++ b/test/e2e/backends/litert_lm_bundle_template_e2e_test.dart @@ -11,6 +11,7 @@ import 'package:llamadart/src/backends/litert_lm/litert_lm_bundle_template.dart' import 'package:llamadart/src/backends/litert_lm/litert_lm_cache.dart'; import 'package:llamadart/src/backends/litert_lm/litert_lm_runtime.dart'; import 'package:llamadart/src/backends/litert_lm/litert_lm_service.dart'; +import 'package:llamadart/src/core/exceptions.dart'; import 'package:llamadart/src/core/llama_logger.dart'; import 'package:llamadart/src/core/models/chat/chat_message.dart'; import 'package:llamadart/src/core/models/chat/chat_role.dart'; @@ -19,6 +20,8 @@ import 'package:llamadart/src/core/models/inference/generation_params.dart'; import 'package:llamadart/src/core/models/inference/model_params.dart'; import 'package:test/test.dart'; +import '../../support/suite_system_temp.dart'; + const _generationPrompt = "{%- if add_generation_prompt -%}{{ '<|im_start|>assistant\\n' }}" '{%- endif -%}'; @@ -66,6 +69,13 @@ const _messageKeysTemplate = '{% endfor -%}'; const _userTurn = '<|im_start|>user\n'; + +/// Raw prompts, one already rendered as a ChatML turn. +const _rawPrompts = [ + 'hi', + '\n The capital of France is', + '<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n', +]; const _assistantTurn = '<|im_end|>\n<|im_start|>assistant\n'; /// Records what the service asks of the real runtime. @@ -104,6 +114,29 @@ class _RecordingClient extends LiteRtLmRuntimeClient { ); } + @override + Stream generate( + String prompt, { + int? maxOutputTokens, + double? repetitionPenalty, + double? presencePenalty, + }) { + sentPrompts.add( + renderMessageToString({ + 'role': 'user', + 'content': [ + {'type': 'text', 'text': prompt}, + ], + }), + ); + return super.generate( + prompt, + maxOutputTokens: maxOutputTokens, + repetitionPenalty: repetitionPenalty, + presencePenalty: presencePenalty, + ); + } + @override Stream generateMessageJson( String messageJson, { @@ -185,6 +218,7 @@ String _bundleWithTemplate( } void main() { + useSuiteSystemTemp(); final model = Platform.environment['LITERT_LM_MODEL']; setUpAll(() { @@ -368,6 +402,23 @@ void main() { ); }); + test('renders a raw prompt unchanged through the raw prompt template', () { + for (final prompt in _rawPrompts) { + expect( + render( + liteRtLmRawPromptTemplate, + message: { + 'role': 'user', + 'content': [ + {'type': 'text', 'text': prompt}, + ], + }, + ), + prompt, + ); + } + }); + test('keeps how a template handles the whitespace it starts with', () { for (final template in [ '\n start', @@ -403,6 +454,91 @@ void main() { directory.deleteSync(recursive: true); }); + test('sends a raw prompt that starts with the start token with one start ' + 'token', () async { + final cache = Directory('${directory.path}/cache')..createSync(); + final client = _RecordingClient(); + final service = LiteRtLmService(clientFactory: () => client); + final params = ModelParams( + contextSize: 1024, + numberOfThreads: 2, + liteRtLmBackend: LiteRtLmBackendPreference.cpu, + liteRtLmCacheDir: cache.path, + ); + try { + final handle = await service.loadModel(model!, params); + final context = service.createContext(handle, params); + final start = await service.tokenize(handle, '', true); + if (start.isEmpty) { + markTestSkipped('The runtime adds no start token for this bundle.'); + return; + } + final startText = client.detokenize(start); + await service + .generate( + context, + '${startText}hi', + const GenerationParams(maxTokens: 1, temp: 0, seed: 1), + ) + .drain(); + + expect(client.sentPrompts, ['hi']); + expect( + service.getPerformanceContext(context)?.promptEvalTokens, + (await service.tokenize(handle, 'hi', true)).length, + ); + await expectLater( + service + .generate( + context, + startText, + const GenerationParams(maxTokens: 1, temp: 0, seed: 1), + ) + .drain(), + throwsA(isA()), + ); + } finally { + service.dispose(); + } + }); + + test('sends a raw prompt to the model unchanged', () async { + final cache = Directory('${directory.path}/cache')..createSync(); + final client = _RecordingClient(); + final service = LiteRtLmService(clientFactory: () => client); + final params = ModelParams( + contextSize: 1024, + numberOfThreads: 2, + liteRtLmBackend: LiteRtLmBackendPreference.cpu, + liteRtLmCacheDir: cache.path, + ); + try { + final handle = await service.loadModel(model!, params); + final context = service.createContext(handle, params); + for (final prompt in _rawPrompts) { + await service + .generate( + context, + prompt, + const GenerationParams(maxTokens: 1, temp: 0, seed: 1), + ) + .drain(); + final tokens = await service.tokenize(handle, prompt, true); + expect( + service.getPerformanceContext(context)?.promptEvalTokens, + tokens.length, + reason: prompt, + ); + } + expect(client.promptTemplates, [ + for (final _ in _rawPrompts) liteRtLmRawPromptTemplate, + ]); + expect(client.sentPrompts, _rawPrompts); + } finally { + service.dispose(); + } + }); + for (final MapEntry(key: shape, value: template) in _stringContentTemplates.entries) { test('answers with a bundle whose template is $shape content', () async { 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 01803b616..b17982642 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 @@ -410,6 +410,42 @@ void main() { }); }); + group('liteRtLmRawPromptTemplate', () { + const prompts = [ + 'hi', + '\n The capital of France is', + '<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n', + '{{ messages }} {% if x %}literal{% endif %}\n\n', + '안녕 \t trailing whitespace \n', + ]; + + for (final prompt in prompts) { + test('renders ${jsonEncode(prompt)} unchanged', () { + expect( + renderLiteRtLmContent(liteRtLmRawPromptTemplate, [ + {'type': 'text', 'text': prompt}, + ]), + prompt, + ); + expect( + renderLiteRtLmContent(liteRtLmRawPromptTemplate, prompt), + prompt, + ); + }); + } + + test('renders only the text parts of a message', () { + expect( + renderLiteRtLmContent(liteRtLmRawPromptTemplate, [ + {'type': 'text', 'text': 'a'}, + {'type': 'image'}, + {'type': 'text', 'text': 'b'}, + ]), + 'ab', + ); + }); + }); + group('liteRtLmTextContentAdapter', () { const probeParts = [ {'type': 'text', 'text': liteRtLmContentShapeProbeText}, diff --git a/test/unit/backends/litert_lm/litert_lm_conversation_template_test.dart b/test/unit/backends/litert_lm/litert_lm_conversation_template_test.dart index 6e2def6f3..7281f3962 100644 --- a/test/unit/backends/litert_lm/litert_lm_conversation_template_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_conversation_template_test.dart @@ -9,6 +9,7 @@ import 'package:ffi/ffi.dart'; import 'package:llamadart/src/backends/litert_lm/litert_lm_runtime.dart'; import 'package:llamadart/src/core/exceptions.dart'; +import 'package:llamadart/src/hook/native_release_pins.dart'; import 'package:test/test.dart'; Future _compileFixture(Directory dir, List defines) async { @@ -41,7 +42,18 @@ void main() { promptTemplate: 'required', npuBackend: true, ), - throwsA(isA()), + throwsA( + isA().having( + (error) => error.message, + 'message', + allOf( + contains('litert_lm_conversation_config_set_prompt_template'), + contains('cannot set a conversation template'), + contains('raw prompt generation'), + contains('litert-lm-native $liteRtLmReleaseTag'), + ), + ), + ), ); // A runtime without this optional setter still supports requests // which preserve its native model template. 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 64e212293..0ead40094 100644 --- a/test/unit/backends/litert_lm/litert_lm_service_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_service_test.dart @@ -535,6 +535,102 @@ void main() { }); }); + group('raw prompt start token', () { + const params = ModelParams(liteRtLmBackend: LiteRtLmBackendPreference.cpu); + late _FakeLiteRtLmRuntimeClient client; + + setUp(() => client = _FakeLiteRtLmRuntimeClient()); + + /// A tokenizer that puts [start] (the text of token 1) before every + /// prompt and reads [vocabulary] words, longest first, one token each. + void tokenizer(String start, Map vocabulary) { + client.onTokenize = (text, addSpecial) { + final tokens = [if (addSpecial && start.isNotEmpty) 1]; + var rest = text; + while (rest.isNotEmpty) { + final word = vocabulary.keys + .where(rest.startsWith) + .fold('', (a, b) => b.length > a.length ? b : a); + if (word.isEmpty) { + tokens.add(rest.codeUnitAt(0) + 1000); + rest = rest.substring(1); + } else { + tokens.add(vocabulary[word]!); + rest = rest.substring(word.length); + } + } + return tokens; + }; + client.onDetokenize = (tokens) => + tokens.length == 1 && tokens.single == 1 ? start : ''; + } + + LiteRtLmService? service; + int? context; + + tearDown(() { + service?.dispose(); + service = null; + }); + + Future send(String prompt) async { + if (service == null) { + service = LiteRtLmService(clientFactory: () => client); + final model = await service!.loadModel(modelFile.path, params); + context = service!.createContext(model, params); + } + client.generated = StreamController()..add('ok'); + unawaited(client.generated.close()); + await service! + .generate(context!, prompt, const GenerationParams(maxTokens: 8)) + .drain(); + return client.lastPrompt; + } + + test('drops special start-token text the runtime would read as a second ' + 'start token', () async { + tokenizer('', const {'hi': 50}); + expect(await send('hi'), 'hi'); + expect(await send('hi'), 'hi'); + expect(await send('hi'), 'hi'); + }); + + test('drops plain start-token text only when the rest keeps its ' + 'tokens', () async { + tokenizer('None', const {'None': 1, 'hi': 50, 'Nonet': 60, 'he': 61}); + expect(await send('Nonehi'), 'hi'); + expect(await send('Nonethe'), 'Nonethe'); + }); + + test('keeps a prompt when the runtime adds no start token', () async { + tokenizer('', const {'hi': 50}); + expect(await send('hi'), 'hi'); + }); + + for (final (name, start, prompt) in [ + ('an empty prompt', '', ''), + ('a prompt that is only the start token', '', ''), + ]) { + test('refuses $name before native work', () async { + tokenizer(start, const {}); + await expectLater( + send(prompt), + throwsA( + isA() + .having((error) => error.name, 'name', 'prompt') + .having( + (error) => error.message, + 'message', + contains('needs prompt text'), + ), + ), + ); + expect(client.createConversationCount, 0); + expect(client.generateCount, 0); + }); + } + }); + group('bundle template content shape', () { const params = ModelParams(liteRtLmBackend: LiteRtLmBackendPreference.cpu); const probeParts = [ @@ -635,10 +731,8 @@ void main() { ]); expect(readPaths, [modelFile.path]); - await raw(service, context); await chat(service, context); expect(client.conversations.skip(3), [ - (template: adapter, seeded: false), (template: adapter, seeded: true), ]); expect(client.renderMessageCount, 2); @@ -657,11 +751,11 @@ void main() { final model = await service.loadModel(modelFile.path, params); final context = service.createContext(model, params); - await raw(service, context); + await chat(service, context); await chat(service, context); expect(client.conversations, [ (template: null, seeded: false), - (template: null, seeded: false), + (template: null, seeded: true), (template: null, seeded: true), ]); expect(client.renderMessageCount, 1); @@ -765,10 +859,8 @@ void main() { final created = client.conversations.length; final rendered = client.renderMessageCount; await chat(service, context); - await raw(service, context); expect(client.conversations.skip(created), [ (template: null, seeded: true), - (template: null, seeded: false), ]); expect(client.renderMessageCount, rendered); expect(records, hasLength(1)); @@ -778,35 +870,111 @@ void main() { }); } - for (final (name, send) in [('chat', chat), ('raw', raw)]) { - test('a failed $name send names a bundle template it could not ' - 'adapt', () async { - client.onRenderMessage = (_) => throw StateError('render failed'); - final service = serviceReading(null); - final failure = StateError('send_message_stream rc=13'); - try { - final model = await service.loadModel(modelFile.path, params); - final context = service.createContext(model, params); + test('a failed chat send names a bundle template it could not ' + 'adapt', () async { + client.onRenderMessage = (_) => throw StateError('render failed'); + final service = serviceReading(null); + final failure = StateError('send_message_stream rc=13'); + try { + final model = await service.loadModel(modelFile.path, params); + final context = service.createContext(model, params); - await expectLater( - send(service, context, sendError: failure), - throwsA( - isA().having( - (error) => error.message, - 'message', - allOf( - startsWith('send_message_stream rc=13 '), - contains('chat template of this bundle'), - contains('list of {"type": "text", "text": ...} parts'), - ), + await expectLater( + chat(service, context, sendError: failure), + throwsA( + isA().having( + (error) => error.message, + 'message', + allOf( + startsWith('send_message_stream rc=13 '), + contains('chat template of this bundle'), + contains('list of {"type": "text", "text": ...} parts'), ), ), - ); - } finally { - service.dispose(); - } - }); + ), + ); + } finally { + service.dispose(); + } + }); + + test('a failed raw send does not name a bundle template it does not ' + 'use', () async { + client.onRenderMessage = (_) => throw StateError('render failed'); + final service = serviceReading(null); + final failure = StateError('send_message_stream rc=13'); + try { + final model = await service.loadModel(modelFile.path, params); + final context = service.createContext(model, params); + await chat(service, context); + expect(records.single.message, contains('could not adapt')); + + await expectLater( + raw(service, context, sendError: failure), + throwsA(same(failure)), + ); + } finally { + service.dispose(); + } + }); + test('raw generation sends the prompt unchanged, without the bundle ' + 'template or its probe', () async { + renderLikeTheRuntime(interpolating); + final service = serviceReading(interpolating); + try { + final model = await service.loadModel(modelFile.path, params); + final context = service.createContext(model, params); + const prompt = + '<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n'; + client.generated = StreamController()..add('Hi'); + unawaited(client.generated.close()); + + await service + .generate(context, prompt, const GenerationParams(maxTokens: 8)) + .drain(); + + expect(client.conversations, [ + (template: liteRtLmRawPromptTemplate, seeded: false), + ]); + expect(client.lastPrompt, prompt); + expect(client.renderMessageCount, 0); + expect(readPaths, isEmpty); + + await chat(service, context); + expect(client.conversations.skip(1), [ + (template: null, seeded: false), + (template: liteRtLmTextContentAdapter(interpolating), seeded: false), + (template: liteRtLmTextContentAdapter(interpolating), seeded: true), + ]); + } finally { + service.dispose(); + } + }); + + test('raw generation keeps a runtime refusal of its template', () async { + final refusal = LlamaUnsupportedException('no template setter'); + client.onCreateConversation = () { + if (client.lastPromptTemplate != null) throw refusal; + }; + final service = serviceReading(null); + try { + final model = await service.loadModel(modelFile.path, params); + final context = service.createContext(model, params); + + await expectLater( + service + .generate(context, 'Hello', const GenerationParams(maxTokens: 8)) + .drain(), + throwsA(same(refusal)), + ); + expect(client.generateCount, 0); + } finally { + service.dispose(); + } + }); + + for (final (name, send) in [('chat', chat), ('raw', raw)]) { test('a failed $name send stays as it is for a template that reads ' 'content', () async { final service = serviceReading(liteRtLmPartsContentTemplate); @@ -8246,12 +8414,15 @@ class _FakeLiteRtLmRuntimeClient extends LiteRtLmRuntimeClient { bool thinkingBudget = true; LiteRtLmFinishReason? finishReason; List tokenizeResult = const []; + List? Function(String text, bool addSpecial)? onTokenize; + String? Function(List tokens)? onDetokenize; String detokenizeResult = ''; LiteRtLmRuntimeMetrics? metrics; Object? metricsError; void Function()? onCreateConversation; void Function()? onInitialize; String? lastPromptTemplate; + String? lastPrompt; final List<({String? template, bool seeded})> conversations = []; String Function(String? promptTemplate)? onRenderMessage; @@ -8386,14 +8557,14 @@ class _FakeLiteRtLmRuntimeClient extends LiteRtLmRuntimeClient { _checkNotDisposed(); lastTokenizeText = text; lastTokenizeAddSpecial = addSpecial; - return tokenizeResult; + return onTokenize?.call(text, addSpecial) ?? tokenizeResult; } @override String detokenize(List tokens) { _checkNotDisposed(); lastDetokenizeTokens = List.from(tokens); - return detokenizeResult; + return onDetokenize?.call(tokens) ?? detokenizeResult; } @override @@ -8413,6 +8584,7 @@ class _FakeLiteRtLmRuntimeClient extends LiteRtLmRuntimeClient { double? presencePenalty, }) { _checkNotDisposed(); + lastPrompt = prompt; lastMaxOutputTokens = maxOutputTokens; lastRepetitionPenalty = repetitionPenalty; lastPresencePenalty = presencePenalty; diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 0c59da21d..0a9353bbe 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -13,6 +13,7 @@ validate against the exact release tag notes. ## Unreleased +- 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)). ## 0.19.1 diff --git a/website/docs/guides/generation-and-streaming.md b/website/docs/guides/generation-and-streaming.md index 459fb7f8a..348397f42 100644 --- a/website/docs/guides/generation-and-streaming.md +++ b/website/docs/guides/generation-and-streaming.md @@ -19,6 +19,15 @@ description: Stream tokens with generate, create and ChatSession; use structured | `engine.create(messages)` | Yes | No | You have the complete `List` for each request, such as an OpenAI-compatible server, a one-shot completion, or an app that owns its transcript. | | `ChatSession.create(parts)` | Yes | Yes | You are building a multi-turn chat UI/CLI and want the SDK to append user/assistant turns, apply the system prompt, and trim history as the context grows. | +`engine.generate(prompt)` sends the prompt without a chat template, on +native LiteRT-LM too. Where the model uses a BOS (start) token, the backend +adds one, and only one: a prompt that already starts with it, such as a +`chatTemplate()` prompt beginning with Gemma's ``, does not get a second. +Native LiteRT-LM throws `LlamaArgumentException` for an empty prompt. +LiteRT-LM Web is the exception: it sends the prompt as one user turn through +the bundle's chat template, because `@litert-lm/core` cannot replace that +template ([#1863](https://github.com/leehack/llamadart/issues/1863)). + For one-shot instructions, prefer `engine.create(...)`: it applies the chat template without session state, and a follow-up turn sees only the messages you pass again. For chat apps, prefer `ChatSession` unless your app already stores