diff --git a/CHANGELOG.md b/CHANGELOG.md index b3dda59e7..5bacebb0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ ## Unreleased - Add manual tool calling to LiteRT-LM Web through `LlamaBackend.withTextHistory()` on `@litert-lm/core@0.19.0`: tools reach the model, `create` returns its tool calls, and tool results go back in the next request. `supportsToolCalling` reports whether the loaded runtime reads tool declarations; automatic tool loops, `ToolChoice.required` and `parallelToolCalls` still throw `LlamaUnsupportedException` ([#1790](https://github.com/leehack/llamadart/issues/1790)). +- Report LiteRT-LM Web replies cut off at `maxTokens` or the context size as finish reason `length`, and run automatic tool loops (`sendWithTools`, `completeWithTools`) there, through `LlamaBackend.withTextHistory()` on `@litert-lm/core@0.19.0`. A load probe checks that the runtime reports per-turn token counts; a reply that ends exactly at `maxTokens` is also reported as `length` ([#919](https://github.com/leehack/llamadart/issues/919)). ## 0.19.2 diff --git a/README.md b/README.md index c6e11814b..d94f7c859 100644 --- a/README.md +++ b/README.md @@ -174,8 +174,8 @@ published native owner source `0b15fb34` / upstream `7a03724c`. The selected loader requires macOS 14+ before owned library loads, including legacy libraries and custom paths. Web LiteRT-LM uses `@litert-lm/core@0.19.0`; through -`LlamaBackend.withTextHistory()` it forwards chat history and supports manual -tool calling. +`LlamaBackend.withTextHistory()` it forwards chat history, supports tool +calling and reports replies cut off at a token limit. Native overrides accept stable `vMAJOR.MINOR.PATCH` releases and explicit historical or nightly `bNNNN` artifacts. New nightly wrapper rebuilds use diff --git a/doc/testing_matrix.md b/doc/testing_matrix.md index 84701f85d..9f2289259 100644 --- a/doc/testing_matrix.md +++ b/doc/testing_matrix.md @@ -1206,9 +1206,32 @@ dart run tool/testing/run_local_e2e.dart --scenario litert-lm-web-tool-calling \ --model-path /path/to/Qwen3-0.6B.litertlm --backend cpu --dry-run ``` -Use `--backend gpu` with a `-web.litertlm` bundle for WebGPU. Automatic tool -loops stay out of scope until the runtime reports truncation -([#919](https://github.com/leehack/llamadart/issues/919)). +Use `--backend gpu` with a `-web.litertlm` bundle for WebGPU. + +### LiteRT-LM Web truncation + +`litert-lm-web-truncation` runs the same local server and Chrome +configuration with `test/e2e/backends/litert_lm_truncation_web_e2e_test.dart` +([#919](https://github.com/leehack/llamadart/issues/919)). It downloads no +model. The published runtime alone, with `benchmarkEnabled`, measures a +natural reply's decode steps `n` and replays it at budgets `n + 1`, `n`, +`n - 1` and `n - 2`, then fills a 1024-token context. The adapter must report +`stop` above `n`, `length`/`maxTokens` at and below it, `length`/`contextSize` +for the filled context, complete an automatic `get_weather` loop, and stop a +3-token loop as `truncated` without running the tool. A last phase requests a +65536-token context, above a fixed KV cache such as Qwen3 0.6B's 4096 on WASM +CPU: the runtime's own over-long-prompt rejection names the executor's limit, +and the adapter must report the long reply as `length` at that limit or at +`maxTokens` 8192. Dry-run before +execution: + +```bash +dart run tool/testing/run_local_e2e.dart --scenario litert-lm-web-truncation \ + --model-path /path/to/Qwen3-0.6B.litertlm --backend cpu --dry-run +``` + +Use `--backend gpu` with a `-web.litertlm` bundle for WebGPU. Rerun it when +the `@litert-lm/core` pin changes. ### Native LiteRT-LM JSON Schema diff --git a/example/chat_app/README.md b/example/chat_app/README.md index 606b54ca9..ef610ef66 100644 --- a/example/chat_app/README.md +++ b/example/chat_app/README.md @@ -279,11 +279,11 @@ flutter test --run-skipped -t local-only \ - The chat app explicitly uses `LlamaBackend.withTextHistory()` to forward ordered system/user/assistant text through the probed LiteRT-LM Web conversation API. The runtime still applies its own model template. - Function Calling and Thinking controls remain unavailable: the app uses - model-default thinking without changing saved preferences. The library - supports manual LiteRT-LM Web tool calls, but this app runs tool calls - automatically, which needs the truncation report the runtime lacks - ([#919](https://github.com/leehack/llamadart/issues/919)). Media and + Thinking controls remain unavailable: the app uses model-default + thinking without changing saved preferences. Function Calling runs when + the loaded runtime reports replies cut off at a token limit + (`@litert-lm/core@0.19.0`, + [#919](https://github.com/leehack/llamadart/issues/919)). Media and template/thinking controls are outside this slice. Existing core default backends and the Genkit adapter do not opt in automatically. @@ -372,6 +372,9 @@ layouts) opens a separate screen for the experimental `ImageGenerationEngine` offload when it fits. Choosing a lower layer count makes it a fixed manual setting. Reload the model to apply changes. 3. Optionally enable **Function Calling** and edit tool declarations depending on model/template support. + The app runs the model's tool calls itself, on every runtime, and runs + none from a reply that ended at the token limit (finish reason `length`): + it shows a notice instead. Raise **Max generated tokens** and send again. 4. Tap **Load Model** to apply changes. diff --git a/example/chat_app/lib/providers/chat_provider.dart b/example/chat_app/lib/providers/chat_provider.dart index 526f6a079..245492be5 100644 --- a/example/chat_app/lib/providers/chat_provider.dart +++ b/example/chat_app/lib/providers/chat_provider.dart @@ -6,6 +6,7 @@ import 'dart:ui' as ui; import 'package:dio/dio.dart'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/foundation.dart'; +import 'package:llamadart/backend.dart'; import 'package:llamadart/llamadart.dart'; import 'package:path/path.dart' as p; @@ -2062,6 +2063,7 @@ class ChatProvider extends ChangeNotifier { var hasAudioPartsInTurn = false; var isCpuMultimodalTurn = false; var pendingToolCalls = const []; + var toolCallsCutOff = false; var accountingApplied = false; try { @@ -2261,7 +2263,12 @@ class ChatProvider extends ChangeNotifier { if (allowToolExecution && toolsForTurn != null && toolCalls.isNotEmpty) { - pendingToolCalls = toolCalls; + // A reply cut off at a token limit may hold only some of its calls. + if (generationResult.reachedTokenLimit) { + toolCallsCutOff = true; + } else { + pendingToolCalls = toolCalls; + } } } } @@ -2284,6 +2291,11 @@ class ChatProvider extends ChangeNotifier { } _removeEmptyAssistantPlaceholder(); + if (toolCallsCutOff) { + _addInfoMessage( + 'The reply reached the token limit, so its tool calls were not run. Raise Max generated tokens and send it again.', + ); + } } catch (e) { if (!_generationContextMatches(context)) { return; @@ -4449,10 +4461,17 @@ class ChatProvider extends ChangeNotifier { } void _updateToolTemplateSupport(Map metadata) { - // This app runs the model's calls automatically, which needs the - // truncation report LiteRT-LM Web lacks (#919). + // This app runs the model's calls itself, so it needs a reply cut off at + // a token limit reported; LiteRT-LM Web reports it only on runtimes that + // pass its load probe (#919). + final backend = _chatService.engine.backend; final unreportedTruncation = - kIsWeb && _engineCapabilities.runtime == LlamaRuntime.liteRtLm; + kIsWeb && + _engineCapabilities.runtime == LlamaRuntime.liteRtLm && + (backend is! BackendGenerationLimitSupport || + (backend as BackendGenerationLimitSupport) + .generationLimitUnsupportedReason != + null); if (!_engineCapabilities.supportsToolCalling || unreportedTruncation) { _detectedChatFormat = ChatFormat.contentOnly; _templateSupportsTools = false; diff --git a/example/chat_app/lib/services/chat_generation_service.dart b/example/chat_app/lib/services/chat_generation_service.dart index b5fa4c087..a06e66c66 100644 --- a/example/chat_app/lib/services/chat_generation_service.dart +++ b/example/chat_app/lib/services/chat_generation_service.dart @@ -26,6 +26,9 @@ class GenerationStreamResult { final int elapsedMs; final int decodeElapsedMs; + /// Whether the reply ended at a token limit (finish reason `length`). + final bool reachedTokenLimit; + const GenerationStreamResult({ required this.fullResponse, required this.fullThinking, @@ -33,6 +36,7 @@ class GenerationStreamResult { required this.firstTokenLatencyMs, required this.elapsedMs, required this.decodeElapsedMs, + this.reachedTokenLimit = false, }); } @@ -113,6 +117,7 @@ class ChatGenerationService { var cleanTarget = ''; var generatedTokens = 0; var sawFirstToken = false; + var reachedTokenLimit = false; int? firstTokenLatencyMs; final effectiveNotifyIntervalMs = uiNotifyIntervalMs <= 0 @@ -252,6 +257,9 @@ class ChatGenerationService { final content = chunk.text; final thinking = thinkingEnabled ? chunk.thinking : ''; + if (chunk.choices.firstOrNull?.finishReason == 'length') { + reachedTokenLimit = true; + } if (!sawFirstToken && (content.isNotEmpty || @@ -344,6 +352,7 @@ class ChatGenerationService { firstTokenLatencyMs: firstTokenLatencyMs, elapsedMs: streamElapsedMs, decodeElapsedMs: decodeElapsedMs, + reachedTokenLimit: reachedTokenLimit, ); } diff --git a/example/chat_app/test/mocks.dart b/example/chat_app/test/mocks.dart index ef1ac9669..57d1b9d7b 100644 --- a/example/chat_app/test/mocks.dart +++ b/example/chat_app/test/mocks.dart @@ -235,9 +235,9 @@ class MockLlamaEngine extends LlamaEngine { supportsStreamBatching: true, ); - MockLlamaEngine() + MockLlamaEngine({MockLlamaBackend? backend}) : super( - MockLlamaBackend(), + backend ?? MockLlamaBackend(), modelDownloadManager: FakeModelDownloadManager(), ); diff --git a/example/chat_app/test/unit_test.dart b/example/chat_app/test/unit_test.dart index c224a12b1..01898d488 100644 --- a/example/chat_app/test/unit_test.dart +++ b/example/chat_app/test/unit_test.dart @@ -523,8 +523,8 @@ void main() { }, ); - test('loadModel keeps tools off for LiteRT-LM Web tool calling, which ' - 'reports no truncation', () async { + test('loadModel turns tools on for LiteRT-LM Web tool calling once its ' + 'runtime reports truncation', () async { final initialSettings = const ChatSettings( modelPath: 'https://example.com/gemma-4-web.litertlm', toolsEnabled: true, @@ -534,9 +534,9 @@ void main() { engine: _MetadataEngine(const { 'general.architecture': 'litert-lm', - 'tokenizer.chat_template': - '{% for message in messages %}{% if loop.last %}{{ message["content"] }}{% endif %}{% endfor %}', - }) + 'llamadart.chat_template.parsing': + '{% for message in messages %}{{ message["content"] }}{% endfor %}', + }, backend: _LimitReportingBackend(null)) ..loadedCapabilities = const LlamaEngineCapabilities( isSupported: true, runtime: LlamaRuntime.liteRtLm, @@ -552,18 +552,55 @@ void main() { await provider.loadModel(); - expect(provider.templateSupportsTools, isFalse); - expect(provider.settings.toolsEnabled, isFalse); - expect( - provider.messages.map((message) => message.text), - contains( - kIsWeb - ? contains('runs tool calls automatically') - : contains('template is content-only'), - ), - ); + expect(provider.templateSupportsTools, isTrue); + expect(provider.settings.toolsEnabled, isTrue); }); + for (final (name, backend) in [ + ('has no truncation report', MockLlamaBackend()), + ('reports no truncation', _LimitReportingBackend('No token counts.')), + ]) { + test('loadModel keeps tools off on the Web for LiteRT-LM tool calling ' + 'whose runtime $name', () async { + final initialSettings = const ChatSettings( + modelPath: 'https://example.com/gemma-4-web.litertlm', + toolsEnabled: true, + ); + final provider = ChatProvider( + chatService: MockChatService( + engine: + _MetadataEngine(const { + 'general.architecture': 'litert-lm', + 'llamadart.chat_template.parsing': + '{% for message in messages %}{{ message["content"] }}{% endfor %}', + }, backend: backend) + ..loadedCapabilities = const LlamaEngineCapabilities( + isSupported: true, + runtime: LlamaRuntime.liteRtLm, + supportsMultiTurnChat: true, + supportsToolCalling: true, + ), + ), + settingsService: MockSettingsService()..settings = initialSettings, + enableWebModelPrefetch: false, + initialSettings: initialSettings, + ); + addTearDown(provider.dispose); + + await provider.loadModel(); + + // Native LiteRT-LM keeps tools on. + expect(provider.templateSupportsTools, !kIsWeb); + expect(provider.settings.toolsEnabled, !kIsWeb); + if (kIsWeb) { + expect( + provider.messages.map((message) => message.text), + contains(contains('runs tool calls automatically')), + ); + } + }); + } + test( 'loadModel detects tool support from the LiteRT-LM parsing template', () async { @@ -601,7 +638,7 @@ void main() { expect(provider.templateSupportsTools, isTrue); expect(provider.settings.toolsEnabled, isTrue); }, - // Native LiteRT-LM: on the Web the app keeps tools off (#919). + // On the Web the app needs the runtime's truncation report (#919). testOn: 'vm', ); @@ -1624,6 +1661,34 @@ void main() { expect(singlePassProvider.messages.last.text, 'It is sunny in Seoul.'); }); + test('does not run the tool calls of a reply cut off at the token ' + 'limit', () async { + final engine = _SinglePassToolCallEngine(callFinishReason: 'length'); + final cutOffProvider = ChatProvider( + chatService: MockChatService(engine: engine), + settingsService: mockSettingsService, + initialSettings: const ChatSettings(modelPath: 'test_model.gguf'), + ); + + await cutOffProvider.loadModel(); + cutOffProvider.updateToolsEnabled(true); + cutOffProvider.resetToolDeclarations(); + + await cutOffProvider.sendMessage('what time is it?'); + + expect(engine.createCallCount, 1); + expect( + cutOffProvider.messages.expand( + (m) => m.parts?.whereType() ?? const [], + ), + isEmpty, + ); + expect( + cutOffProvider.messages.last.text, + contains('reached the token limit, so its tool calls were not run'), + ); + }); + test( 'parses FunctionGemma tool-call text into structured tool parts', () async { @@ -2676,7 +2741,7 @@ void main() { class _MetadataEngine extends MockLlamaEngine { final Map metadata; - _MetadataEngine(this.metadata); + _MetadataEngine(this.metadata, {super.backend}); @override Future> getMetadata() async => metadata; @@ -2818,6 +2883,10 @@ class _ToolCaptureEngine extends MockLlamaEngine { } class _SinglePassToolCallEngine extends MockLlamaEngine { + _SinglePassToolCallEngine({this.callFinishReason}); + + /// The finish reason of the reply that carries the call. + final String? callFinishReason; int createCallCount = 0; @override @@ -2872,12 +2941,22 @@ class _SinglePassToolCallEngine extends MockLlamaEngine { ), ], ), + finishReason: callFinishReason, ), ], ); } } +/// A backend whose runtime reports, or cannot report, token-limit truncation. +class _LimitReportingBackend extends MockLlamaBackend + implements BackendGenerationLimitSupport { + _LimitReportingBackend(this.generationLimitUnsupportedReason); + + @override + final String? generationLimitUnsupportedReason; +} + class _ThinkingControlCaptureEngine extends MockLlamaEngine { GenerationParams? lastParams; bool? lastEnableThinking; diff --git a/lib/src/backends/litert_lm/litert_lm_backend_web.dart b/lib/src/backends/litert_lm/litert_lm_backend_web.dart index e49e5503f..b305c91a8 100644 --- a/lib/src/backends/litert_lm/litert_lm_backend_web.dart +++ b/lib/src/backends/litert_lm/litert_lm_backend_web.dart @@ -83,10 +83,15 @@ class LiteRtLmBackend final Expando> _conversationDeletes = Expando>(); final _LiteRtLmWebRuntimeToolCalls _runtimeToolCalls = _LiteRtLmWebRuntimeToolCalls(); + final _LiteRtLmWebGenerationLimits _generationLimits = + _LiteRtLmWebGenerationLimits(); LlamaLogLevel _logLevel = LlamaLogLevel.warn; bool _isReady = false; bool _supportsTextHistory = false; bool _supportsToolDeclarations = false; + // The context size the loaded engine's executor enforces, once the load + // probe showed its runtime reports per-turn decode and context token counts. + int? _reportedContextTokens; bool _hasContext = false; bool _cancelRequested = false; int _nextModelHandle = 1; @@ -118,6 +123,7 @@ class LiteRtLmBackend _readyTimeout = readyTimeout ?? _engineReadyTimeout, _preferredBackend = _normalizeBackendOverride(preferredBackend) { registerRuntimeToolCallReporter(this, _runtimeToolCalls); + registerGenerationLimitReporter(this, _generationLimits); } /// Creates a backend with ordered system/user/assistant text history. @@ -126,9 +132,13 @@ class LiteRtLmBackend /// The final message must be user text or tool results. Tools are declared /// through `preface.tools` when the loaded runtime reads it, which /// `supportsToolCalling` reports; the model's calls come back as - /// [LlamaToolCallContent]. Automatic tool loops stay unavailable because - /// the runtime reports no termination cause. `ToolChoice.required`, parallel - /// tool calls, media and template/thinking controls throw + /// [LlamaToolCallContent]. A load probe checks that the runtime reports + /// each turn's decode and context token counts; a reply that reaches + /// `maxTokens` or fills the context then ends with finish reason `length`, + /// and automatic tool loops run. A reply whose end-of-turn token is its + /// `maxTokens`-th token also ends with `length`: the runtime does not say + /// which of the two ended it. `ToolChoice.required`, parallel tool calls, + /// media and template/thinking controls throw /// [LlamaUnsupportedException]. The original constructor's /// subclass dispatch contract remains unchanged. Session budgets use a /// full-transcript UTF-8 estimate; exact JS tokenization is unavailable. @@ -147,11 +157,23 @@ class LiteRtLmBackend bool get _textHistoryEnabled => false; + /// Null once a [LiteRtLmBackend.withTextHistory] load has shown that its + /// runtime reports each turn's decode and context token counts; otherwise, + /// and before a load, why automatic tool loops cannot run. @override - String? get generationLimitUnsupportedReason => - 'LiteRT-LM Web @litert-lm/core@0.19.0 does not expose a reliable generation termination reason. ' - 'Automatic tool loops require a qualified Web runtime with token-limit reporting; ' - 'use ChatSession.create or LlamaEngine.create for manual completion.'; + String? get generationLimitUnsupportedReason => !_textHistoryEnabled + ? 'LiteRT-LM Web reports token-limit truncation only through ' + 'LlamaBackend.withTextHistory() or LiteRtLmBackend.withTextHistory(). ' + 'Use ChatSession.create or LlamaEngine.create for manual completion.' + : _isReady && _reportedContextTokens != null + ? null + : 'The loaded LiteRT-LM Web runtime did not report the decode and ' + 'context token counts of a turn (benchmarkEnabled, ' + 'getBenchmarkInfo and getTokenCount) and the context size its ' + 'executor enforces, so a reply cut off at maxTokens or the ' + 'context size cannot be told from a finished one. ' + '@litert-lm/core@0.19.0 reports them. Use ChatSession.create or ' + 'LlamaEngine.create for manual completion.'; @override bool get isReady => _isReady; @@ -263,6 +285,9 @@ class LiteRtLmBackend _textHistoryEnabled && await _probeTextHistory(_engine!); _supportsToolDeclarations = _supportsTextHistory && await _probeToolDeclarations(_engine!); + _reportedContextTokens = _supportsTextHistory + ? await _probeGenerationLimits(_engine!) + : null; _modelHandle = _nextModelHandle++; _isReady = true; onProgress?.call(1); @@ -271,6 +296,7 @@ class LiteRtLmBackend _isReady = false; _supportsTextHistory = false; _supportsToolDeclarations = false; + _reportedContextTokens = null; _modelHandle = null; _contextHandle = null; _modelUrl = null; @@ -382,6 +408,7 @@ class LiteRtLmBackend run.toolCalls, ); } + _generationLimits.limits[stream] = run.limit; _finishRun(run); unawaited(controller.close()); }, @@ -470,6 +497,16 @@ class LiteRtLmBackend } yield chunk; } + final contextTokens = _reportedContextTokens; + if (!_cancelRequested && contextTokens != null) { + final limit = await _generationLimitOf( + conversation, + maxTokens: params.maxTokens, + contextTokens: contextTokens, + ); + // A cancel or stop sequence wins over a limit reached meanwhile. + if (!_cancelRequested) run.limit = limit; + } } finally { if (identical(_activeConversation, conversation)) { _activeConversation = null; @@ -801,6 +838,10 @@ class LiteRtLmBackend final executorSettings = JSObject(); executorSettings.setProperty('maxNumTokens'.toJS, params.contextSize.toJS); settings.setProperty('mainExecutorSettings'.toJS, executorSettings); + // Per-turn decode token counts come only from the benchmark record. + if (_textHistoryEnabled) { + settings.setProperty('benchmarkEnabled'.toJS, true.toJS); + } return settings; } @@ -928,6 +969,182 @@ class LiteRtLmBackend } } + /// The context size [engine]'s executor enforces, when its runtime reports + /// the decode and context token counts of a turn and names that size; else + /// null. + Future _probeGenerationLimits(_LiteRtLmWebEngine engine) async { + final resolved = _resolvedContextTokens(engine); + if (resolved == null) return null; + final total = await _probeOneTokenTurn(engine); + if (total == null) return null; + final contextTokens = await _probeExecutorContextTokens(engine, resolved); + return contextTokens != null && total < contextTokens + ? contextTokens + : null; + } + + /// The tokens a one-token turn leaves in its conversation, or null when the + /// runtime does not count that turn. + /// + /// At `maxOutputTokens` 1 a turn decodes exactly one token, so a runtime + /// that keeps no benchmark record or counts another turn fails. + Future _probeOneTokenTurn(_LiteRtLmWebEngine engine) async { + _LiteRtLmWebConversation? conversation; + try { + conversation = await engine + .createConversation( + _createConversationConfig(const GenerationParams(maxTokens: 1)), + ) + .toDart; + if (!conversation.has('getBenchmarkInfo') || + !conversation.has('getTokenCount')) { + return null; + } + final reader = conversation.sendMessageStreaming('Hi'.toJS).getReader(); + while (!(await reader.read().toDart).done) {} + final counts = await _tokenCounts(conversation); + return counts != null && counts.decoded == 1 ? counts.total : null; + } catch (_) { + return null; + } finally { + if (conversation != null) await _deleteConversation(conversation); + } + } + + static final RegExp _inputTooLong = RegExp( + r'^Input token ids are too long\. Exceeding the maximum number of ' + r'tokens allowed: (\d+) >= (\d+)$', + ); + + /// The `maxNumTokens` [engine]'s executor enforces, from its rejection of a + /// prompt longer than [resolved] tokens, or null. + /// + /// `engine.settings` repeats the requested size, but an executor with a + /// fixed KV cache clamps its own copy to the cache, and decoding stops at + /// that copy. Prefill rejects an input of at least that many tokens before + /// running the model and names the limit. Tokenizers give digits a token + /// each or per three (Gemma, Qwen, Llama 3); one that merges more lets the + /// prompt through, which costs a long prefill and fails the probe. + Future _probeExecutorContextTokens( + _LiteRtLmWebEngine engine, + int resolved, + ) async { + _LiteRtLmWebConversation? conversation; + try { + conversation = await engine + .createConversation( + _createConversationConfig(const GenerationParams(maxTokens: 1)), + ) + .toDart; + // Varied digits, which tokenizers merge least. + final digits = StringBuffer(); + var seed = 1; + for (var i = 0; i < resolved * 4 + 64; i++) { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + digits.write(seed % 10); + } + final reader = conversation + .sendMessageStreaming(digits.toString().toJS) + .getReader(); + try { + while (!(await reader.read().toDart).done) {} + } catch (error) { + final match = _inputTooLong.firstMatch(_errorMessage(error) ?? ''); + if (match == null) return null; + final input = int.parse(match[1]!); + final limit = int.parse(match[2]!); + return limit > 1 && input >= limit ? limit : null; + } + return null; + } catch (_) { + return null; + } finally { + if (conversation != null) await _deleteConversation(conversation); + } + } + + static String? _errorMessage(Object error) { + try { + final message = (error as JSObject).getProperty('message'.toJS); + return message.isA() ? (message as JSString).toDart : null; + } catch (_) { + return null; + } + } + + /// The `maxNumTokens` [engine] resolved at creation: the requested size, + /// which bounds the executor's. + int? _resolvedContextTokens(_LiteRtLmWebEngine engine) { + try { + final settings = engine.getProperty('settings'.toJS); + if (settings == null || !settings.isA()) return null; + final executor = (settings as JSObject).getProperty( + 'mainExecutorSettings'.toJS, + ); + if (executor == null || !executor.isA()) return null; + return _positiveInt( + (executor as JSObject).getProperty('maxNumTokens'.toJS), + ); + } catch (_) { + return null; + } + } + + /// Why the turn [conversation] just finished ended, from its token counts. + /// + /// `@litert-lm/core@0.19.0` ends a turn at a stop token, once its decode + /// steps reach `maxOutputTokens`, or once the conversation's tokens reach + /// the executor's `maxNumTokens` ([contextTokens]), and reports none of + /// these causes. Fewer decode steps than [maxTokens] and fewer tokens than + /// [contextTokens] rule both budgets out, so only then is the turn + /// finished. A turn at a budget is cut off even if its last token was a + /// stop token: the counts cannot tell the two apart. + Future _generationLimitOf( + _LiteRtLmWebConversation conversation, { + required int maxTokens, + required int contextTokens, + }) async { + final counts = await _tokenCounts(conversation); + return counts == null + ? BackendGenerationLimit.runtime + : counts.total >= contextTokens + ? BackendGenerationLimit.contextSize + : counts.decoded >= maxTokens + ? BackendGenerationLimit.maxTokens + : null; + } + + /// The tokens [conversation]'s last turn decoded and the tokens it holds, + /// or null when the runtime does not report them consistently. + Future<({int decoded, int total})?> _tokenCounts( + _LiteRtLmWebConversation conversation, + ) async { + try { + final info = await conversation.getBenchmarkInfo().toDart; + final decoded = info != null && info.isA() + ? _positiveInt( + (info as JSObject).getProperty( + 'lastDecodeTokenCount'.toJS, + ), + ) + : null; + final total = _positiveInt(await conversation.getTokenCount().toDart); + // A turn prefills at least one token before it decodes. + if (decoded == null || total == null || total <= decoded) return null; + return (decoded: decoded, total: total); + } catch (_) { + return null; + } + } + + static int? _positiveInt(JSAny? value) { + if (value == null || !value.isA()) return null; + final number = (value as JSNumber).toDartDouble; + return number.isFinite && number >= 1 && number == number.truncate() + ? number.toInt() + : null; + } + _LiteRtLmWebEngine _requireEngine() { final engine = _engine; if (engine == null || !_isReady) { @@ -1219,6 +1436,7 @@ class LiteRtLmBackend _isReady = false; _supportsTextHistory = false; _supportsToolDeclarations = false; + _reportedContextTokens = null; _hasContext = false; _modelHandle = null; _contextHandle = null; @@ -1875,6 +2093,10 @@ final class _LiteRtLmWebRun { /// The runtime-parsed tool calls so far, in order. final List toolCalls = []; + /// The budget that ended this run, or null when it finished, was cancelled + /// or stopped at a stop sequence. + BackendGenerationLimit? limit; + /// Completes with true when a queued run may start, or false when it ends /// without starting. final Completer admission = Completer(); @@ -1891,6 +2113,17 @@ final class _LiteRtLmWebRuntimeToolCalls implements BackendRuntimeToolCalls { ) => calls[generation]; } +/// The token budget that ended each finished generation stream. +final class _LiteRtLmWebGenerationLimits + implements BackendGenerationLimitReporting { + final Expando limits = + Expando(); + + @override + BackendGenerationLimit? generationLimitOf(Stream> generation) => + limits[generation]; +} + @JS() extension type _LiteRtLmConsoleGuard._(JSObject _) implements JSObject { external void restore(); @@ -1917,6 +2150,10 @@ extension type _LiteRtLmWebConversation._(JSObject _) implements JSObject { external void cancel(); + external JSPromise getBenchmarkInfo(); + + external JSPromise getTokenCount(); + @JS('delete') external JSPromise? deleteConversation(); } diff --git a/lib/src/backends/web/web_backend.dart b/lib/src/backends/web/web_backend.dart index a7b10858f..877f0d8d9 100644 --- a/lib/src/backends/web/web_backend.dart +++ b/lib/src/backends/web/web_backend.dart @@ -661,14 +661,8 @@ class WebAutoBackend } @override - BackendGenerationLimit? generationLimitOf(Stream> generation) { - final delegate = _delegate; - return delegate is BackendGenerationLimitReporting - ? (delegate as BackendGenerationLimitReporting).generationLimitOf( - generation, - ) - : null; - } + BackendGenerationLimit? generationLimitOf(Stream> generation) => + generationLimitReporterOf(_delegate)?.generationLimitOf(generation); @override List? runtimeToolCallsOf( diff --git a/packages/llamadart_validation/assets/capability_coverage.json b/packages/llamadart_validation/assets/capability_coverage.json index c7aa9aa6d..a04baf36a 100644 --- a/packages/llamadart_validation/assets/capability_coverage.json +++ b/packages/llamadart_validation/assets/capability_coverage.json @@ -277,7 +277,7 @@ ], "exemption": { "id": "automatic-tool-loops", - "reason": "Reliable runtime termination and automatic-loop rollback, including native LiteRT-LM finish reasons, need their own validation contract; the litert-lm-chat-features-smoke local check covers the LiteRT-LM cutoff. Ordinary best-effort tool-call cases are insufficient.", + "reason": "Reliable runtime termination and automatic-loop rollback, including native LiteRT-LM finish reasons and LiteRT-LM Web limits inferred from @litert-lm/core@0.19.0 token counts, need their own validation contract; the litert-lm-chat-features-smoke local check covers the native LiteRT-LM cutoff, and production-path Chrome tests plus the litert-lm-web-truncation local runner (direct-runtime token counts at the maxTokens boundary and a filled context, completed and truncated loops) cover LiteRT-LM Web. Ordinary best-effort tool-call cases are insufficient.", "issue": "https://github.com/leehack/llamadart/issues/919" } }, @@ -594,7 +594,7 @@ ], "exemption": { "issue": "https://github.com/leehack/llamadart/issues/1196", - "reason": "The row's native and WebGPU columns are the tools pack's routes (bound through capability:supportsToolCalling); its LiteRT-LM Web column has no versioned Web validation profile. That column (manual tool calling, #1790) is covered by production-path Chrome tests of the preface.tools probe, declaration/call/result wire shapes, runtime tool_calls carried beside text in either order, typed refusals and cancel/reset, and by the maintained litert-lm-web-tool-calling local runner, which compares a pinned @litert-lm/core@0.19.0 reference and a no-tools control on an identified browser/model. Automatic loops stay out of scope (#919). No model qualification is inferred.", + "reason": "The row's native and WebGPU columns are the tools pack's routes (bound through capability:supportsToolCalling); its LiteRT-LM Web column has no versioned Web validation profile. That column (manual tool calling, #1790) is covered by production-path Chrome tests of the preface.tools probe, declaration/call/result wire shapes, runtime tool_calls carried beside text in either order, typed refusals and cancel/reset, and by the maintained litert-lm-web-tool-calling local runner, which compares a pinned @litert-lm/core@0.19.0 reference and a no-tools control on an identified browser/model. Automatic loops and truncation are covered by the automatic-tool-loops exemption (#919). No model qualification is inferred.", "id": "litert-web-tool-calling-profile" } }, diff --git a/skills/llamadart-chat-streaming/SKILL.md b/skills/llamadart-chat-streaming/SKILL.md index d1e21a9ae..76bc93b32 100644 --- a/skills/llamadart-chat-streaming/SKILL.md +++ b/skills/llamadart-chat-streaming/SKILL.md @@ -25,8 +25,7 @@ modalities and speculative strategies before offering them. or append it to history. `completion.message`, sessions and automatic loops exclude diagnostics. All executable calls remain withheld at length. Natural EOF/cancellation expose no diagnostics and retain existing policy; - none/parsing-disabled output stays literal. This does not resolve LiteRT-LM - Web's unknown finish cause (#919). + none/parsing-disabled output stays literal. - Pick the entry point by who owns history: - `ChatSession.create(parts)` for multi-turn chat. It applies the system diff --git a/skills/llamadart-tool-calling/SKILL.md b/skills/llamadart-tool-calling/SKILL.md index f04fffdd5..f98848ccd 100644 --- a/skills/llamadart-tool-calling/SKILL.md +++ b/skills/llamadart-tool-calling/SKILL.md @@ -20,8 +20,7 @@ description: >- or append it to history. `completion.message`, sessions and automatic loops exclude diagnostics. All executable calls remain withheld at length. Natural EOF/cancellation expose no diagnostics and retain existing policy; - none/parsing-disabled output stays literal. This does not resolve LiteRT-LM - Web's unknown finish cause (#919). + none/parsing-disabled output stays literal. - Prefer `session.sendWithTools(text, tools: ..., maxRounds: ...)`: it runs each call's `ToolDefinition.handler` (concurrently for parallel calls), @@ -212,16 +211,20 @@ description: >- - Automatic `sendWithTools` and `completeWithTools` loops need a runtime that reports why generation stopped; a reply cut off at `maxTokens` returns `LlamaToolLoopStopReason.truncated` and runs no tools. Native LiteRT-LM - reports it from litert-lm-native `v0.18.0-3` (the default pin does). Older - native runtimes and Web `@litert-lm/core@0.19.0` throw - `LlamaUnsupportedException` before generation or history mutation; manual + reports it from litert-lm-native `v0.18.0-3` (the default pin does). + LiteRT-LM Web infers it from `@litert-lm/core@0.19.0` token counts through + `LlamaBackend.withTextHistory()` once a load probe passes; a reply ending + exactly at `maxTokens` also counts as truncated, so leave headroom. Older + native runtimes, Web runtimes that fail the probe and the default Web + constructors throw `LlamaUnsupportedException` before generation or history + mutation; manual `ChatSession.create`/`LlamaEngine.create` still work there, but their `stop` does not prove EOS. Do not infer truncation from output length or run tool handlers automatically from an unverified terminal result. - Runtime limits: LiteRT-LM has no grammar enforcement, LiteRT-LM on web - forwards tools only through `LlamaBackend.withTextHistory()` (manual - `create` calls; `ToolChoice.required`, `parallelToolCalls` and tool-result - `content` throw), and WebGPU `ToolChoice.auto` parses calls best-effort. + forwards tools only through `LlamaBackend.withTextHistory()` + (`ToolChoice.required`, `parallelToolCalls` and tool-result `content` + throw), and WebGPU `ToolChoice.auto` parses calls best-effort. `(await engine.capabilities).supportsToolCalling`, `supportsStructuredOutput` and `supportsLazyGrammar` report these per loaded model. Test tool flows on every target runtime. diff --git a/skills/llamadart-web/SKILL.md b/skills/llamadart-web/SKILL.md index 4741706cc..463e0b6e9 100644 --- a/skills/llamadart-web/SKILL.md +++ b/skills/llamadart-web/SKILL.md @@ -154,9 +154,11 @@ in the llamadart-getting-started and llamadart-chat-streaming skills. text and manual tool calling: `create` returns the runtime's tool calls, and you add a tool result message per call before the next `create`. `supportsMultiTurnChat` and `supportsToolCalling` report what the loaded - runtime forwards. Automatic tool loops (`sendWithTools`), `ToolChoice.required` - and `parallelToolCalls` still throw, because the runtime reports no - truncation. + runtime forwards. A reply cut off at `maxTokens` or the context ends with + `length` (inferred from the runtime's token counts, after a load probe), so + `sendWithTools` runs and returns `truncated` for a cut-off reply; a reply + ending exactly at `maxTokens` also counts as cut off. `ToolChoice.required` + and `parallelToolCalls` still throw. It rejects media parts, grammar, `penalty`, `minP`, `presencePenalty`, `thinkingBudget` and speculative decoding; generation honors only `maxTokens`, `temp`, `topK`, `topP`, `seed` and `stopSequences`. It has no diff --git a/test/e2e/backends/litert_lm_truncation_web_e2e_test.dart b/test/e2e/backends/litert_lm_truncation_web_e2e_test.dart new file mode 100644 index 000000000..517dff568 --- /dev/null +++ b/test/e2e/backends/litert_lm_truncation_web_e2e_test.dart @@ -0,0 +1,487 @@ +@TestOn('browser') +@Tags(['local-only', 'e2e']) +@Timeout(Duration(minutes: 30)) +library; + +import 'dart:async'; +import 'dart:convert'; +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:llamadart/backend.dart' as spi; +import 'package:llamadart/llamadart.dart'; +import 'package:llamadart/src/backends/backend.dart' as internal; +import 'package:llamadart/src/backends/litert_lm/litert_lm_backend_web.dart'; +import 'package:llamadart/src/core/engine/engine.dart'; +import 'package:test/test.dart'; +import 'package:web/web.dart'; + +typedef _Turn = ({String text, int decoded, int total, String? error}); + +// The maintained runner supplies only an existing local file, never downloads +// model weights, and hashes that file before serving it with byte ranges. +void main() { + test('Web token-limit reports match the published runtime token counts', () async { + const moduleUrl = + 'https://cdn.jsdelivr.net/npm/@litert-lm/core@0.19.0/+esm'; + final manifestResponse = await window + .fetch('http://127.0.0.1:5198/manifest.json'.toJS) + .toDart; + final manifest = + jsonDecode((await manifestResponse.text().toDart).toDart) + as Map; + final model = manifest['model'] as String; + final device = manifest['backend'] == 'cpu' + ? ComputeDevice.cpu + : ComputeDevice.gpu; + const callback = '__llamadartTruncationReferenceLoaded'; + final loaded = Completer(); + globalContext.setProperty( + callback.toJS, + ((JSAny? error) { + if (error == null) { + loaded.complete(); + } else { + loaded.completeError(error); + } + }).toJS, + ); + final script = HTMLScriptElement() + ..type = 'module' + ..text = + "import('$moduleUrl').then(m => { window.LiteRtLmEngine = m.Engine; window.$callback(null); }).catch(e => window.$callback(String(e)));"; + document.head!.append(script); + addTearDown(() { + script.remove(); + globalContext.delete(callback.toJS); + }); + await loaded.future.timeout(const Duration(seconds: 60)); + final constructor = globalContext.getProperty( + 'LiteRtLmEngine'.toJS, + ); + + const contextSize = 1024; + const shortPrompt = + 'Name the first five planets from the Sun, separated by commas.'; + const longPrompt = + 'Write every whole number from one to two thousand in English words, ' + 'separated by commas. Do not stop early.'; + const longBudget = 4096; + print( + 'LITERT_TRUNCATION_IDENTITY ${jsonEncode({...manifest, 'module': moduleUrl, 'browser': window.navigator.userAgent})}', + ); + + // The published runtime alone, with the benchmark record the adapter + // enables: every turn's decode steps and the conversation's tokens. + final direct = await constructor + .callMethod>( + 'create'.toJS, + { + 'model': model, + // GPU keeps the runtime default, as the adapter does. + if (device == ComputeDevice.cpu) 'backend': 3, + 'benchmarkEnabled': true, + 'mainExecutorSettings': {'maxNumTokens': contextSize}, + }.jsify(), + ) + .toDart; + final settings = direct.getProperty('settings'.toJS); + final directBackend = settings + .getProperty('backend'.toJS) + .toDartInt; + final resolvedContext = settings + .getProperty('mainExecutorSettings'.toJS) + .getProperty('maxNumTokens'.toJS) + .toDartInt; + Future<_Turn> reference(String prompt, int budget) async { + final conversation = await direct + .callMethod>( + 'createConversation'.toJS, + { + 'sessionConfig': { + 'maxOutputTokens': budget, + 'samplerBackend': directBackend, + 'samplerParams': {'k': 1, 'p': 1, 'temperature': 0, 'seed': 42}, + }, + }.jsify(), + ) + .toDart; + final text = StringBuffer(); + String? error; + try { + final reader = conversation + .callMethod('sendMessageStreaming'.toJS, prompt.toJS) + .callMethod('getReader'.toJS); + try { + while (true) { + final result = await reader + .callMethod>('read'.toJS) + .toDart; + if (result.getProperty('done'.toJS).toDart) break; + final chunk = + (result.getProperty('value'.toJS).dartify() as Map) + .cast(); + // Text and reasoning alike: a cut can fall in either channel. + void write(Object? value, [String? key]) => switch (value) { + final String leaf when key != 'role' && key != 'type' => + text.write(leaf), + final Map map => map.forEach( + (key, value) => write(value, '$key'), + ), + final List list => list.forEach(write), + _ => null, + }; + write(chunk); + } + } catch (e) { + error = '$e'; + } finally { + reader.callMethod('releaseLock'.toJS); + } + final info = await conversation + .callMethod>('getBenchmarkInfo'.toJS) + .toDart; + final total = await conversation + .callMethod>('getTokenCount'.toJS) + .toDart; + return ( + text: '$text', + decoded: info + .getProperty('lastDecodeTokenCount'.toJS) + .toDartInt, + total: total.toDartInt, + error: error, + ); + } finally { + await conversation.callMethod>('delete'.toJS).toDart; + } + } + + Map describe(_Turn turn) => { + 'decoded': turn.decoded, + 'total': turn.total, + 'textChars': turn.text.length, + 'tail': turn.text.substring( + turn.text.length < 80 ? 0 : turn.text.length - 80, + ), + 'error': turn.error, + }; + + final natural = await reference(shortPrompt, 512); + final steps = natural.decoded; + final atSteps = await reference(shortPrompt, steps); + final aboveSteps = await reference(shortPrompt, steps + 1); + final lastTextStep = await reference(shortPrompt, steps - 1); + final belowSteps = await reference(shortPrompt, steps - 2); + final filled = await reference(longPrompt, longBudget); + await direct.callMethod>('delete'.toJS).toDart; + print( + 'LITERT_TRUNCATION_DIRECT ${jsonEncode({ + 'execution': const {2: 'WebGPU_ARTISAN', 3: 'WASM CPU', 4: 'WebGPU'}[directBackend], + 'resolvedContext': resolvedContext, + 'natural': describe(natural), + 'atSteps': describe(atSteps), + 'aboveSteps': describe(aboveSteps), + 'lastTextStep': describe(lastTextStep), + 'belowSteps': describe(belowSteps), + 'filled': describe(filled), + })}', + ); + expect(resolvedContext, contextSize); + // A natural stop decodes its stop token as one more step, which emits no + // text: the count stays under a budget above it and reaches a budget + // equal to it. One step fewer ends at the budget before the stop token + // with the same text; two fewer cut the text. + expect(natural.error, isNull); + expect(steps, inInclusiveRange(3, 511)); + expect(natural.total, lessThan(contextSize)); + expect(aboveSteps, natural); + expect(atSteps, natural); + expect(lastTextStep.decoded, steps - 1); + expect(lastTextStep.text, natural.text); + expect(belowSteps.decoded, steps - 2); + expect(belowSteps.error, isNull); + expect(natural.text, startsWith(belowSteps.text)); + expect(belowSteps.text, isNot(natural.text)); + // A turn that fills the context ends with every context token used and + // fewer decode steps than its budget. + expect(filled.decoded, lessThan(longBudget)); + expect(filled.total, greaterThanOrEqualTo(contextSize)); + + final backend = LiteRtLmBackend.withTextHistory(moduleUrl: moduleUrl); + final engine = LlamaEngine(backend); + addTearDown(engine.dispose); + expect( + (backend as spi.BackendGenerationLimitSupport) + .generationLimitUnsupportedReason, + isNotNull, + ); + await engine.loadModelFromUrl( + model, + modelParams: ModelParams(contextSize: contextSize, device: device), + ); + expect( + (backend as spi.BackendGenerationLimitSupport) + .generationLimitUnsupportedReason, + isNull, + ); + + GenerationParams greedy(int maxTokens) => GenerationParams( + maxTokens: maxTokens, + temp: 0, + topK: 1, + topP: 1, + seed: 42, + ); + Future< + ({ + String text, + String? reason, + internal.BackendGenerationLimit? limit, + String? error, + }) + > + ask(String prompt, int maxTokens) async { + final chunks = []; + try { + await engine + .create([ + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: prompt), + ], params: greedy(maxTokens)) + .forEach(chunks.add); + } catch (e) { + return (text: '', reason: null, limit: null, error: '$e'); + } + return ( + text: chunks + .map((chunk) => chunk.choices.firstOrNull?.delta.content ?? '') + .join(), + reason: chunks.last.choices.single.finishReason, + limit: completionGenerationLimit(chunks.last), + error: null, + ); + } + + final adapterNatural = await ask(shortPrompt, 512); + final adapterAbove = await ask(shortPrompt, steps + 1); + final adapterAt = await ask(shortPrompt, steps); + final adapterLastText = await ask(shortPrompt, steps - 1); + final adapterBelow = await ask(shortPrompt, steps - 2); + final adapterFilled = await ask(longPrompt, longBudget); + + const weatherQuestion = 'What is the weather in Paris right now?'; + const forecast = { + 'city': 'Paris', + 'condition': 'violet hail', + 'temp_c': -7, + }; + var toolRuns = 0; + final weather = ToolDefinition( + name: 'get_weather', + description: 'Returns the current weather for a city.', + parameters: [ + ToolParam.string('city', description: 'City name', required: true), + ], + handler: (_) async { + toolRuns++; + return forecast; + }, + ); + const system = + 'You are a weather assistant. Call get_weather for every weather ' + 'question, then answer from its result.'; + final loopSession = ChatSession( + engine, + maxContextTokens: 0, + systemPrompt: system, + ); + final completed = await loopSession.completeWithTools( + const [LlamaTextContent(weatherQuestion)], + tools: [weather], + params: greedy(512), + ); + final completedRuns = toolRuns; + final truncatedSession = ChatSession( + engine, + maxContextTokens: 0, + systemPrompt: system, + ); + final truncated = await truncatedSession.completeWithTools( + const [LlamaTextContent(weatherQuestion)], + tools: [weather], + params: greedy(3), + ); + + print( + 'LITERT_TRUNCATION_ADAPTER ${jsonEncode({ + for (final (name, reply) in [('natural', adapterNatural), ('aboveSteps', adapterAbove), ('atSteps', adapterAt), ('lastTextStep', adapterLastText), ('belowSteps', adapterBelow), ('filled', adapterFilled)]) name: {'finishReason': reply.reason, 'limit': reply.limit?.name, 'textChars': reply.text.length, 'error': reply.error}, + 'loop': {'stopReason': completed.stopReason.name, 'rounds': completed.rounds, 'toolRuns': completedRuns, 'answer': completed.completion.text}, + 'truncatedLoop': {'stopReason': truncated.stopReason.name, 'toolRuns': toolRuns - completedRuns, 'rolledBack': truncated.rolledBack}, + })}', + ); + + expect(adapterNatural.reason, 'stop'); + expect(adapterNatural.limit, isNull); + // The direct text carries the reasoning and the answer. + expect(adapterNatural.text.trim(), isNotEmpty); + expect(natural.text, contains(adapterNatural.text.trim())); + expect(adapterAbove.reason, 'stop'); + expect(adapterAbove.limit, isNull); + // Documented conservative report: the runtime does not say whether the + // last step at the budget was the stop token. + expect(adapterAt.reason, 'length'); + expect(adapterAt.limit, internal.BackendGenerationLimit.maxTokens); + expect(adapterLastText.reason, 'length'); + expect(adapterLastText.limit, internal.BackendGenerationLimit.maxTokens); + expect(adapterBelow.reason, 'length'); + expect(adapterBelow.limit, internal.BackendGenerationLimit.maxTokens); + expect(adapterFilled.error, isNull); + expect(adapterFilled.reason, 'length'); + expect(adapterFilled.limit, internal.BackendGenerationLimit.contextSize); + + expect(completed.stopReason, LlamaToolLoopStopReason.completed); + expect(completedRuns, greaterThan(0)); + expect( + completed.completion.text.toLowerCase().contains('violet') || + completed.completion.text.contains('-7'), + isTrue, + reason: completed.completion.text, + ); + expect(truncated.stopReason, LlamaToolLoopStopReason.truncated); + expect(toolRuns, completedRuns); + expect(truncated.rolledBack, isTrue); + expect(truncatedSession.history, isEmpty); + + // A context above a fixed KV cache: the executor clamps its own limit + // while engine.settings repeats the request, and decoding stops at the + // executor's limit. + await engine.dispose(); + const largeContext = 65536; + const largeBudget = 8192; + final large = await constructor + .callMethod>( + 'create'.toJS, + { + 'model': model, + if (device == ComputeDevice.cpu) 'backend': 3, + 'benchmarkEnabled': true, + 'mainExecutorSettings': {'maxNumTokens': largeContext}, + }.jsify(), + ) + .toDart; + final largeSettings = large + .getProperty('settings'.toJS) + .getProperty('mainExecutorSettings'.toJS) + .getProperty('maxNumTokens'.toJS) + .toDartInt; + // The executor names its limit when it rejects an over-long input. + final overLong = await large + .callMethod>( + 'createConversation'.toJS, + { + 'sessionConfig': {'maxOutputTokens': 1}, + }.jsify(), + ) + .toDart; + String? rejection; + try { + final reader = overLong + .callMethod( + 'sendMessageStreaming'.toJS, + List.filled(largeContext * 4, '7').join().toJS, + ) + .callMethod('getReader'.toJS); + while (!(await reader.callMethod>('read'.toJS).toDart) + .getProperty('done'.toJS) + .toDart) {} + } catch (e) { + rejection = '$e'; + } finally { + await overLong.callMethod>('delete'.toJS).toDart; + } + final executorContext = int.parse( + RegExp(r'>= (\d+)$').firstMatch(rejection ?? '')![1]!, + ); + final directLarge = await (() async { + final conversation = await large + .callMethod>( + 'createConversation'.toJS, + { + 'sessionConfig': { + 'maxOutputTokens': largeBudget, + 'samplerBackend': directBackend, + 'samplerParams': {'k': 1, 'p': 1, 'temperature': 0, 'seed': 42}, + }, + }.jsify(), + ) + .toDart; + try { + final reader = conversation + .callMethod('sendMessageStreaming'.toJS, longPrompt.toJS) + .callMethod('getReader'.toJS); + while (!(await reader + .callMethod>('read'.toJS) + .toDart) + .getProperty('done'.toJS) + .toDart) {} + final info = await conversation + .callMethod>('getBenchmarkInfo'.toJS) + .toDart; + final total = await conversation + .callMethod>('getTokenCount'.toJS) + .toDart; + return ( + decoded: info + .getProperty('lastDecodeTokenCount'.toJS) + .toDartInt, + total: total.toDartInt, + ); + } finally { + await conversation.callMethod>('delete'.toJS).toDart; + } + })(); + await large.callMethod>('delete'.toJS).toDart; + + final largeBackend = LiteRtLmBackend.withTextHistory(moduleUrl: moduleUrl); + final largeEngine = LlamaEngine(largeBackend); + addTearDown(largeEngine.dispose); + await largeEngine.loadModelFromUrl( + model, + modelParams: ModelParams(contextSize: largeContext, device: device), + ); + final largeReason = (largeBackend as spi.BackendGenerationLimitSupport) + .generationLimitUnsupportedReason; + final largeChunks = await largeEngine.create(const [ + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: longPrompt), + ], params: greedy(largeBudget)).toList(); + final largeLast = largeChunks.last; + print( + 'LITERT_TRUNCATION_LARGE_CONTEXT ${jsonEncode({ + 'requested': largeContext, + 'settings': largeSettings, + 'executor': executorContext, + 'direct': {'decoded': directLarge.decoded, 'total': directLarge.total}, + 'adapterReason': largeReason, + 'finishReason': largeLast.choices.single.finishReason, + 'limit': completionGenerationLimit(largeLast)?.name, + })}', + ); + expect(largeSettings, largeContext); + expect(executorContext, lessThanOrEqualTo(largeContext)); + // The turn ended at a budget: the executor's context or maxTokens. + expect( + directLarge.total >= executorContext || + directLarge.decoded >= largeBudget, + isTrue, + ); + expect(largeReason, isNull); + expect(largeLast.choices.single.finishReason, 'length'); + expect( + completionGenerationLimit(largeLast), + directLarge.total >= executorContext + ? internal.BackendGenerationLimit.contextSize + : internal.BackendGenerationLimit.maxTokens, + ); + print('LITERT_TRUNCATION_RESULT PASS'); + }); +} diff --git a/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart b/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart index 7b1f889bf..3a915c873 100644 --- a/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_backend_web_test.dart @@ -8,6 +8,7 @@ import 'dart:js_interop_unsafe'; import 'package:llamadart/llamadart.dart' as api; import 'package:llamadart/backend.dart' as spi; +import 'package:llamadart/src/backends/backend.dart' as internal; import 'package:llamadart/src/backends/litert_lm/litert_lm_backend_web.dart'; import 'package:llamadart/src/backends/web/web_backend.dart'; import 'package:llamadart/src/core/engine/engine.dart'; @@ -1239,50 +1240,48 @@ void main() { expect(prompts, 0); }); - test( - 'automatic tool loops stay refused while tools are supported', - () async { - var prompts = 0; - var toolRuns = 0; - _installFakeEngine( - textHistory: true, - toolDeclarations: true, - chunks: [ - _toolCallChunk([ - ('get_weather', {'city': 'Paris'}), - ]), - ], - onPrompt: (_) => prompts++, - ); - final engine = LlamaEngine(spi.LlamaBackend.withTextHistory()); - addTearDown(engine.dispose); - await engine.loadModelFromUrl('model.litertlm'); - expect((await engine.capabilities).supportsToolCalling, isTrue); - final session = api.ChatSession(engine, maxContextTokens: 0); - final handled = api.ToolDefinition( - name: 'get_weather', - description: 'Weather for a city', - parameters: [api.ToolParam.string('city', required: true)], - handler: (_) async { - toolRuns++; - return 'sunny'; - }, - ); - await expectLater( - session.sendWithTools('Weather in Paris?', tools: [handled]), - throwsA( - isA().having( - (error) => error.message, - 'diagnostic', - contains('@0.19.0'), - ), + test('automatic tool loops stay refused while tools are supported but the ' + 'runtime reports no token counts', () async { + var prompts = 0; + var toolRuns = 0; + _installFakeEngine( + textHistory: true, + toolDeclarations: true, + chunks: [ + _toolCallChunk([ + ('get_weather', {'city': 'Paris'}), + ]), + ], + onPrompt: (_) => prompts++, + ); + final engine = LlamaEngine(spi.LlamaBackend.withTextHistory()); + addTearDown(engine.dispose); + await engine.loadModelFromUrl('model.litertlm'); + expect((await engine.capabilities).supportsToolCalling, isTrue); + final session = api.ChatSession(engine, maxContextTokens: 0); + final handled = api.ToolDefinition( + name: 'get_weather', + description: 'Weather for a city', + parameters: [api.ToolParam.string('city', required: true)], + handler: (_) async { + toolRuns++; + return 'sunny'; + }, + ); + await expectLater( + session.sendWithTools('Weather in Paris?', tools: [handled]), + throwsA( + isA().having( + (error) => error.message, + 'diagnostic', + contains('@0.19.0'), ), - ); - expect(prompts, 0); - expect(toolRuns, 0); - expect(session.history, isEmpty); - }, - ); + ), + ); + expect(prompts, 0); + expect(toolRuns, 0); + expect(session.history, isEmpty); + }); test('a cancelled tool request ends cleanly and the next request on a ' 'reset session declares tools again', () async { @@ -1323,6 +1322,435 @@ void main() { }); }); + group('token-limit reporting', () { + const params = api.GenerationParams(maxTokens: 8); + final weather = api.ToolDefinition( + name: 'get_weather', + description: 'Weather for a city', + parameters: [api.ToolParam.string('city', required: true)], + ); + + test('a text-history load enables the benchmark record and probes one ' + 'decoded token; the legacy constructor does neither', () async { + for (final textHistory in [false, true]) { + final fake = _installCountingFakeEngine( + counts: (_, budget) => (decoded: budget, total: 20), + ); + final backend = textHistory + ? LiteRtLmBackend.withTextHistory() + : LiteRtLmBackend(); + final support = backend as internal.BackendGenerationLimitSupport; + expect(support.generationLimitUnsupportedReason, isNotNull); + await backend.modelLoadFromUrl('model.litertlm', const ModelParams()); + expect( + fake.settings.single['benchmarkEnabled'], + textHistory ? isTrue : isNull, + ); + expect(fake.prompts, textHistory ? ['Hi'] : isEmpty); + expect(fake.budgets, textHistory ? [1] : isEmpty); + // The executor-limit probe's prompt exceeds four tokens per + // resolved context token. + expect(fake.rejectedLengths, textHistory ? [4096 * 4 + 64] : isEmpty); + expect(fake.deleted, fake.created); + expect( + support.generationLimitUnsupportedReason, + textHistory ? isNull : contains('withTextHistory()'), + ); + await backend.dispose(); + expect(support.generationLimitUnsupportedReason, isNotNull); + } + }); + + for (final (name, configure) in <(String, _CountingFake Function())>[ + ( + 'no token-count API', + () => _installCountingFakeEngine( + counts: (_, budget) => (decoded: budget, total: 20), + countsApi: false, + ), + ), + ( + 'no benchmark record', + () => _installCountingFakeEngine( + counts: (_, _) => (decoded: 0, total: 20), + ), + ), + ( + 'a decode count of more than the probe turn', + () => _installCountingFakeEngine( + counts: (turn, _) => (decoded: turn == 0 ? 2 : 1, total: 20), + ), + ), + ( + 'a context count without the prefill', + () => _installCountingFakeEngine( + counts: (_, _) => (decoded: 1, total: 1), + ), + ), + ( + 'a probe that fills the context', + () => _installCountingFakeEngine( + counts: (_, _) => (decoded: 1, total: 4096), + ), + ), + ( + 'no resolved context size', + () => _installCountingFakeEngine( + counts: (_, budget) => (decoded: budget, total: 20), + maxNumTokens: null, + ), + ), + ( + 'a failing count', + () => _installCountingFakeEngine(counts: (_, _) => null), + ), + ( + 'a failing one-token turn', + () => _installCountingFakeEngine( + counts: (_, budget) => (decoded: budget, total: 20), + reject: (prompt) => + prompt == 'Hi' ? 'Internal error' : _inputTooLong(prompt, 4096), + ), + ), + ( + 'an over-long prompt the runtime accepts', + () => _installCountingFakeEngine( + counts: (_, budget) => (decoded: budget, total: 20), + reject: (_) => null, + ), + ), + ( + 'a limit error in another format', + () => _installCountingFakeEngine( + counts: (_, budget) => (decoded: budget, total: 20), + reject: (prompt) => prompt.length > 100 + ? 'Input token ids are too long: ${prompt.length} >= 4096' + : null, + ), + ), + ( + 'a named limit above the rejected input', + () => _installCountingFakeEngine( + counts: (_, budget) => (decoded: budget, total: 20), + reject: (prompt) => prompt.length > 100 + ? 'Input token ids are too long. Exceeding the maximum number ' + 'of tokens allowed: 10 >= 4096' + : null, + ), + ), + ( + 'a limit probe whose send throws', + () => _installCountingFakeEngine( + counts: (_, budget) => (decoded: budget, total: 20), + throwOnSend: (prompt) => prompt.length > 100, + ), + ), + ( + 'a probe turn that fills the executor context', + () => _installCountingFakeEngine( + counts: (_, _) => (decoded: 1, total: 20), + executorTokens: 20, + ), + ), + ]) { + test('a runtime with $name keeps automatic tool loops refused and ' + 'reports no limit', () async { + final fake = configure(); + final engine = LlamaEngine(spi.LlamaBackend.withTextHistory()); + addTearDown(engine.dispose); + await engine.loadModelFromUrl('model.litertlm'); + expect((await engine.capabilities).supportsToolCalling, isTrue); + final session = api.ChatSession(engine, maxContextTokens: 0); + await expectLater( + session.completeWithTools( + const [api.LlamaTextContent('Weather?')], + tools: [weather], + params: params, + ), + throwsA( + isA().having( + (error) => error.message, + 'diagnostic', + allOf(contains('getTokenCount'), contains('@0.19.0')), + ), + ), + ); + final turns = fake.prompts.length; + // A reply at the budget is not reported without a passed probe. + fake.counts = (_, _) => (decoded: 8, total: 20); + final chunks = await engine.create(const [ + api.LlamaChatMessage.fromText( + role: api.LlamaChatRole.user, + text: 'hi', + ), + ], params: params).toList(); + expect(chunks.last.choices.single.finishReason, 'stop'); + expect(fake.prompts.length, turns + 1); + }); + } + + test('a runtime without the count API gets no probe turn', () async { + final fake = _installCountingFakeEngine( + counts: (_, budget) => (decoded: budget, total: 20), + countsApi: false, + ); + final backend = LiteRtLmBackend.withTextHistory(); + addTearDown(backend.dispose); + await backend.modelLoadFromUrl('model.litertlm', const ModelParams()); + expect(fake.prompts, isEmpty); + expect(fake.rejectedLengths, isEmpty); + }); + + for (final (name, factory) in [ + ('LlamaBackend.withTextHistory()', spi.LlamaBackend.withTextHistory), + ('LiteRtLmBackend.withTextHistory()', LiteRtLmBackend.withTextHistory), + ]) { + for (final (counts, limit) + in <(_TurnCounts?, internal.BackendGenerationLimit?)>[ + ((decoded: 7, total: 4095), null), + ( + (decoded: 8, total: 100), + internal.BackendGenerationLimit.maxTokens, + ), + ( + (decoded: 9, total: 100), + internal.BackendGenerationLimit.maxTokens, + ), + ( + (decoded: 7, total: 4096), + internal.BackendGenerationLimit.contextSize, + ), + ( + (decoded: 8, total: 4097), + internal.BackendGenerationLimit.contextSize, + ), + ((decoded: 7, total: 7), internal.BackendGenerationLimit.runtime), + ((decoded: 0, total: 100), internal.BackendGenerationLimit.runtime), + (null, internal.BackendGenerationLimit.runtime), + ]) { + test('$name reports $counts at maxTokens 8 and context 4096 as ' + '${limit?.name ?? 'finished'}', () async { + _installCountingFakeEngine( + counts: (turn, budget) => + turn == 0 ? (decoded: budget, total: 20) : counts, + ); + final engine = LlamaEngine(factory()); + addTearDown(engine.dispose); + await engine.loadModelFromUrl( + 'model.litertlm', + modelParams: const ModelParams(contextSize: 4096), + ); + final chunks = await engine.create(const [ + api.LlamaChatMessage.fromText( + role: api.LlamaChatRole.user, + text: 'hi', + ), + ], params: params).toList(); + expect(chunks.map((chunk) => chunk.text).join(), 'reply'); + final last = chunks.last; + expect( + last.choices.single.finishReason, + limit == null ? 'stop' : 'length', + ); + expect(completionGenerationLimit(last), limit); + + final raw = engine.generate('hi', params: params); + expect(await raw.join(), 'reply'); + expect(rawGenerationLimit(raw), limit); + }); + } + } + + test('the limit comes from the engine-resolved context size', () async { + _installCountingFakeEngine( + counts: (turn, budget) => turn == 0 + ? (decoded: budget, total: 20) + : (decoded: 2, total: 1024), + maxNumTokens: 1024, + ); + final engine = LlamaEngine(spi.LlamaBackend.withTextHistory()); + addTearDown(engine.dispose); + await engine.loadModelFromUrl( + 'model.litertlm', + modelParams: const ModelParams(contextSize: 4096), + ); + final last = await engine.create(const [ + api.LlamaChatMessage.fromText(role: api.LlamaChatRole.user, text: 'hi'), + ], params: params).last; + expect( + completionGenerationLimit(last), + internal.BackendGenerationLimit.contextSize, + ); + }); + + test('the limit comes from the executor when its fixed KV cache holds ' + 'fewer tokens than the settings report', () async { + for (final (counts, limit) + in <(_TurnCounts, internal.BackendGenerationLimit?)>[ + ( + (decoded: 4066, total: 4096), + internal.BackendGenerationLimit.contextSize, + ), + ((decoded: 100, total: 4095), null), + ]) { + final fake = _installCountingFakeEngine( + counts: (turn, budget) => + turn == 0 ? (decoded: budget, total: 20) : counts, + maxNumTokens: 65536, + executorTokens: 4096, + ); + final engine = LlamaEngine(spi.LlamaBackend.withTextHistory()); + await engine.loadModelFromUrl( + 'model.litertlm', + modelParams: const ModelParams(contextSize: 65536), + ); + expect(fake.rejectedLengths, [65536 * 4 + 64]); + final last = await engine.create(const [ + api.LlamaChatMessage.fromText( + role: api.LlamaChatRole.user, + text: 'hi', + ), + ], params: const api.GenerationParams(maxTokens: 8192)).last; + expect(completionGenerationLimit(last), limit); + await engine.dispose(); + } + }); + + test('an automatic tool loop runs a call from a finished reply and ' + 'answers from its result', () async { + final ran = []; + final fake = _installCountingFakeEngine( + chunks: (turn) => [ + if (turn == 1) + _toolCallChunk([ + ('get_weather', {'city': 'Paris'}), + ]) + else + _messageChunk('Sunny.'), + ], + counts: (turn, budget) => + turn == 0 ? (decoded: budget, total: 20) : (decoded: 7, total: 90), + ); + final engine = LlamaEngine(spi.LlamaBackend.withTextHistory()); + addTearDown(engine.dispose); + await engine.loadModelFromUrl('model.litertlm'); + final session = api.ChatSession(engine, maxContextTokens: 0); + final result = await session.completeWithTools( + const [api.LlamaTextContent('Weather in Paris?')], + tools: [ + api.ToolDefinition( + name: 'get_weather', + description: 'Weather for a city', + parameters: [api.ToolParam.string('city', required: true)], + handler: (call) async { + ran.add(call.raw); + return 'sunny'; + }, + ), + ], + params: params, + ); + expect(result.stopReason, api.LlamaToolLoopStopReason.completed); + expect(result.completion.text, 'Sunny.'); + expect(ran, [ + {'city': 'Paris'}, + ]); + expect(fake.prompts.skip(1).first, 'Weather in Paris?'); + expect(fake.prompts.length, 3); + }); + + for (final (name, counts) in [ + ('at maxTokens', (decoded: 8, total: 90)), + ('at the context size', (decoded: 3, total: 4096)), + ]) { + test('an automatic tool loop stops a reply $name as truncated without ' + 'running its call', () async { + var ran = 0; + final fake = _installCountingFakeEngine( + chunks: (_) => [ + _toolCallChunk([ + ('get_weather', {'city': 'Paris'}), + ]), + ], + counts: (turn, budget) => + turn == 0 ? (decoded: budget, total: 20) : counts, + ); + final engine = LlamaEngine(spi.LlamaBackend.withTextHistory()); + addTearDown(engine.dispose); + await engine.loadModelFromUrl( + 'model.litertlm', + modelParams: const ModelParams(contextSize: 4096), + ); + final session = api.ChatSession(engine, maxContextTokens: 0); + final result = await session.completeWithTools( + const [api.LlamaTextContent('Weather in Paris?')], + tools: [ + api.ToolDefinition( + name: 'get_weather', + description: 'Weather for a city', + parameters: [api.ToolParam.string('city', required: true)], + handler: (_) async { + ran++; + return 'sunny'; + }, + ), + ], + params: params, + ); + expect(result.stopReason, api.LlamaToolLoopStopReason.truncated); + expect(result.completion.finishReason, api.LlamaFinishReason.length); + expect(ran, 0); + expect(result.rolledBack, isTrue); + expect(session.history, isEmpty); + expect(fake.prompts.length, 2); + }); + } + + test('a stop sequence wins over a budget the turn also reached', () async { + final fake = _installCountingFakeEngine( + chunks: (_) => [_messageChunk('Hello STOP more')], + counts: (turn, budget) => + turn == 0 ? (decoded: budget, total: 20) : (decoded: 8, total: 90), + ); + final engine = LlamaEngine(spi.LlamaBackend.withTextHistory()); + addTearDown(engine.dispose); + await engine.loadModelFromUrl('model.litertlm'); + final chunks = await engine.create(const [ + api.LlamaChatMessage.fromText(role: api.LlamaChatRole.user, text: 'hi'), + ], params: params.copyWith(stopSequences: ['STOP'])).toList(); + expect(chunks.map((chunk) => chunk.text).join(), 'Hello '); + expect(chunks.last.choices.single.finishReason, 'stop'); + expect(completionGenerationLimit(chunks.last), isNull); + expect(fake.countReads, 1); + }); + + test('a cancel while the counts are read wins over the budget they ' + 'report', () async { + final read = Completer(); + final release = Completer(); + final fake = _installCountingFakeEngine( + counts: (turn, budget) => + turn == 0 ? (decoded: budget, total: 20) : (decoded: 8, total: 90), + ); + final engine = LlamaEngine(spi.LlamaBackend.withTextHistory()); + addTearDown(engine.dispose); + await engine.loadModelFromUrl('model.litertlm'); + fake.beforeCounts = () { + read.complete(); + return release.future; + }; + final last = engine.create(const [ + api.LlamaChatMessage.fromText(role: api.LlamaChatRole.user, text: 'hi'), + ], params: params).last; + await read.future.timeout(const Duration(seconds: 2)); + engine.cancelGeneration(); + release.complete(); + final chunk = await last; + expect(chunk.choices.single.finishReason, 'stop'); + expect(completionGenerationLimit(chunk), isNull); + }); + }); + test( 'unknown legacy roles are typed errors before template rendering', () async { @@ -1482,7 +1910,7 @@ void main() { isA().having( (error) => error.message, 'diagnostic', - contains('@0.19.0'), + contains('withTextHistory()'), ), ), ); @@ -3915,6 +4343,189 @@ void _installFakeEngine({ globalContext.setProperty('LiteRtLmEngine'.toJS, engineClass); } +typedef _TurnCounts = ({int decoded, int total}); + +/// A `@litert-lm/core@0.19.0`-shaped runtime with text history, tool +/// declarations and per-turn token counts. Turn 0 is the first message sent, +/// the one-token probe on a text-history load. Rejected messages, such as the +/// over-long prompt of the executor-limit probe, take no turn. +final class _CountingFake { + _CountingFake(this.counts, this.chunks, this.reject); + + /// The counts of [turn] at its `maxOutputTokens`, or null to fail the read. + _TurnCounts? Function(int turn, int budget) counts; + final List Function(int turn) chunks; + + /// The error the runtime streams instead of a reply to [prompt], or null. + final String? Function(String prompt) reject; + final List rejectedLengths = []; + final List> settings = []; + final List prompts = []; + final List budgets = []; + Future Function()? beforeCounts; + int created = 0; + int deleted = 0; + int countReads = 0; +} + +_CountingFake _installCountingFakeEngine({ + required _TurnCounts? Function(int turn, int budget) counts, + List Function(int turn)? chunks, + bool countsApi = true, + int? maxNumTokens = 4096, + int? executorTokens, + String? Function(String prompt)? reject, + bool Function(String prompt)? throwOnSend, +}) { + // Each character is one token; the executor enforces [executorTokens], + // which a fixed KV cache can hold below the [maxNumTokens] settings report. + final limit = executorTokens ?? maxNumTokens ?? 4096; + final fake = _CountingFake( + counts, + chunks ?? (_) => [_messageChunk('reply')], + reject ?? (prompt) => _inputTooLong(prompt, limit), + ); + final engineClass = JSObject() + ..setProperty( + 'create'.toJS, + ((JSObject settings) { + fake.settings.add( + (settings.dartify()! as Map) + .cast(), + ); + final engine = JSObject() + ..setProperty( + 'settings'.toJS, + { + 'backend': 3, + 'mainExecutorSettings': {'maxNumTokens': ?maxNumTokens}, + }.jsify(), + ) + ..setProperty( + 'delete'.toJS, + (() => Future.value(null).toJS).toJS, + ); + engine.setProperty( + 'createConversation'.toJS, + ((JSObject config) { + fake.created++; + final preface = config.getProperty('preface'.toJS); + // @litert-lm/core@0.19.0 serializes the whole preface. + if (preface != null) { + globalContext + .getProperty('JSON'.toJS) + .callMethod('stringify'.toJS, preface); + } + final budget = config + .getProperty('sessionConfig'.toJS) + .getProperty('maxOutputTokens'.toJS) + .toDartInt; + int? turn; + final conversation = + _fakeConversation( + chunks: const [], + chunksForRun: () { + turn = fake.prompts.length - 1; + fake.budgets.add(budget); + return fake.chunks(turn!); + }, + onPrompt: fake.prompts.add, + ) + ..setProperty( + 'getHistory'.toJS, + (() => Future.value([].toJS).toJS).toJS, + ) + ..setProperty( + 'delete'.toJS, + (() { + fake.deleted++; + return Future.value(null).toJS; + }).toJS, + ); + final send = conversation.getProperty( + 'sendMessageStreaming'.toJS, + ); + conversation.setProperty( + 'sendMessageStreaming'.toJS, + ((JSAny message) { + if (message.isA() && + (throwOnSend?.call((message as JSString).toDart) ?? + false)) { + throw StateError('send failed'); + } + final error = message.isA() + ? fake.reject((message as JSString).toDart) + : null; + if (error == null) { + return send.callAsFunction(conversation, message); + } + fake.rejectedLengths.add((message as JSString).toDart.length); + return _rejectingReadableStream(error); + }).toJS, + ); + Future<_TurnCounts> read() async { + await fake.beforeCounts?.call(); + final counts = fake.counts(turn ?? -1, budget); + if (counts == null) throw StateError('no counts'); + return counts; + } + + if (countsApi) { + conversation + ..setProperty( + 'getBenchmarkInfo'.toJS, + (() { + fake.countReads++; + return read().then((counts) { + return { + 'lastDecodeTokenCount': counts.decoded, + 'lastPrefillTokenCount': counts.total - counts.decoded, + }.jsify(); + }).toJS; + }).toJS, + ) + ..setProperty( + 'getTokenCount'.toJS, + (() => read() + .then((counts) => counts.total.toJS) + .toJS) + .toJS, + ); + } + return Future.value(conversation).toJS; + }).toJS, + ); + return Future.value(engine).toJS; + }).toJS, + ); + globalContext.setProperty('LiteRtLmEngine'.toJS, engineClass); + return fake; +} + +String? _inputTooLong(String prompt, int limit) => prompt.length >= limit + ? 'Input token ids are too long. Exceeding the maximum number of tokens ' + 'allowed: ${prompt.length} >= $limit' + : null; + +/// A stream whose first read rejects with a JS `Error` of [message], as +/// `@litert-lm/core@0.19.0` reports a failed turn. +JSObject _rejectingReadableStream(String message) { + final error = globalContext + .getProperty('Error'.toJS) + .callAsConstructor(message.toJS); + final reader = JSObject() + ..setProperty( + 'read'.toJS, + (() => globalContext + .getProperty('Promise'.toJS) + .callMethod('reject'.toJS, error)) + .toJS, + ) + ..setProperty('cancel'.toJS, (() => Future.value(null).toJS).toJS) + ..setProperty('releaseLock'.toJS, (() {}).toJS); + return JSObject()..setProperty('getReader'.toJS, (() => reader).toJS); +} + JSObject _fakeConversation({ required List chunks, List Function()? chunksForRun, diff --git a/test/unit/tooling/litert_text_history_web_driver_test.dart b/test/unit/tooling/litert_text_history_web_driver_test.dart index 73875f40d..2d977a80d 100644 --- a/test/unit/tooling/litert_text_history_web_driver_test.dart +++ b/test/unit/tooling/litert_text_history_web_driver_test.dart @@ -64,6 +64,11 @@ void main() { 'test/e2e/backends/litert_lm_tool_calling_web_e2e_test.dart', 'LITERT_TOOLS_INPUT ', ), + ( + 'truncation', + 'test/e2e/backends/litert_lm_truncation_web_e2e_test.dart', + 'LITERT_TRUNCATION_INPUT ', + ), ]) { test('Web LiteRT driver runs the ${suite ?? 'default'} suite', () async { final result = diff --git a/test/unit/tooling/run_local_e2e_test.dart b/test/unit/tooling/run_local_e2e_test.dart index a0120ad50..aedd290bd 100644 --- a/test/unit/tooling/run_local_e2e_test.dart +++ b/test/unit/tooling/run_local_e2e_test.dart @@ -523,6 +523,50 @@ Future main(List args) async { expect(result.stdout, isNot(contains('download'))); }); + test('LiteRT Web truncation requires a backend and local model and runs the ' + 'truncation suite', () async { + for (final args in [ + ['--scenario', 'litert-lm-web-truncation', '--dry-run'], + [ + '--scenario', + 'litert-lm-web-truncation', + '--model-path', + 'model.litertlm', + '--dry-run', + ], + [ + '--scenario', + 'litert-lm-web-truncation', + '--backend', + 'cpu', + '--dry-run', + ], + ]) { + expect((await runLocalE2e(args, projectRoot: '/repo')).exitCode, 64); + } + final result = await runLocalE2e( + [ + '--scenario', + 'litert-lm-web-truncation', + '--model-path', + 'models/existing.litertlm', + '--backend', + 'cpu', + '--dry-run', + ], + projectRoot: '/repo', + displayShell: LocalE2eDisplayShell.posix, + ); + expect(result.exitCode, 0); + expect( + result.stdout, + contains( + 'python3 tool/testing/litert_text_history_web_e2e.py --model-path models/existing.litertlm --backend cpu --suite truncation', + ), + ); + expect(result.stdout, isNot(contains('download'))); + }); + test( 'LiteRT Web scenarios leave the browser to the Chrome default', () async { diff --git a/test/unit/tooling/test_matrix_test.dart b/test/unit/tooling/test_matrix_test.dart index 811ab2591..331a9b2a1 100644 --- a/test/unit/tooling/test_matrix_test.dart +++ b/test/unit/tooling/test_matrix_test.dart @@ -405,6 +405,20 @@ void main() { expect(row.command, contains('--scenario image-editing')); }); + test('LiteRT Web truncation matrix selects its local scenario', () { + final row = testMatrixRows.singleWhere( + (row) => row.id == 'litert-lm-web-truncation', + ); + expect(row.mode, 'local-only'); + expect(row.covers, contains('maxTokens boundary')); + expect(row.command, contains('--scenario litert-lm-web-truncation')); + final scenario = buildLocalE2eScenarios().singleWhere( + (scenario) => scenario.name == row.id, + ); + expect(scenario.requiresDevice, isFalse); + expect(scenario.description, contains('existing local model')); + }); + test('LiteRT Web tool-calling matrix selects its local scenario', () { final row = testMatrixRows.singleWhere( (row) => row.id == 'litert-lm-web-tool-calling', diff --git a/tool/testing/litert_text_history_web_e2e.py b/tool/testing/litert_text_history_web_e2e.py index e4b8bb365..84c6f7309 100644 --- a/tool/testing/litert_text_history_web_e2e.py +++ b/tool/testing/litert_text_history_web_e2e.py @@ -13,6 +13,8 @@ 'LITERT_TEXT_HISTORY_INPUT'), 'tool-calling': ('test/e2e/backends/litert_lm_tool_calling_web_e2e_test.dart', 'LITERT_TOOLS_INPUT'), + 'truncation': ('test/e2e/backends/litert_lm_truncation_web_e2e_test.dart', + 'LITERT_TRUNCATION_INPUT'), } from serve_static_with_headers import CoiStaticHandler, ThreadingTcpServer diff --git a/tool/testing/run_local_e2e.dart b/tool/testing/run_local_e2e.dart index 90fabd0a2..b0a433029 100644 --- a/tool/testing/run_local_e2e.dart +++ b/tool/testing/run_local_e2e.dart @@ -1803,6 +1803,30 @@ List buildLocalE2eScenarios({String? projectRoot}) { ), ], ), + LocalE2eScenario( + name: 'litert-lm-web-truncation', + group: LocalE2eScenarioGroup.webSmoke, + description: + 'Compare Web token-limit reports and automatic tool loops with the pinned JS runtime token counts using an existing local model.', + requiresDevice: false, + stepsBuilder: (context) => [ + LocalE2eCommandStep( + workingDirectory: context.projectRoot, + executable: context.python, + arguments: [ + 'tool/testing/litert_text_history_web_e2e.py', + '--model-path', + context.modelPath!, + '--backend', + context.backend, + '--suite', + 'truncation', + ], + description: + 'LiteRT Web maxTokens boundary, context fill and automatic tool loops against direct-runtime token counts (local port 5198)', + ), + ], + ), LocalE2eScenario( name: 'litert-lm-multimodal-embedding', group: LocalE2eScenarioGroup.dartLocalOnly, @@ -2886,6 +2910,7 @@ Future runLocalE2e( if (const [ 'litert-lm-web-text-history', 'litert-lm-web-tool-calling', + 'litert-lm-web-truncation', ].contains(scenario.name) && !const ['cpu', 'gpu'].contains(parsed.backend)) { return LocalE2eResult( @@ -3165,6 +3190,7 @@ Future runLocalE2e( scenario.name == 'litert-lm-multimodal-embedding' || scenario.name == 'litert-lm-web-text-history' || scenario.name == 'litert-lm-web-tool-calling' || + scenario.name == 'litert-lm-web-truncation' || scenario.name == 'litert-lm-chat-features-smoke' || scenario.name == 'qwen3-litert-cpu-unicode' || scenario.name == 'native-prompt-cancel' || diff --git a/tool/testing/test_matrix.dart b/tool/testing/test_matrix.dart index 015afceef..4a8f205a1 100644 --- a/tool/testing/test_matrix.dart +++ b/tool/testing/test_matrix.dart @@ -1276,7 +1276,18 @@ const List testMatrixRows = [ command: 'dart run tool/testing/run_local_e2e.dart --scenario litert-lm-web-tool-calling --model-path --backend cpu', useWhen: - 'LiteRT-LM Web tool declarations, tool-call/result serialization, the preface.tools probe or tool-call parsing. Repeat with the affected model/backend; automatic tool loops stay out of scope (#919).', + 'LiteRT-LM Web tool declarations, tool-call/result serialization, the preface.tools probe or tool-call parsing. Repeat with the affected model/backend; litert-lm-web-truncation covers automatic tool loops.', + ), + TestMatrixRow( + id: 'litert-lm-web-truncation', + tier: 'targeted', + mode: 'local-only', + covers: + 'Web finish reason length at and below the maxTokens boundary and for a filled context, including a requested context above a fixed KV cache, matching pinned JS runtime token counts; stop above the boundary; automatic tool loop completed and truncated without running the tool', + command: + 'dart run tool/testing/run_local_e2e.dart --scenario litert-lm-web-truncation --model-path --backend cpu', + useWhen: + 'LiteRT-LM Web generation-limit reporting, the token-count load probe, automatic tool loops or a @litert-lm/core pin change. Repeat with the affected model/backend.', ), TestMatrixRow( id: 'litert-lm-json-schema', diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 49406365a..5d1e78235 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -14,6 +14,7 @@ validate against the exact release tag notes. ## Unreleased - Add manual tool calling to LiteRT-LM Web through `LlamaBackend.withTextHistory()` on `@litert-lm/core@0.19.0`: tools reach the model, `create` returns its tool calls, and tool results go back in the next request. `supportsToolCalling` reports whether the loaded runtime reads tool declarations; automatic tool loops, `ToolChoice.required` and `parallelToolCalls` still throw `LlamaUnsupportedException` ([#1790](https://github.com/leehack/llamadart/issues/1790)). +- Report LiteRT-LM Web replies cut off at `maxTokens` or the context size as finish reason `length`, and run automatic tool loops (`sendWithTools`, `completeWithTools`) there, through `LlamaBackend.withTextHistory()` on `@litert-lm/core@0.19.0`. A load probe checks that the runtime reports per-turn token counts; a reply that ends exactly at `maxTokens` is also reported as `length` ([#919](https://github.com/leehack/llamadart/issues/919)). ## 0.19.2 diff --git a/website/docs/guides/backend-selection.md b/website/docs/guides/backend-selection.md index 189b62157..01add4054 100644 --- a/website/docs/guides/backend-selection.md +++ b/website/docs/guides/backend-selection.md @@ -331,10 +331,11 @@ Assistant calls and `LlamaToolResultContent` results are replayed in the `@litert-lm/core@0.19.0` message shape, and a final tool result message is sent as the request's message. Check `supportsToolCalling`: the adapter probes that `createConversation` reads `preface.tools`, and a runtime that does not -rejects tools and tool messages with `LlamaUnsupportedException`. Automatic -tool loops stay unavailable until the runtime reports truncation -([#919](https://github.com/leehack/llamadart/issues/919)); see -[Tool calling](./tool-calling#runtime-notes). +rejects tools and tool messages with `LlamaUnsupportedException`. A reply cut +off at `maxTokens` or the context size ends with `length`, inferred from the +runtime's token counts, and automatic tool loops run when the load probe for +those counts passes ([#919](https://github.com/leehack/llamadart/issues/919)); +see [Tool calling](./tool-calling#runtime-notes). Use a browser-compatible bundle; the JS package documents its [Web LLM Models](https://huggingface.co/collections/litert-community/web-llm-models) collection, such as Gemma 4 E2B/E4B `-web.litertlm` files. A WebGPU load keeps @@ -350,8 +351,8 @@ assistant/system message, custom templates (including an empty override), `liteRtLm*` controls. Default thinking remains the model's behavior; no template replacement or thinking-budget support is implied. Raw `generate` sends one user text. Low-level `backend.applyChatTemplate` accepts one user message only; use -`engine.create` for structured history. Automatic tool loops remain unavailable -([#919](https://github.com/leehack/llamadart/issues/919)). +`engine.create` for structured history. The default constructors report no +token-limit truncation and refuse automatic tool loops. ## Measure before choosing diff --git a/website/docs/guides/tool-calling.md b/website/docs/guides/tool-calling.md index 7cd471788..1f946c290 100644 --- a/website/docs/guides/tool-calling.md +++ b/website/docs/guides/tool-calling.md @@ -282,8 +282,7 @@ them as tool calls to history. `completion.message`, `ChatSession` history and automatic tool loops exclude them. Natural EOF and cancellation retain their existing parsing behavior and expose no `partialToolCalls`; diagnostics never establish why generation ended. `ToolChoice.none` and parsing-disabled output -stay literal. In particular, LiteRT-LM Web still has the unknown-finish-cause -restriction tracked by [#919](https://github.com/leehack/llamadart/issues/919). +stay literal. ```dart final reply = await engine.complete(messages, tools: tools); @@ -604,15 +603,31 @@ runtime termination reporting, so that a reply cut off at `maxTokens` or the context stops the loop as `truncated` without running its calls. Native LiteRT-LM reports why a reply ended on runtimes whose `stream_proxy_finish_reason_abi_version` export returns 1: litert-lm-native -`v0.18.0-3` and later, including the default pin. Older native runtimes, and -Web `@litert-lm/core@0.19.0`, which reports no cause -([#919](https://github.com/leehack/llamadart/issues/919)), throw -`LlamaUnsupportedException` before starting the loop or modifying its history, including when resuming a turn or -passing an empty tools list. Plain `ChatSession.create` and -`LlamaEngine.create` remain available there for manually managed completion; -their LiteRT-LM `stop` finish reason does not prove the model reached EOS. Do -not execute calls automatically based on that value or infer truncation from -output length. +`v0.18.0-3` and later, including the default pin. + +LiteRT-LM Web `@litert-lm/core@0.19.0` reports no cause, so +`LlamaBackend.withTextHistory()` (or `LiteRtLmBackend.withTextHistory()`) +reads the runtime's token counts instead +([#919](https://github.com/leehack/llamadart/issues/919)). The load enables +the runtime's benchmark record, probes it with a one-token turn, and reads +the context size the runtime enforces from its rejection of an over-long +prompt: a model with a fixed KV cache can hold fewer tokens than +`contextSize`, which the runtime does not report otherwise. The runtime ends +a turn at an end-of-turn token, when its decode steps reach `maxTokens`, or +when the conversation fills that context, so a turn with fewer decode steps +than `maxTokens` and fewer tokens than that context ended normally; any other +turn ends with `length`. The end-of-turn token counts as a +decode step, so a reply whose last token lands exactly on `maxTokens` is also +reported as `length` and stops an automatic loop as `truncated`: give replies +headroom. + +Older native runtimes, Web runtimes that fail the probe and the default Web +constructors throw `LlamaUnsupportedException` before starting the loop or +modifying its history, including when resuming a turn or passing an empty +tools list. Plain `ChatSession.create` and `LlamaEngine.create` remain +available there for manually managed completion; their LiteRT-LM `stop` +finish reason does not prove the model reached EOS. Do not execute calls +automatically based on that value or infer truncation from output length. LiteRT-LM Web runs manual tool calling through `LlamaBackend.withTextHistory()` (or `LiteRtLmBackend.withTextHistory()`) on `@litert-lm/core@0.19.0`, when the @@ -624,8 +639,8 @@ content. Add one `LlamaToolResultContent` message per call, as in the manual loop above; assistant calls and results reach the runtime in the shape native LiteRT-LM sends. `ToolChoice.none` declares no tools, while `ToolChoice.required`, `parallelToolCalls`, tool-result `content` and media -throw `LlamaUnsupportedException`. Because the reply's stop reason is unknown, -check a reply before running its calls ([#919](https://github.com/leehack/llamadart/issues/919)). +throw `LlamaUnsupportedException`. Automatic loops run there when the load's +token-count probe passes, as described above. GPT-OSS channel and assistant frames wait for final parsing, including headers continued from the model's prompt, with or without tools. Ordinary prose streams diff --git a/website/docs/maintainers/runtime-ownership.md b/website/docs/maintainers/runtime-ownership.md index 45d8a4cf5..55e7b4aac 100644 --- a/website/docs/maintainers/runtime-ownership.md +++ b/website/docs/maintainers/runtime-ownership.md @@ -60,12 +60,34 @@ report why a conversation stream turn ended, and llamadart reads it `generationLimitUnsupportedReason` is null only after a load on a reporting runtime. -Web `@litert-lm/core@0.19.0` exposes no cause, so LiteRT-LM Web keeps -rejecting automatic tool loops. It needs a terminal cause from a qualified -`@litert-lm/core` release (or an owned bridge package) that distinguishes EOS, -output and context budgets and cancellation, a capability probe for it in -`litert_lm_backend_web.dart`, and `BackendGenerationLimitReporting` there. -Plain completion stays available; its `stop` remains unverified. +Web `@litert-lm/core@0.19.0` exposes no cause, but its counts bound one. +`withTextHistory()` loads set `benchmarkEnabled`, and after each turn +`litert_lm_backend_web.dart` reads `getBenchmarkInfo().lastDecodeTokenCount` +(the turn's decode steps, end-of-turn token included) and `getTokenCount()` +(the conversation's tokens). Upstream `ShouldStop` stops on a stop token, at +`current_step >= max_num_tokens` or at `num_decoded_steps >= +max_output_tokens`, so fewer steps than `maxOutputTokens` and fewer tokens +than the executor's `max_num_tokens` prove a stop-token end; anything else +reports `contextSize` or `maxTokens`, and unreadable counts report +`runtime`. A stop exactly at the budget is indistinguishable and reports +`maxTokens`. Cancellation and Dart stop sequences win. + +`engine.settings.mainExecutorSettings.maxNumTokens` is the engine's copy of +the request, not the limit: a static-KV executor clamps its own copy to its +cache (`ClampMaxNumTokens` in `llm_litert_compiled_model_executor.cc`), and +`ShouldStop` uses that copy. Qwen3 0.6B on WASM CPU requested at 65536 stops +at 4096 while the settings say 65536. `JsBenchmarkInfo` does not expose the +benchmark's `max_num_tokens`, so the load reads the executor's limit from +`Prefill`'s rejection of an input of at least that many tokens: `Input token +ids are too long. Exceeding the maximum number of tokens allowed: N >= M`. +The probe sends `4 × requested + 64` pseudo-random digits, which Gemma, Qwen +and Llama 3 tokenize at one to three digits per token, and is rejected before +any model work (about 20-100 ms at 65536). It also runs a one-token turn that +must report a decode count of 1 and a context count below `M`. Any other +outcome, including an accepted prompt or another error text, leaves +`generationLimitUnsupportedReason` set. Requalify with `litert-lm-web-truncation` whenever the +`@litert-lm/core` pin changes: a new stop condition in `ShouldStop` breaks +the inference. Why the cause needs the owner patch, from upstream `v0.18.0`: diff --git a/website/docs/platforms/support-matrix.md b/website/docs/platforms/support-matrix.md index f7760a39b..3234242a2 100644 --- a/website/docs/platforms/support-matrix.md +++ b/website/docs/platforms/support-matrix.md @@ -170,15 +170,15 @@ native and web. Model architecture support depends on the pinned runtime; see | Text task helpers and Matryoshka | Opt-in EG2 text profile; CPU BF16 retrieval reference | Same Dart helpers on an available embedding engine; no new Web qualification | Same Dart helpers on an available CPU embedding engine; bundle requires independent retrieval qualification | Unsupported with the underlying embedding engine | | Image/audio embeddings (`embedContent`) | EmbeddingGemma-2 + compatible projector, native v0.7.0-1; one complete micro-batch (BF16 qualified on CPU on macOS arm64, Linux x64, Windows x64, Android and iOS, and on macOS Metal; other GPU backends unqualified) | Explicit API-version-1 modality probe + compatible projector; EmbeddingGemma-2 qualified Chrome CPU wasm memory64 vs native CPU/Metal; repeated media batches qualified only on memory64 (wasm32 unqualified); hardware WebGPU unqualified | CPU; bundle processors on macOS arm64, iOS arm64, Android arm64 (Galaxy S24 and emulators), Linux x64 and arm64, and Windows x64 | Unsupported (parity gate) | | Next-token scores | Yes | Yes | No | No | -| Generation-limit reporting | `length` for output or context limits | `length` with the bridge usage probe; cap cause unspecified | `length` for output or context limits | No | +| Generation-limit reporting | `length` for output or context limits | `length` with the bridge usage probe; cap cause unspecified | `length` for output or context limits | `withTextHistory()`: `length` for output or context limits, inferred from the runtime's token counts after a load probe; a reply ending exactly at `maxTokens` also reports `length`. Default constructors: no | | Per-request usage | `usage` on the final `create` chunk | Yes | No | No ([#725](https://github.com/leehack/llamadart/issues/725)) | | Operation observers | Yes; after a load, `runtime` is `llamaCpp` | Yes; after a load, `runtime` is `llamaCpp` | Yes; after a load, `runtime` is `liteRtLm` | Yes; after a load, `runtime` is `liteRtLm` | | Multi-turn `ChatSession` | Yes | Yes | Yes | `LlamaBackend.withTextHistory()` or `LiteRtLmBackend.withTextHistory()` (existing defaults retain single-user-text): system/user/assistant text when the loaded runtime consumes `preface` and exposes `getHistory()` (`@litert-lm/core@0.19.0`), plus assistant tool calls and tool results when it also reads `preface.tools` (`supportsToolCalling`); final user or tool result message required; model/browser qualification is separate | | Deterministic session template time | `TemplateTimeChatSession`, Dart-rendered templates | Same Dart template path | Dart-side rendering only; runtime-owned template clock unchanged | No: runtime-owned clock; explicit template time rejected | | Tool calling | Yes | Yes | Yes, through the `LlamaEngine` parser; LiteRT-native constrained tool execution is not wired | Manual only, with `withTextHistory()` when the loaded runtime reads `preface.tools`: calls come from the runtime's `tool_calls`, checked in Chrome with Qwen3 0.6B on WebAssembly CPU and Gemma 4 E2B on WebGPU; `ToolChoice.required` and tool-result `content` throw; default constructors report no tool calling | -| Incomplete tool diagnostics | LFM raw `partialToolCalls` at reported length limits | Same parser when the runtime reports a length limit | Same Dart parser at reported length limits | No reliable terminal cause; unchanged #919 restriction | +| Incomplete tool diagnostics | LFM raw `partialToolCalls` at reported length limits | Same parser when the runtime reports a length limit | Same Dart parser at reported length limits | Unqualified: calls come from the runtime's `tool_calls` | | Canonical JSON Schema tools | Supported subset and selected formats | Selected formats; lazy grammars require the `lazyGrammar` runtime probe | No | No | -| Automatic `sendWithTools` / `completeWithTools` loop | Yes | Requires reliable runtime finish reporting | Yes | No: pinned runtime has no reliable termination cause; throws before generation | +| Automatic `sendWithTools` / `completeWithTools` loop | Yes | Requires reliable runtime finish reporting | Yes | `withTextHistory()` when the load's token-count probe passes (`@litert-lm/core@0.19.0`), checked in Chrome with Qwen3 0.6B on WebAssembly CPU and Gemma 4 E2B on WebGPU; otherwise throws before generation | | Multimodal | Image and audio with a projector | Image and audio with a projector URL | Image and audio files or bytes, when the bundle supports them | No | | Video | No | No | No | No | | Tool-result media | Images with a vision projector and a Hermes-style template (smoke-tested on macOS CPU and Metal with Qwen3.5-0.8B weights, a `qwen3vl_merger` projector and the Qwen3-VL template) | No | No | No |