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
@@ -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 `<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)).

## 0.19.1
Expand Down
41 changes: 23 additions & 18 deletions example/chat_app/lib/litert_lm_benchmark_app.dart
Original file line number Diff line number Diff line change
Expand Up @@ -384,16 +384,7 @@ class _LiteRtLmBenchmarkAppState extends State<LiteRtLmBenchmarkApp> {
);

for (var i = 0; i < _warmups; i++) {
await engine
.generate(
_promptController.text,
params: GenerationParams(
maxTokens: _outputTokens,
seed: 1,
speculativeDecoding: _speculative,
),
)
.drain<void>();
await _liteRtChat(engine).drain<void>();
}

var lastText = '';
Expand All @@ -403,14 +394,7 @@ class _LiteRtLmBenchmarkAppState extends State<LiteRtLmBenchmarkApp> {
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();
Expand Down Expand Up @@ -501,6 +485,27 @@ class _LiteRtLmBenchmarkAppState extends State<LiteRtLmBenchmarkApp> {
};
}

// 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<String> _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<void> _runLlamaDartBenchmark(
String modelPath, {
String? draftModelPath,
Expand Down
18 changes: 18 additions & 0 deletions lib/src/backends/litert_lm/litert_lm_bundle_template.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down
8 changes: 6 additions & 2 deletions lib/src/backends/litert_lm/litert_lm_runtime.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
84 changes: 65 additions & 19 deletions lib/src/backends/litert_lm/litert_lm_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,7 @@ class LiteRtLmService {
bool _bundleTemplateProbed = false;
String? _bundleTemplateAdapter;
bool _bundleTemplateMisreadsContent = false;
({List<int> tokens, String text, bool plainText})? _startToken;
({bool penalties, bool thinkingBudget})? _runtimeGenerationControls;
bool? _runtimeFinishReasons;
BackendGenerationLimit? _lastGenerationLimit;
Expand Down Expand Up @@ -319,6 +320,7 @@ class LiteRtLmService {
_bundleTemplateProbed = false;
_bundleTemplateAdapter = null;
_bundleTemplateMisreadsContent = false;
_startToken = null;
_bundleDeclaresThinkingChannel = null;
_modelHandle = _nextModelHandle++;
_contextHandle = null;
Expand Down Expand Up @@ -346,6 +348,7 @@ class LiteRtLmService {
_bundleTemplateProbed = false;
_bundleTemplateAdapter = null;
_bundleTemplateMisreadsContent = false;
_startToken = null;
_bundleDeclaresThinkingChannel = null;
_modelHandle = null;
_contextHandle = null;
Expand Down Expand Up @@ -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();
Expand All @@ -552,11 +565,7 @@ class LiteRtLmService {
npuBackend: backend == 'npu',
loraPath: loraPath,
);
_createBundleTemplateConversation(
client,
create: createConversation,
createProbe: createConversation,
);
createConversation(liteRtLmRawPromptTemplate);
if (_cancelRequested) {
client.cancel();
return;
Expand All @@ -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,
);
Expand All @@ -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 {
Expand All @@ -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 `<bos>`, 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<int> a, List<int> 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<void> prepareJsonSchemaChat() async {
if (_jsonSchemaAdmitted) return;
Expand Down
3 changes: 2 additions & 1 deletion skills/llamadart-chat-streaming/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading