From a60e685df63527421e1cce63e6e03a6dc1d2bbf4 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Mon, 9 Nov 2026 20:21:44 -0500 Subject: [PATCH 1/3] Add LiteRT-LM Web manual tool calling on @litert-lm/core 0.19.0 LlamaBackend.withTextHistory() now declares tools through preface.tools, returns the runtime's parsed tool_calls from create, and replays assistant calls and tool results in the 0.19.0 Message shape native LiteRT-LM sends. A load-time probe reports supportsToolCalling only when the runtime reads preface.tools; ToolChoice.required, parallelToolCalls and tool-result content throw LlamaUnsupportedException, and automatic tool loops stay refused (#919). Fixes #1790 Refs #1874 --- CHANGELOG.md | 2 + README.md | 4 +- doc/testing_matrix.md | 22 +- example/chat_app/README.md | 7 +- .../chat_app/lib/providers/chat_provider.dart | 10 +- example/chat_app/test/unit_test.dart | 43 ++ lib/src/backends/backend.dart | 8 +- .../litert_lm/litert_lm_backend_web.dart | 324 ++++++++--- lib/src/core/engine/engine_capabilities.dart | 12 +- .../assets/capability_coverage.json | 4 +- skills/llamadart-chat-streaming/SKILL.md | 11 +- skills/llamadart-tool-calling/SKILL.md | 6 +- skills/llamadart-web/SKILL.md | 14 +- .../litert_lm_tool_calling_web_e2e_test.dart | 342 +++++++++++ .../litert_lm/litert_lm_backend_web_test.dart | 534 +++++++++++++++++- test/unit/tooling/run_local_e2e_test.dart | 44 ++ test/unit/tooling/test_matrix_test.dart | 14 + tool/testing/litert_text_history_web_e2e.py | 10 +- tool/testing/run_local_e2e.dart | 35 +- tool/testing/test_matrix.dart | 11 + website/docs/changelog/recent-releases.md | 2 + website/docs/guides/backend-selection.md | 25 +- website/docs/guides/tool-calling.md | 12 + website/docs/platforms/support-matrix.md | 6 +- 24 files changed, 1372 insertions(+), 130 deletions(-) create mode 100644 test/e2e/backends/litert_lm_tool_calling_web_e2e_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 68fd84b4a..b3dda59e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +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)). + ## 0.19.2 - Keep the default WebGPU bridge assets at `v0.1.83` (unchanged from 0.19.1). diff --git a/README.md b/README.md index 5cf52aae4..c6e11814b 100644 --- a/README.md +++ b/README.md @@ -173,7 +173,9 @@ published native [v0.19.1-2](https://github.com/leehack/litert-lm-native/releases/tag/v0.19.1-2), 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`. +paths. Web LiteRT-LM uses `@litert-lm/core@0.19.0`; through +`LlamaBackend.withTextHistory()` it forwards chat history and supports manual +tool calling. 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 8ae551cd6..84701f85d 100644 --- a/doc/testing_matrix.md +++ b/doc/testing_matrix.md @@ -1189,8 +1189,26 @@ no-system controls that fail if the preface is bypassed. Session reset and cancel/reuse must pass. A load failure on either route leaves semantic paths unqualified; a browser adapter alone establishes no model GPU execution. The model-free Chrome suite separately checks routing, API skew and typed -unsupported roles/options. Remaining tool/media/template work stays in -[#1152](https://github.com/leehack/llamadart/issues/1152). +unsupported roles/options. + +### LiteRT-LM Web tool calling + +`litert-lm-web-tool-calling` runs the same local server and Chrome +configuration with `test/e2e/backends/litert_lm_tool_calling_web_e2e_test.dart`. +It downloads no model. The published runtime alone must parse a `get_weather` +call into `tool_calls`, emit none without tools, and answer from a 0.19.0 tool +message; the adapter must then return that call from `ChatSession.create`, +answer from the `LlamaToolResultContent`, and pass cancel-after-first-chunk, +reset and reuse. Dry-run before execution: + +```bash +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)). ### Native LiteRT-LM JSON Schema diff --git a/example/chat_app/README.md b/example/chat_app/README.md index 2ad732b3c..606b54ca9 100644 --- a/example/chat_app/README.md +++ b/example/chat_app/README.md @@ -280,8 +280,11 @@ flutter test --run-skipped -t local-only \ 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. Tools, media - and template/thinking controls are outside this text-history slice. + 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 + template/thinking controls are outside this slice. Existing core default backends and the Genkit adapter do not opt in automatically. - The Gemma 4 E2B LiteRT-LM preset uses the native `.litertlm` bundle on diff --git a/example/chat_app/lib/providers/chat_provider.dart b/example/chat_app/lib/providers/chat_provider.dart index 35af697f0..526f6a079 100644 --- a/example/chat_app/lib/providers/chat_provider.dart +++ b/example/chat_app/lib/providers/chat_provider.dart @@ -4449,7 +4449,11 @@ class ChatProvider extends ChangeNotifier { } void _updateToolTemplateSupport(Map metadata) { - if (!_engineCapabilities.supportsToolCalling) { + // This app runs the model's calls automatically, which needs the + // truncation report LiteRT-LM Web lacks (#919). + final unreportedTruncation = + kIsWeb && _engineCapabilities.runtime == LlamaRuntime.liteRtLm; + if (!_engineCapabilities.supportsToolCalling || unreportedTruncation) { _detectedChatFormat = ChatFormat.contentOnly; _templateSupportsTools = false; if (_settings.toolsEnabled) { @@ -4457,7 +4461,9 @@ class ChatProvider extends ChangeNotifier { unawaited(_saveSettingsNow()); } _addInfoMessage( - 'Tool calling disabled for this runtime: it does not pass tools to the model. Use GGUF/WebGPU or a native LiteRT-LM target for structured tool calls.', + _engineCapabilities.supportsToolCalling + ? 'Tool calling disabled for LiteRT-LM Web in this app: it runs tool calls automatically, and this runtime does not report a reply cut off at the token limit. Use GGUF/WebGPU or a native LiteRT-LM target.' + : 'Tool calling disabled for this runtime: it does not pass tools to the model. Use GGUF/WebGPU or a native LiteRT-LM target for structured tool calls.', ); return; } diff --git a/example/chat_app/test/unit_test.dart b/example/chat_app/test/unit_test.dart index dd37115a8..c224a12b1 100644 --- a/example/chat_app/test/unit_test.dart +++ b/example/chat_app/test/unit_test.dart @@ -523,6 +523,47 @@ void main() { }, ); + test('loadModel keeps tools off for LiteRT-LM Web tool calling, which ' + 'reports no truncation', () 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', + 'tokenizer.chat_template': + '{% for message in messages %}{% if loop.last %}{{ message["content"] }}{% endif %}{% endfor %}', + }) + ..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(); + + 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'), + ), + ); + }); + test( 'loadModel detects tool support from the LiteRT-LM parsing template', () async { @@ -560,6 +601,8 @@ void main() { expect(provider.templateSupportsTools, isTrue); expect(provider.settings.toolsEnabled, isTrue); }, + // Native LiteRT-LM: on the Web the app keeps tools off (#919). + testOn: 'vm', ); test( diff --git a/lib/src/backends/backend.dart b/lib/src/backends/backend.dart index 1f0c13802..da1a75b87 100644 --- a/lib/src/backends/backend.dart +++ b/lib/src/backends/backend.dart @@ -28,10 +28,14 @@ abstract class LlamaBackend { /// Factory to create the appropriate backend for the current platform. factory LlamaBackend() => createBackend(); - /// Opts into ordered LiteRT-LM Web text history and system prompts. + /// Opts into ordered LiteRT-LM Web text history, system prompts and manual + /// tool calling. /// /// Web requires a runtime with the published conversation/preface APIs; - /// unsupported thinking, tools, media and template controls throw explicitly. + /// tools need one that reads `preface.tools`, which + /// `LlamaEngineCapabilities.supportsToolCalling` reports. Automatic tool + /// loops, unsupported thinking, media and template controls throw + /// explicitly. /// Native selection and behavior are the same as [LlamaBackend.new]. /// The original default factory retains its existing Web behavior. factory LlamaBackend.withTextHistory() => createTextHistoryBackend(); 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 3018f92b3..3f6d33588 100644 --- a/lib/src/backends/litert_lm/litert_lm_backend_web.dart +++ b/lib/src/backends/litert_lm/litert_lm_backend_web.dart @@ -38,10 +38,11 @@ import 'litert_lm_templates.dart'; /// `https://cdn.jsdelivr.net/npm/@litert-lm/core@0.19.0/+esm`. /// /// [LiteRtLmBackend.withTextHistory] opts into ordered system/user/assistant -/// text through a probed conversation preface. The original constructor retains -/// single-user-text dispatch and existing subclass generation overrides. -/// Tools, media, custom templates and explicit thinking/template controls are -/// unavailable. Raw [generate] sends one user text. +/// text and manual tool calling through a probed conversation preface. The +/// original constructor retains single-user-text dispatch and existing +/// subclass generation overrides. Media, custom templates and explicit +/// thinking/template controls are unavailable. Raw [generate] sends one user +/// text. class LiteRtLmBackend implements BackendRuntimeIdentity, @@ -81,6 +82,7 @@ class LiteRtLmBackend LlamaLogLevel _logLevel = LlamaLogLevel.warn; bool _isReady = false; bool _supportsTextHistory = false; + bool _supportsToolDeclarations = false; bool _hasContext = false; bool _cancelRequested = false; int _nextModelHandle = 1; @@ -115,8 +117,13 @@ class LiteRtLmBackend /// Creates a backend with ordered system/user/assistant text history. /// /// Requires the loaded runtime to consume `preface` and expose `getHistory`. - /// The final message must be user text. Tools, media and template/thinking - /// controls throw [LlamaUnsupportedException]. The original constructor's + /// 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 + /// [LlamaUnsupportedException]. The original constructor's /// subclass dispatch contract remains unchanged. Session budgets use a /// full-transcript UTF-8 estimate; exact JS tokenization is unavailable. factory LiteRtLmBackend.withTextHistory({ @@ -161,6 +168,9 @@ class LiteRtLmBackend @override bool get supportsMultiTurnChat => false; + /// False for this legacy single-user-text constructor. + /// [LiteRtLmBackend.withTextHistory] probes whether the loaded runtime reads + /// `preface.tools`. @override bool get supportsToolCalling => false; @@ -245,6 +255,8 @@ class LiteRtLmBackend _reportedBackendValue(_engine!) ?? _backendValueFor(backend); _supportsTextHistory = _textHistoryEnabled && await _probeTextHistory(_engine!); + _supportsToolDeclarations = + _supportsTextHistory && await _probeToolDeclarations(_engine!); _modelHandle = _nextModelHandle++; _isReady = true; onProgress?.call(1); @@ -252,6 +264,7 @@ class LiteRtLmBackend } catch (error) { _isReady = false; _supportsTextHistory = false; + _supportsToolDeclarations = false; _modelHandle = null; _contextHandle = null; _modelUrl = null; @@ -309,14 +322,17 @@ class LiteRtLmBackend String prompt, GenerationParams params, { List? parts, - }) => _generateWithHistory(contextHandle, prompt, params, parts: parts); + }) => _generateWithHistory(contextHandle, prompt.toJS, params, parts: parts); + /// Streams one reply to [message], a user text string or a `Message` + /// object, after the [history] and [tools] preface. Stream> _generateWithHistory( int contextHandle, - String prompt, + JSAny message, GenerationParams params, { List? parts, - List> history = const [], + List> history = const [], + List> tools = const [], }) { final run = _LiteRtLmWebRun(); late final StreamController> controller; @@ -342,10 +358,11 @@ class LiteRtLmBackend _generateRun( run, contextHandle, - prompt, + message, params, parts, history, + tools, ).listen( controller.add, onError: controller.addError, @@ -382,10 +399,11 @@ class LiteRtLmBackend Stream> _generateRun( _LiteRtLmWebRun run, int contextHandle, - String prompt, + JSAny message, GenerationParams params, List? parts, - List> history, + List> history, + List> tools, ) async* { final engine = _requireContextHandle(contextHandle); if (parts?.any((part) => part is LlamaVideoContent) ?? false) { @@ -408,7 +426,9 @@ class LiteRtLmBackend } final conversation = await engine - .createConversation(_createConversationConfig(params, history: history)) + .createConversation( + _createConversationConfig(params, history: history, tools: tools), + ) .toDart; _activeConversation = conversation; @@ -423,7 +443,7 @@ class LiteRtLmBackend return; } final stream = _withScopedConsoleGuardedStream( - _streamConversation(conversation, prompt), + _streamConversation(conversation, message), ); await for (final chunk in _applyStopSequences( stream, @@ -771,7 +791,8 @@ class LiteRtLmBackend JSObject _createConversationConfig( GenerationParams params, { - List> history = const [], + List> history = const [], + List> tools = const [], }) { final samplerParams = JSObject(); samplerParams.setProperty( @@ -795,8 +816,14 @@ class LiteRtLmBackend final config = JSObject(); config.setProperty('sessionConfig'.toJS, sessionConfig); - if (history.isNotEmpty) { - config.setProperty('preface'.toJS, {'messages': history}.jsify()); + if (history.isNotEmpty || tools.isNotEmpty) { + config.setProperty( + 'preface'.toJS, + { + if (history.isNotEmpty) 'messages': history, + if (tools.isNotEmpty) 'tools': tools, + }.jsify(), + ); } return config; } @@ -837,6 +864,55 @@ class LiteRtLmBackend } } + /// Whether creating a conversation reads `preface.tools`, so tool + /// declarations reach the runtime rather than being dropped. + Future _probeToolDeclarations(_LiteRtLmWebEngine engine) async { + _LiteRtLmWebConversation? conversation; + var consumedTools = false; + try { + final tools = [ + { + 'type': 'function', + 'function': { + 'name': 'llamadart_probe', + 'description': '', + 'parameters': { + 'type': 'object', + 'properties': {}, + }, + }, + }, + ].jsify(); + final preface = {'messages': []}.jsify()!; + // Enumerable, so a runtime that serializes the preface reads it. + final descriptor = JSObject() + ..setProperty('enumerable'.toJS, true.toJS) + ..setProperty( + 'get'.toJS, + (() { + consumedTools = true; + return tools; + }).toJS, + ); + globalContext + .getProperty('Object'.toJS) + .callMethod( + 'defineProperty'.toJS, + preface, + 'tools'.toJS, + descriptor, + ); + final config = _createConversationConfig(const GenerationParams()) + ..setProperty('preface'.toJS, preface); + conversation = await engine.createConversation(config).toDart; + return consumedTools; + } catch (_) { + return false; + } finally { + if (conversation != null) await _deleteConversation(conversation); + } + } + _LiteRtLmWebEngine _requireEngine() { final engine = _engine; if (engine == null || !_isReady) { @@ -863,9 +939,9 @@ class LiteRtLmBackend Stream _streamConversation( _LiteRtLmWebConversation conversation, - String prompt, + JSAny message, ) async* { - final reader = conversation.sendMessageStreaming(prompt).getReader(); + final reader = conversation.sendMessageStreaming(message).getReader(); try { while (!_cancelRequested) { final _LiteRtLmStreamReadResult result; @@ -990,23 +1066,29 @@ class LiteRtLmBackend return (directText as JSString).toDart; } - final content = obj.getProperty('content'.toJS); - if (content == null || !content.isA()) { - return ''; - } - final buffer = StringBuffer(); - final items = content as JSArray; - for (var i = 0; i < items.length; i += 1) { - final item = items.getProperty(i.toJS); - if (item == null || !item.isA()) { - continue; - } - final text = (item as JSObject).getProperty('text'.toJS); - if (text != null && text.isA()) { - buffer.write((text as JSString).toDart); + final content = obj.getProperty('content'.toJS); + if (content != null && content.isA()) { + final items = content as JSArray; + for (var i = 0; i < items.length; i += 1) { + final item = items.getProperty(i.toJS); + if (item == null || !item.isA()) { + continue; + } + final text = (item as JSObject).getProperty('text'.toJS); + if (text != null && text.isA()) { + buffer.write((text as JSString).toDart); + } } } + // The runtime parses the model's calls into `tool_calls`; the generic + // JSON envelope hands them to the Dart parser, as native LiteRT-LM does. + final toolCalls = obj.getProperty('tool_calls'.toJS); + if (toolCalls != null && + toolCalls.isA() && + (toolCalls as JSArray).toDart.isNotEmpty) { + buffer.write(jsonEncode({'tool_calls': toolCalls.dartify()})); + } return buffer.toString(); } @@ -1095,6 +1177,7 @@ class LiteRtLmBackend _engine = null; _isReady = false; _supportsTextHistory = false; + _supportsToolDeclarations = false; _hasContext = false; _modelHandle = null; _contextHandle = null; @@ -1536,53 +1619,127 @@ final class _TextHistoryLiteRtLmBackend extends LiteRtLmBackend @override bool get supportsNativeChatGeneration => isReady; + /// True once the loaded runtime has passed the history probe and reads + /// `preface.tools` when it creates a conversation. + @override + bool get supportsToolCalling => _isReady && _supportsToolDeclarations; + @override bool get requiresStructuredChatInput => true; @override void validateChatMessages(List messages) { - _textMessages(messages); + _wireMessages(messages); } - List> _textMessages(List messages) { - const runtime = 'LiteRT-LM Web @litert-lm/core@0.19.0'; + static const String _runtime = 'LiteRT-LM Web @litert-lm/core@0.19.0'; + + /// [messages] as `@litert-lm/core@0.19.0` `Message` objects, in the shape + /// native LiteRT-LM sends: assistant calls in `tool_calls`, results as + /// `tool_response` parts of one `tool` message. + List> _wireMessages(List messages) { if (messages.isEmpty) { throw LlamaUnsupportedException( - '$runtime needs a final user text message.', + '$_runtime needs a final user text or tool result message.', ); } - final history = >[]; + final wire = >[]; + var carriesTools = false; for (final message in messages) { final role = message.roleEnum?.name ?? message.roleString; - if (!const ['system', 'user', 'assistant'].contains(role) || - message.parts.any( - (part) => - part is! LlamaTextContent && - !(role == 'assistant' && part is LlamaThinkingContent), - )) { + bool allowed(LlamaContentPart part) => switch (role) { + 'system' || 'user' => part is LlamaTextContent, + 'assistant' => + part is LlamaTextContent || + part is LlamaThinkingContent || + part is LlamaToolCallContent, + 'tool' => part is LlamaToolResultContent, + _ => false, + }; + if (!const ['system', 'user', 'assistant', 'tool'].contains(role) || + !message.parts.every(allowed)) { throw LlamaUnsupportedException( - '$runtime supports only system/user/assistant text; ' - 'tools, media and user/system thinking content are unavailable.', + '$_runtime supports system/user/assistant text, assistant tool ' + 'calls and tool results; media, user/system thinking content and ' + 'text in a tool message are unavailable.', ); } - history.add({'role': role!, 'content': message.content}); + final calls = message.parts.whereType(); + if (role == 'tool') { + final results = message.parts.cast(); + if (results.isEmpty) { + throw LlamaUnsupportedException( + '$_runtime needs a LlamaToolResultContent in a tool message.', + ); + } + if (results.any((result) => result.content.isNotEmpty)) { + throw LlamaUnsupportedException( + '$_runtime does not take LlamaToolResultContent.content. Return ' + 'the tool output as its result.', + ); + } + carriesTools = true; + wire.add({ + 'role': 'tool', + 'content': [ + for (final result in results) + { + 'type': 'tool_response', + 'name': result.name, + 'response': result.result, + }, + ], + }); + } else if (calls.isNotEmpty) { + carriesTools = true; + final thinking = message.parts.whereType(); + wire.add({ + 'role': 'assistant', + // Text only: `content` would repeat each call's raw JSON. + 'content': message.parts + .whereType() + .map((part) => part.text) + .join(), + if (thinking.isNotEmpty) + 'reasoning_content': thinking + .map((part) => part.thinking) + .join('\n'), + 'tool_calls': [ + for (final call in calls) + { + 'type': 'function', + 'function': {'name': call.name, 'arguments': call.arguments}, + }, + ], + }); + } else { + wire.add({'role': role, 'content': message.content}); + } } - if (history.last['role'] != 'user') { + if (!const ['user', 'tool'].contains(wire.last['role'])) { throw LlamaUnsupportedException( - '$runtime text history needs a final user message; assistant ' + '$_runtime chat needs a final user or tool result message; assistant ' 'continuation and system-only generation are unavailable.', ); } - if (history.length > 1 && !supportsMultiTurnChat) { + if (wire.length > 1 && !supportsMultiTurnChat) { throw LlamaUnsupportedException( 'The loaded LiteRT-LM Web runtime did not consume preface.messages ' 'or expose getHistory. Text history and system prompts require ' 'the published @litert-lm/core@0.19.0 conversation APIs.', ); } - return history; + if (carriesTools && !supportsToolCalling) throw _toolsUnavailable(); + return wire; } + LlamaUnsupportedException _toolsUnavailable() => LlamaUnsupportedException( + 'The loaded LiteRT-LM Web runtime did not read preface.tools when it ' + 'created a conversation, so tool calling is unavailable. It requires ' + 'the published @litert-lm/core@0.19.0 conversation tools and a backend ' + 'from LlamaBackend.withTextHistory().', + ); + @override Stream> generateChat( int contextHandle, @@ -1596,32 +1753,49 @@ final class _TextHistoryLiteRtLmBackend extends LiteRtLmBackend String? sourceLangCode, String? targetLangCode, DateTime? templateNow, - }) async* { - const runtime = 'LiteRT-LM Web @litert-lm/core@0.19.0'; - if ((tools?.isNotEmpty ?? false) || - toolChoice == ToolChoice.required || - parallelToolCalls) { - throw LlamaUnsupportedException( - '$runtime supports text history only; tool declarations, required ' - 'tools and parallel tool calls are unavailable (see #1152 and #919).', - ); - } - if (!enableThinking || - (chatTemplateKwargs?.isNotEmpty ?? false) || - sourceLangCode != null || - targetLangCode != null || - templateNow != null) { - throw LlamaUnsupportedException( - '$runtime text history does not expose thinking, template kwargs, ' - 'language or template-clock controls. Use the model defaults.', - ); + }) { + final List> wire; + final List> declarations; + try { + if (toolChoice == ToolChoice.required || parallelToolCalls) { + throw LlamaUnsupportedException( + '$_runtime exposes neither ToolChoice.required enforcement nor a ' + 'parallel tool-call switch. Use ToolChoice.auto with ' + 'parallelToolCalls false, or a grammar-capable runtime such as ' + 'llama.cpp.', + ); + } + if (!enableThinking || + (chatTemplateKwargs?.isNotEmpty ?? false) || + sourceLangCode != null || + targetLangCode != null || + templateNow != null) { + throw LlamaUnsupportedException( + '$_runtime chat does not expose thinking, template kwargs, ' + 'language or template-clock controls. Use the model defaults.', + ); + } + // As on native LiteRT-LM, ToolChoice.none declares no tools. + declarations = toolChoice == ToolChoice.none + ? const [] + : [ + for (final tool in tools ?? const []) + tool.toJson(), + ]; + if (declarations.isNotEmpty && !supportsToolCalling) { + throw _toolsUnavailable(); + } + wire = _wireMessages(messages); + } on LlamaException catch (error, stackTrace) { + return Stream.error(error, stackTrace); } - final history = _textMessages(messages); - yield* _generateWithHistory( + final last = wire.last; + return _generateWithHistory( contextHandle, - history.last['content']!, + last['role'] == 'user' ? (last['content'] as String).toJS : last.jsify()!, params, - history: history.sublist(0, history.length - 1), + history: wire.sublist(0, wire.length - 1), + tools: declarations, ); } } @@ -1655,7 +1829,7 @@ extension type _LiteRtLmWebEngine._(JSObject _) implements JSObject { @JS() extension type _LiteRtLmWebConversation._(JSObject _) implements JSObject { - external _LiteRtLmReadableStream sendMessageStreaming(String message); + external _LiteRtLmReadableStream sendMessageStreaming(JSAny message); external void cancel(); diff --git a/lib/src/core/engine/engine_capabilities.dart b/lib/src/core/engine/engine_capabilities.dart index a39ca5f1f..d70a65657 100644 --- a/lib/src/core/engine/engine_capabilities.dart +++ b/lib/src/core/engine/engine_capabilities.dart @@ -82,16 +82,20 @@ class LlamaEngineCapabilities implements EngineCapabilities { /// Explicit `withTextHistory` factories support /// LiteRT-LM system/user/assistant text only when their loaded /// runtime consumes a conversation preface and exposes a working history API. - /// It requires a final user message. Tools/media and user/system thinking - /// parts are rejected; stored assistant reasoning is omitted from replay. + /// It requires a final user or tool result message. Media and user/system + /// thinking parts are rejected; stored assistant reasoning is replayed only + /// with an assistant tool call, as native LiteRT-LM does. /// The probe does not qualify a particular model's behavior. final bool supportsMultiTurnChat; /// Whether tools passed to `LlamaEngine.create` reach the model and its /// output is parsed for tool calls. /// - /// False on LiteRT-LM Web. Explicit text-history factories reject tool - /// declarations and messages; original constructors retain legacy behavior. + /// On LiteRT-LM Web, true only for explicit `withTextHistory` factories + /// whose loaded runtime reads `preface.tools` (`@litert-lm/core@0.19.0`); + /// calls come from the runtime's `tool_calls`. Automatic tool loops still + /// throw there, and `ToolChoice.required` and `parallelToolCalls` are + /// rejected. Original constructors report false. /// How well other models call tools still depends on their chat template. `ToolChoice.required` also /// needs [supportsGrammar] for Hermes-style templates, and /// [supportsLazyGrammar] for templates whose tool-call grammar waits for a diff --git a/packages/llamadart_validation/assets/capability_coverage.json b/packages/llamadart_validation/assets/capability_coverage.json index 9a557c046..d72d3b654 100644 --- a/packages/llamadart_validation/assets/capability_coverage.json +++ b/packages/llamadart_validation/assets/capability_coverage.json @@ -534,8 +534,8 @@ "matrix:Multi-turn ChatSession" ], "exemption": { - "issue": "https://github.com/leehack/llamadart/issues/1152", - "reason": "The existing C06.history pack covers native GGUF profiles, not the new LiteRT-LM Web preface/system path. Production-path Chrome tests cover ordered text, old/missing APIs, typed rejection and reset/cancellation isolation; the maintained litert-lm-web-text-history local runner compares a pinned JS reference and preface-bypass controls on an identified browser/model. A dedicated versioned Web validation profile and broader tool/media/template parity remain open in #1152. No model qualification is inferred from these inventory bindings.", + "issue": "https://github.com/leehack/llamadart/issues/1196", + "reason": "The existing C06.history and tools packs cover native profiles, not the LiteRT-LM Web preface path that carries history, system prompts and manual tool calls (#1790). Production-path Chrome tests cover ordered text, tool declaration/call/result wire shapes, old/missing APIs and the preface.tools probe, typed rejection and reset/cancellation isolation; the maintained litert-lm-web-text-history and litert-lm-web-tool-calling local runners compare a pinned JS reference with bypass and no-tools controls on an identified browser/model. No versioned Web validation profile exists yet (#1196); media/template parity and automatic tool loops (#919) stay out of scope. No model qualification is inferred from these inventory bindings.", "id": "litert-web-text-history-profile" } }, diff --git a/skills/llamadart-chat-streaming/SKILL.md b/skills/llamadart-chat-streaming/SKILL.md index 57465468b..d1e21a9ae 100644 --- a/skills/llamadart-chat-streaming/SKILL.md +++ b/skills/llamadart-chat-streaming/SKILL.md @@ -44,18 +44,21 @@ modalities and speculative strategies before offering them. `engine.create` and `ChatSession` when the loaded runtime's preface/history API probe passes; check `supportsMultiTurnChat` after loading. Each request owns a new conversation and supplies its visible transcript once. Stored - assistant reasoning stays in app history and is omitted from replay/accounting. Use a Web-compatible + assistant reasoning stays in app history and is omitted from replay/accounting + (except with an assistant tool call). Use a Web-compatible `.litertlm` bundle. Existing default/direct constructors keep legacy LiteRT Web single-user-text routing and subclass hooks. Native selection is unchanged; Genkit adoption is - separate. On this Web path, tools, tool/media and user/system thinking parts, a final assistant/system + separate. On this Web path, `ToolChoice.required`, `parallelToolCalls`, + tool-result `content`, media and user/system thinking parts, a final assistant/system message, custom templates, `enableThinking: false`, template kwargs and explicit template clocks throw `LlamaUnsupportedException`. Model-default thinking stays unchanged. Old runtimes reject history/system input and retain one-user-text completion. Budget trimming uses a full-transcript UTF-8 estimate because the JS tokenizer/template count is unavailable; accounting JSON is not sent - as a replacement model prompt. This text slice leaves tools/media/template work in - [#1152](https://github.com/leehack/llamadart/issues/1152). + as a replacement model prompt. Manual tool calling uses the same path when + `supportsToolCalling` is true (see the `llamadart-tool-calling` skill); + media and template controls stay unavailable. - For reproducible Dart-rendered template dates, use `TemplateTimeChatSession(engine, templateNow: DateTime.utc(2026, 1, 2))`. Each listened request snapshots the value before budget rendering and diff --git a/skills/llamadart-tool-calling/SKILL.md b/skills/llamadart-tool-calling/SKILL.md index 5a8b07110..f04fffdd5 100644 --- a/skills/llamadart-tool-calling/SKILL.md +++ b/skills/llamadart-tool-calling/SKILL.md @@ -218,8 +218,10 @@ description: >- `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 does - not forward tools, and WebGPU `ToolChoice.auto` parses calls best-effort. +- 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. `(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 441287619..4741706cc 100644 --- a/skills/llamadart-web/SKILL.md +++ b/skills/llamadart-web/SKILL.md @@ -96,9 +96,9 @@ in the llamadart-getting-started and llamadart-chat-streaming skills. `supportsMinP`, `supportsThinkingBudget` and `speculativeDecodingStrategies` (WebGPU rejects `SpeculativeDecodingConfig.draftMicroBatchSize`), and for what - LiteRT-LM web lacks: `supportsToolCalling`, `supportsPenalty` and - `supportsGrammar` are false there, and `supportsMultiTurnChat` is false - unless `withTextHistory()` is used and the loaded runtime supports it. Unreported + LiteRT-LM web lacks: `supportsPenalty` and `supportsGrammar` are false + there, and `supportsMultiTurnChat` and `supportsToolCalling` are false + unless `withTextHistory()` is used and the loaded runtime supports them. Unreported controls throw `LlamaUnsupportedException`; `engine.runtime` names the runtime, so never sniff the `.litertlm` extension after loading. - `engine.supportsNextTokenScoring` and @@ -151,8 +151,12 @@ in the llamadart-getting-started and llamadart-chat-streaming skills. message's text, so `ChatSession` history, system prompts and tools are not forwarded. `LlamaBackend.withTextHistory()` (or `LiteRtLmBackend.withTextHistory()`) opts into ordered system/user/assistant - text; tools are still rejected, and `supportsMultiTurnChat` reports whether - history is forwarded. + 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. 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_tool_calling_web_e2e_test.dart b/test/e2e/backends/litert_lm_tool_calling_web_e2e_test.dart new file mode 100644 index 000000000..2c277b93f --- /dev/null +++ b/test/e2e/backends/litert_lm_tool_calling_web_e2e_test.dart @@ -0,0 +1,342 @@ +@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/src/backends/litert_lm/litert_lm_backend_web.dart'; +import 'package:llamadart/llamadart.dart'; +import 'package:test/test.dart'; +import 'package:web/web.dart'; + +// 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('manual tool calls match the published JS runtime', () 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 = '__llamadartToolReferenceLoaded'; + 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 params = GenerationParams( + maxTokens: 1024, + temp: 0, + topK: 1, + topP: 1, + seed: 42, + ); + const contextSize = 4096; + const system = + 'You are a weather assistant. Call get_weather for every weather ' + 'question, then answer from its result.'; + const question = 'What is the weather in Paris right now?'; + const forecast = { + 'city': 'Paris', + 'condition': 'violet hail', + 'temp_c': -7, + }; + final weather = ToolDefinition( + name: 'get_weather', + description: 'Returns the current weather for a city.', + parameters: [ + ToolParam.string('city', description: 'City name', required: true), + ], + ); + final declaration = weather.toJson(); + bool usesForecast(String text) => + text.toLowerCase().contains('violet') || text.contains('-7'); + + final identity = { + ...manifest, + 'module': moduleUrl, + 'browser': window.navigator.userAgent, + }; + print('LITERT_TOOLS_INPUT ${jsonEncode(identity)}'); + + // The published runtime alone: its conversation parses the model's call + // into `tool_calls` and answers from a 0.19.0 tool message. + final direct = await constructor + .callMethod>( + 'create'.toJS, + { + 'model': model, + // GPU keeps the runtime default, as the adapter does. + if (device == ComputeDevice.cpu) 'backend': 3, + 'mainExecutorSettings': {'maxNumTokens': contextSize}, + }.jsify(), + ) + .toDart; + final directBackend = direct + .getProperty('settings'.toJS) + .getProperty('backend'.toJS) + .toDartInt; + Future>> reference( + List> history, + Object message, { + required bool tools, + }) async { + final conversation = await direct + .callMethod>( + 'createConversation'.toJS, + { + 'preface': { + 'messages': history, + if (tools) 'tools': [declaration], + }, + 'sessionConfig': { + 'maxOutputTokens': params.maxTokens, + 'samplerBackend': directBackend, + 'samplerParams': {'k': 1, 'p': 1, 'temperature': 0, 'seed': 42}, + }, + }.jsify(), + ) + .toDart; + final chunks = >[]; + try { + final reader = conversation + .callMethod('sendMessageStreaming'.toJS, message.jsify()) + .callMethod('getReader'.toJS); + try { + while (true) { + final result = await reader + .callMethod>('read'.toJS) + .toDart; + if (result.getProperty('done'.toJS).toDart) break; + chunks.add( + (result.getProperty('value'.toJS).dartify() as Map) + .cast(), + ); + } + } finally { + reader.callMethod('releaseLock'.toJS); + } + } finally { + await conversation.callMethod>('delete'.toJS).toDart; + } + return chunks; + } + + String textOf(List> chunks) => [ + for (final chunk in chunks) + for (final part in chunk['content'] as List? ?? const []) + if (part is Map && part['type'] == 'text') part['text'], + ].join(); + List callsOf(List> chunks) => [ + for (final chunk in chunks) ...?chunk['tool_calls'] as List?, + ]; + + const directSystem = {'role': 'system', 'content': system}; + final directCall = await reference([directSystem], question, tools: true); + final directCalls = callsOf(directCall); + final directNoTools = await reference( + [directSystem], + question, + tools: false, + ); + final directAnswer = await reference( + [ + directSystem, + {'role': 'user', 'content': question}, + { + 'role': 'assistant', + 'content': '', + 'tool_calls': [ + { + 'type': 'function', + 'function': { + 'name': 'get_weather', + 'arguments': {'city': 'Paris'}, + }, + }, + ], + }, + ], + { + 'role': 'tool', + 'content': [ + { + 'type': 'tool_response', + 'name': 'get_weather', + 'response': forecast, + }, + ], + }, + tools: true, + ); + await direct.callMethod>('delete'.toJS).toDart; + print( + 'LITERT_TOOLS_DIRECT ${jsonEncode({ + 'execution': const {2: 'WebGPU_ARTISAN', 3: 'WASM CPU', 4: 'WebGPU'}[directBackend], + 'callChunks': directCall.where((chunk) => chunk.containsKey('tool_calls')).toList(), + 'callText': textOf(directCall), + 'noToolsCalls': callsOf(directNoTools), + 'noToolsText': textOf(directNoTools), + 'answer': textOf(directAnswer), + })}', + ); + expect( + directCalls, + isNotEmpty, + reason: 'The runtime must parse the call into tool_calls.', + ); + expect( + ((directCalls.first! as Map)['function'] as Map)['name'], + 'get_weather', + ); + expect(callsOf(directNoTools), isEmpty); + expect(usesForecast(textOf(directAnswer)), isTrue); + + final engine = LlamaEngine( + LiteRtLmBackend.withTextHistory(moduleUrl: moduleUrl), + ); + addTearDown(engine.dispose); + await engine.loadModelFromUrl( + model, + modelParams: ModelParams(contextSize: contextSize, device: device), + ); + final capabilities = await engine.capabilities; + expect(capabilities.supportsMultiTurnChat, isTrue); + expect(capabilities.supportsToolCalling, isTrue); + + final session = ChatSession( + engine, + maxContextTokens: 0, + systemPrompt: system, + ); + Future ask() => session + .create( + const [LlamaTextContent(question)], + tools: [weather], + params: params, + ) + .collect(); + Future answer(LlamaCompletion reply) { + for (final call in reply.toolCalls) { + session.addMessage( + LlamaChatMessage.withContent( + role: LlamaChatRole.tool, + content: [ + LlamaToolResultContent( + id: call.id, + name: call.name, + result: forecast, + ), + ], + ), + ); + } + return session + .create(const [], tools: [weather], params: params) + .collect(); + } + + void expectWeatherCall(LlamaCompletion reply) { + expect(reply.finishReason, LlamaFinishReason.toolCalls); + expect(reply.toolCalls, isNotEmpty); + expect(reply.toolCalls.first.name, 'get_weather'); + expect( + '${reply.toolCalls.first.arguments['city']}'.toLowerCase(), + contains('paris'), + ); + } + + final call = await ask(); + expectWeatherCall(call); + final used = await answer(call); + expect(used.toolCalls, isEmpty); + expect(usesForecast(used.text), isTrue, reason: used.text); + expect(session.history.map((message) => message.role), [ + LlamaChatRole.user, + LlamaChatRole.assistant, + for (final _ in call.toolCalls) LlamaChatRole.tool, + LlamaChatRole.assistant, + ]); + + final plain = await engine.create(const [ + LlamaChatMessage.fromText(role: LlamaChatRole.system, text: system), + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: question), + ], params: params).collect(); + expect(plain.toolCalls, isEmpty); + + // Cancel a tool request after its first chunk, then reuse the engine. + session.reset(); + final cancelled = Completer(); + var cancelChunks = 0; + final subscription = session + .create( + const [LlamaTextContent(question)], + tools: [weather], + params: params, + ) + .listen( + (_) { + if (cancelChunks++ == 0) engine.cancelGeneration(); + }, + onDone: cancelled.complete, + onError: (Object _) => cancelled.complete(), + ); + await cancelled.future.timeout(const Duration(minutes: 3)); + await subscription.cancel(); + expect(cancelChunks, greaterThan(0)); + + session.reset(); + final reused = await ask(); + expectWeatherCall(reused); + final reusedAnswer = await answer(reused); + expect(usesForecast(reusedAnswer.text), isTrue, reason: reusedAnswer.text); + + print( + 'LITERT_TOOLS_ADAPTER ${jsonEncode({ + 'call': [ + for (final c in call.toolCalls) {'name': c.name, 'arguments': c.arguments}, + ], + 'callThinkingChars': call.thinking.length, + 'answer': used.text, + 'noToolsText': plain.text, + 'cancelChunks': cancelChunks, + 'reuseCall': [ + for (final c in reused.toolCalls) {'name': c.name, 'arguments': c.arguments}, + ], + 'reuseAnswer': reusedAnswer.text, + })}', + ); + print('LITERT_TOOLS_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 69e1e59d9..8c8e54f32 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 @@ -650,6 +650,454 @@ void main() { }, ); + group('manual tool calling', () { + final weather = api.ToolDefinition( + name: 'get_weather', + description: 'Weather for a city', + parameters: [api.ToolParam.string('city', required: true)], + ); + final weatherJson = { + 'type': 'function', + 'function': { + 'name': 'get_weather', + 'description': 'Weather for a city', + 'parameters': { + 'type': 'object', + 'properties': { + 'city': {'type': 'string'}, + }, + 'required': ['city'], + }, + }, + }; + + test('maps declarations, calls and results to the 0.19.0 shapes and ' + 'exposes the runtime calls in order', () async { + final prefaces = []; + final prompts = []; + _installFakeEngine( + textHistory: true, + toolDeclarations: true, + chunks: const [], + chunksForRun: (run) => [ + if (run == 0) ...[ + _messageChunk('need data'), + _toolCallChunk([ + ('get_weather', {'city': 'Paris'}), + ('get_weather', {'city': 'Oslo'}), + ]), + ] else + _messageChunk('Sunny in Paris, snow in Oslo.'), + ], + onPrompt: prompts.add, + onCreateConversation: (config) => + prefaces.add(config.getProperty('preface'.toJS)?.dartify()), + ); + final engine = LlamaEngine(spi.LlamaBackend.withTextHistory()); + addTearDown(engine.dispose); + await engine.loadModelFromUrl('model.litertlm'); + final capabilities = await engine.capabilities; + expect(capabilities.supportsToolCalling, isTrue); + expect(capabilities.supportsMultiTurnChat, isTrue); + + final session = api.ChatSession( + engine, + maxContextTokens: 0, + systemPrompt: 'Use tools.', + ); + final reply = await session + .create( + const [LlamaTextContent('Weather in Paris and Oslo?')], + tools: [weather], + ) + .collect(); + expect(reply.text, isEmpty); + expect(reply.thinking, 'need data'); + expect(reply.finishReason, api.LlamaFinishReason.toolCalls); + expect(reply.toolCalls.map((call) => call.name), [ + 'get_weather', + 'get_weather', + ]); + expect(reply.toolCalls.map((call) => call.arguments), [ + {'city': 'Paris'}, + {'city': 'Oslo'}, + ]); + for (final (call, result) in [ + (reply.toolCalls[0], {'sky': 'sunny'}), + (reply.toolCalls[1], 'snow'), + ]) { + session.addMessage( + LlamaChatMessage.withContent( + role: LlamaChatRole.tool, + content: [ + LlamaToolResultContent( + id: call.id, + name: call.name, + result: result, + ), + ], + ), + ); + } + final answer = await session.create(const [], tools: [weather]).collect(); + expect(answer.text, 'Sunny in Paris, snow in Oslo.'); + expect(answer.toolCalls, isEmpty); + + expect(prompts, [ + 'Weather in Paris and Oslo?', + jsonEncode({ + 'role': 'tool', + 'content': [ + { + 'type': 'tool_response', + 'name': 'get_weather', + 'response': 'snow', + }, + ], + }), + ]); + expect(prefaces, [ + { + 'messages': [ + {'role': 'system', 'content': 'Use tools.'}, + ], + 'tools': [weatherJson], + }, + { + 'messages': [ + {'role': 'system', 'content': 'Use tools.'}, + {'role': 'user', 'content': 'Weather in Paris and Oslo?'}, + { + 'role': 'assistant', + 'content': '', + 'reasoning_content': 'need data', + 'tool_calls': [ + for (final city in ['Paris', 'Oslo']) + { + 'type': 'function', + 'function': { + 'name': 'get_weather', + 'arguments': {'city': city}, + }, + }, + ], + }, + { + 'role': 'tool', + 'content': [ + { + 'type': 'tool_response', + 'name': 'get_weather', + 'response': {'sky': 'sunny'}, + }, + ], + }, + ], + 'tools': [weatherJson], + }, + ]); + }); + + test('ToolChoice.none declares no tools', () async { + final prefaces = []; + _installFakeEngine( + textHistory: true, + toolDeclarations: true, + chunks: [_messageChunk('plain')], + onCreateConversation: (config) => + prefaces.add(config.getProperty('preface'.toJS)?.dartify()), + ); + final engine = LlamaEngine(spi.LlamaBackend.withTextHistory()); + addTearDown(engine.dispose); + await engine.loadModelFromUrl('model.litertlm'); + final reply = await engine + .create( + const [ + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'hi'), + ], + tools: [weather], + toolChoice: api.ToolChoice.none, + ) + .collect(); + expect(reply.text, 'plain'); + expect(prefaces, [null]); + }); + + test('a runtime that ignores preface.tools reports no tool calling and ' + 'rejects tools and tool history before inference', () async { + var prompts = 0; + _installFakeEngine( + textHistory: true, + chunks: [_messageChunk('ok')], + onPrompt: (_) => prompts++, + ); + final engine = LlamaEngine(spi.LlamaBackend.withTextHistory()); + addTearDown(engine.dispose); + await engine.loadModelFromUrl('model.litertlm'); + final capabilities = await engine.capabilities; + expect(capabilities.supportsMultiTurnChat, isTrue); + expect(capabilities.supportsToolCalling, isFalse); + const user = LlamaChatMessage.fromText( + role: LlamaChatRole.user, + text: 'hi', + ); + final toolTurn = [ + user, + const LlamaChatMessage.withContent( + role: LlamaChatRole.assistant, + content: [ + LlamaToolCallContent( + name: 'get_weather', + arguments: {'city': 'Paris'}, + rawJson: '{"city":"Paris"}', + ), + ], + ), + const LlamaChatMessage.withContent( + role: LlamaChatRole.tool, + content: [LlamaToolResultContent(name: 'get_weather', result: 'x')], + ), + ]; + for (final request in [ + () => engine.create(const [user], tools: [weather]).toList(), + () => engine.create(toolTurn).toList(), + ]) { + await expectLater( + request(), + throwsA( + isA().having( + (e) => e.message, + 'message', + allOf(contains('preface.tools'), contains('@0.19.0')), + ), + ), + ); + } + expect(prompts, 0); + expect( + (await engine.create(const [user]).toList()).map((c) => c.text).join(), + 'ok', + ); + }); + + test('rejects required, parallel and unrepresentable tool turns before ' + 'inference, then recovers', () async { + var prompts = 0; + _installFakeEngine( + textHistory: true, + toolDeclarations: true, + chunks: [_messageChunk('ok')], + onPrompt: (_) => prompts++, + ); + final engine = LlamaEngine(spi.LlamaBackend.withTextHistory()); + addTearDown(engine.dispose); + await engine.loadModelFromUrl('model.litertlm'); + const user = LlamaChatMessage.fromText( + role: LlamaChatRole.user, + text: 'hi', + ); + const call = LlamaChatMessage.withContent( + role: LlamaChatRole.assistant, + content: [ + LlamaToolCallContent( + name: 'get_weather', + arguments: {'city': 'Paris'}, + rawJson: '{"city":"Paris"}', + ), + ], + ); + for (final request in Function()>[ + () => engine + .create( + const [user], + tools: [weather], + toolChoice: api.ToolChoice.required, + ) + .toList(), + () => engine + .create(const [user], tools: [weather], parallelToolCalls: true) + .toList(), + // Tool-result content, text in a tool message, a tool message + // without a result and a final assistant call. + () => engine.create([ + user, + call, + const LlamaChatMessage.withContent( + role: LlamaChatRole.tool, + content: [ + LlamaToolResultContent( + name: 'get_weather', + result: 'x', + content: [LlamaTextContent('more')], + ), + ], + ), + ]).toList(), + () => engine.create([ + user, + call, + const LlamaChatMessage.withContent( + role: LlamaChatRole.tool, + content: [ + LlamaToolResultContent(name: 'get_weather', result: 'x'), + LlamaTextContent('note'), + ], + ), + ]).toList(), + () => engine.create([ + user, + call, + const LlamaChatMessage.fromText(role: LlamaChatRole.tool, text: 'x'), + ]).toList(), + () => engine.create([user, call]).toList(), + ]) { + await expectLater(request(), throwsA(isA())); + } + expect(prompts, 0); + expect( + (await engine.create(const [user]).toList()).map((c) => c.text).join(), + 'ok', + ); + }); + + test('the backend SPI rejects tool-result content', () async { + var prompts = 0; + _installFakeEngine( + textHistory: true, + toolDeclarations: true, + chunks: [_messageChunk('ok')], + onPrompt: (_) => prompts++, + ); + final backend = LiteRtLmBackend.withTextHistory(); + addTearDown(backend.dispose); + final model = await backend.modelLoadFromUrl( + 'model.litertlm', + const ModelParams(), + ); + final context = await backend.contextCreate(model, const ModelParams()); + await expectLater( + (backend as spi.BackendNativeChatGeneration).generateChat( + context, + const [ + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'hi'), + LlamaChatMessage.withContent( + role: LlamaChatRole.assistant, + content: [ + LlamaToolCallContent( + name: 'get_weather', + arguments: {'city': 'Paris'}, + rawJson: '{"city":"Paris"}', + ), + ], + ), + LlamaChatMessage.withContent( + role: LlamaChatRole.tool, + content: [ + LlamaToolResultContent( + name: 'get_weather', + result: 'x', + content: [LlamaTextContent('more')], + ), + ], + ), + ], + const GenerationParams(), + ).toList(), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('LlamaToolResultContent.content'), + ), + ), + ); + 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'), + ), + ), + ); + 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 { + final fake = _installQueueFakeEngine( + textHistory: true, + toolDeclarations: true, + ); + final engine = LlamaEngine(spi.LlamaBackend.withTextHistory()); + addTearDown(() async { + fake.finishAll(); + await engine.dispose(); + }); + await engine.loadModelFromUrl('model.litertlm'); + final session = api.ChatSession(engine, maxContextTokens: 0); + final done = Completer(); + final subscription = session + .create(const [LlamaTextContent('first')], tools: [weather]) + .listen((_) {}, onDone: done.complete, onError: (Object _) {}); + await (await fake.started(0)).holding; + engine.cancelGeneration(); + (await fake.started(0)).finish(); + await done.future.timeout(const Duration(seconds: 2)); + await subscription.cancel(); + session.reset(); + final request = session + .create(const [LlamaTextContent('second')], tools: [weather]) + .collect(); + (await fake.started(1)).finish(); + expect((await request).text, 'second;'); + expect(fake.prefaces, [ + { + 'tools': [weatherJson], + }, + { + 'tools': [weatherJson], + }, + ]); + }); + }); + test( 'unknown legacy roles are typed errors before template rendering', () async { @@ -3181,8 +3629,11 @@ void _installFakeEngine({ required List chunks, bool textHistory = false, bool historyApi = true, + bool toolDeclarations = false, + List Function(int run)? chunksForRun, int? reportedBackend, }) { + var runs = 0; final engineClass = JSObject(); engineClass.setProperty( 'create'.toJS, @@ -3201,9 +3652,18 @@ void _installFakeEngine({ final preface = textHistory ? config.getProperty('preface'.toJS) : null; + // @litert-lm/core@0.19.0 serializes the whole preface. + if (toolDeclarations && preface != null) { + globalContext + .getProperty('JSON'.toJS) + .callMethod('stringify'.toJS, preface); + } if (preface == null) onCreateConversation?.call(config); final conversation = _fakeConversation( chunks: chunks, + chunksForRun: chunksForRun == null + ? null + : () => chunksForRun(runs++), onPrompt: onPrompt, onCancel: onCancel, onReaderCancel: onReaderCancel, @@ -3214,11 +3674,7 @@ void _installFakeEngine({ (() => Future.value([].toJS).toJS).toJS, ); } - if (preface != null && - (preface as JSObject) - .getProperty('messages'.toJS) - .toDart - .isNotEmpty) { + if (preface != null && !_isProbePreface(preface as JSObject)) { onCreateConversation?.call(config); } return Future.value(conversation).toJS; @@ -3236,6 +3692,7 @@ void _installFakeEngine({ JSObject _fakeConversation({ required List chunks, + List Function()? chunksForRun, _PromptHook? onPrompt, void Function()? onCancel, void Function()? onReaderCancel, @@ -3243,9 +3700,17 @@ JSObject _fakeConversation({ final conversation = JSObject(); conversation.setProperty( 'sendMessageStreaming'.toJS, - ((String prompt) { - onPrompt?.call(prompt); - return _fakeReadableStream(chunks, onReaderCancel: onReaderCancel); + ((JSAny message) { + // A `Message` object is reported as its JSON. + onPrompt?.call( + message.isA() + ? (message as JSString).toDart + : jsonEncode(message.dartify()), + ); + return _fakeReadableStream( + chunksForRun?.call() ?? chunks, + onReaderCancel: onReaderCancel, + ); }).toJS, ); conversation.setProperty( @@ -3302,6 +3767,34 @@ JSObject _fakeReadableStream( return stream; } +/// Whether [preface] is one of the load-time capability probes, which send +/// no messages. +bool _isProbePreface(JSObject preface) { + final messages = preface.getProperty('messages'.toJS); + return messages != null && messages.toDart.isEmpty; +} + +/// A chunk with the runtime's parsed tool calls, after optional [text]. +JSObject _toolCallChunk( + List<(String, Map)> calls, { + String? text, +}) => + { + 'role': 'assistant', + if (text != null) + 'content': [ + {'type': 'text', 'text': text}, + ], + 'tool_calls': [ + for (final (name, arguments) in calls) + { + 'type': 'function', + 'function': {'name': name, 'arguments': arguments}, + }, + ], + }.jsify()! + as JSObject; + JSObject _messageChunk(String text) { final chunk = JSObject(); final content = JSArray(); @@ -3395,9 +3888,16 @@ final class _QueueFakeRun { } final class _QueueFakeEngine { - _QueueFakeEngine({required this.rejectOnCancel, this.textHistory = false}); + _QueueFakeEngine({ + required this.rejectOnCancel, + this.textHistory = false, + this.toolDeclarations = false, + }); final bool textHistory; + + /// Whether conversation creation serializes the preface, reading its tools. + final bool toolDeclarations; final List prefaces = []; Future? delayNextConversation; int allConversationsDeleted = 0; @@ -3434,9 +3934,13 @@ final class _QueueFakeEngine { final delay = delayNextConversation; delayNextConversation = null; await delay; - final preface = textHistory - ? config.getProperty('preface'.toJS)?.dartify() - : null; + final rawPreface = config.getProperty('preface'.toJS); + if (toolDeclarations && rawPreface != null) { + globalContext + .getProperty('JSON'.toJS) + .callMethod('stringify'.toJS, rawPreface); + } + final preface = textHistory ? rawPreface?.dartify() : null; final gate = failNextConversation; failNextConversation = null; if (gate != null) { @@ -3457,8 +3961,8 @@ final class _QueueFakeEngine { } conversation.setProperty( 'sendMessageStreaming'.toJS, - ((String prompt) { - final current = run = _QueueFakeRun(prompt); + ((JSString prompt) { + final current = run = _QueueFakeRun(prompt.toDart); prefaces.add(preface); runs.add(current); _started[runs.length - 1].complete(current); @@ -3535,10 +4039,12 @@ final class _QueueFakeEngine { _QueueFakeEngine _installQueueFakeEngine({ bool rejectOnCancel = false, bool textHistory = false, + bool toolDeclarations = false, }) { final fake = _QueueFakeEngine( rejectOnCancel: rejectOnCancel, textHistory: textHistory, + toolDeclarations: toolDeclarations, ); final engineClass = JSObject(); engineClass.setProperty( diff --git a/test/unit/tooling/run_local_e2e_test.dart b/test/unit/tooling/run_local_e2e_test.dart index 91e735060..a0120ad50 100644 --- a/test/unit/tooling/run_local_e2e_test.dart +++ b/test/unit/tooling/run_local_e2e_test.dart @@ -479,6 +479,50 @@ Future main(List args) async { }, ); + test('LiteRT Web tool calling requires a backend and local model and runs the ' + 'tool-calling suite', () async { + for (final args in [ + ['--scenario', 'litert-lm-web-tool-calling', '--dry-run'], + [ + '--scenario', + 'litert-lm-web-tool-calling', + '--model-path', + 'model.litertlm', + '--dry-run', + ], + [ + '--scenario', + 'litert-lm-web-tool-calling', + '--backend', + 'cpu', + '--dry-run', + ], + ]) { + expect((await runLocalE2e(args, projectRoot: '/repo')).exitCode, 64); + } + final result = await runLocalE2e( + [ + '--scenario', + 'litert-lm-web-tool-calling', + '--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 tool-calling', + ), + ); + 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 f587b3f3f..811ab2591 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 tool-calling matrix selects its local scenario', () { + final row = testMatrixRows.singleWhere( + (row) => row.id == 'litert-lm-web-tool-calling', + ); + expect(row.mode, 'local-only'); + expect(row.covers, contains('no-tools control')); + expect(row.command, contains('--scenario litert-lm-web-tool-calling')); + final scenario = buildLocalE2eScenarios().singleWhere( + (scenario) => scenario.name == row.id, + ); + expect(scenario.requiresDevice, isFalse); + expect(scenario.description, contains('existing local model')); + }); + test( 'LiteRT Web history matrix selects the direct-runtime control scenario', () { diff --git a/tool/testing/litert_text_history_web_e2e.py b/tool/testing/litert_text_history_web_e2e.py index 5a26e09a2..aff6c67f0 100644 --- a/tool/testing/litert_text_history_web_e2e.py +++ b/tool/testing/litert_text_history_web_e2e.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Run local-only LiteRT Web history and matching published-runtime controls.""" +"""Run a local-only LiteRT Web suite against matching published-runtime controls.""" import argparse import hashlib import json @@ -7,6 +7,11 @@ import subprocess import threading +SUITES = { + 'text-history': 'test/e2e/backends/litert_lm_text_history_web_e2e_test.dart', + 'tool-calling': 'test/e2e/backends/litert_lm_tool_calling_web_e2e_test.dart', +} + from serve_static_with_headers import CoiStaticHandler, ThreadingTcpServer @@ -16,6 +21,7 @@ def main(): parser.add_argument('--backend', choices=['cpu', 'gpu'], default='cpu') # `dart test -p safari` drives the Safari app through safaridriver. parser.add_argument('--browser', choices=['chrome', 'safari'], default='chrome') + parser.add_argument('--suite', choices=sorted(SUITES), default='text-history') args = parser.parse_args() model = pathlib.Path(args.model_path).resolve(strict=True) with model.open('rb') as source: @@ -64,7 +70,7 @@ def log_message(self, *_): 'safari' if args.browser == 'safari' else 'chrome-webgpu', '--run-skipped', '-t', 'local-only', - 'test/e2e/backends/litert_lm_text_history_web_e2e_test.dart', + SUITES[args.suite], ]) finally: server.shutdown() diff --git a/tool/testing/run_local_e2e.dart b/tool/testing/run_local_e2e.dart index dd30d52ca..90fabd0a2 100644 --- a/tool/testing/run_local_e2e.dart +++ b/tool/testing/run_local_e2e.dart @@ -1779,6 +1779,30 @@ List buildLocalE2eScenarios({String? projectRoot}) { ), ], ), + LocalE2eScenario( + name: 'litert-lm-web-tool-calling', + group: LocalE2eScenarioGroup.webSmoke, + description: + 'Compare Web manual tool calls and tool results with pinned JS and a no-tools control 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', + 'tool-calling', + ], + description: + 'LiteRT Web manual tool calls, results, direct-runtime controls, cancellation and reset (local port 5198)', + ), + ], + ), LocalE2eScenario( name: 'litert-lm-multimodal-embedding', group: LocalE2eScenarioGroup.dartLocalOnly, @@ -2859,12 +2883,14 @@ Future runLocalE2e( 'and chat-app-web-litert-gemma4-smoke.\n', ); } - if (scenario.name == 'litert-lm-web-text-history' && + if (const [ + 'litert-lm-web-text-history', + 'litert-lm-web-tool-calling', + ].contains(scenario.name) && !const ['cpu', 'gpu'].contains(parsed.backend)) { - return const LocalE2eResult( + return LocalE2eResult( 64, - stderr: - '--backend cpu or gpu is required for litert-lm-web-text-history.\n', + stderr: '--backend cpu or gpu is required for ${scenario.name}.\n', ); } if (parsed.mmprojPath != null && parsed.modelPath == null) { @@ -3138,6 +3164,7 @@ Future runLocalE2e( scenario.name == 'litert-lm-json-schema' || scenario.name == 'litert-lm-multimodal-embedding' || scenario.name == 'litert-lm-web-text-history' || + scenario.name == 'litert-lm-web-tool-calling' || 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 2f45e7a32..015afceef 100644 --- a/tool/testing/test_matrix.dart +++ b/tool/testing/test_matrix.dart @@ -1267,6 +1267,17 @@ const List testMatrixRows = [ useWhen: 'LiteRT-LM Web conversation serialization, runtime capability probe, ChatSession history or system prompts. Repeat with the affected model/backend; no other browser/backend or tool/media/template support is implied.', ), + TestMatrixRow( + id: 'litert-lm-web-tool-calling', + tier: 'targeted', + mode: 'local-only', + covers: + 'Web manual tool calls from the runtime tool_calls, tool results used in the answer, matching pinned JS reference, no-tools control, cancellation/reuse and reset', + 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).', + ), TestMatrixRow( id: 'litert-lm-json-schema', tier: 'high-risk', diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 97a7e58fe..49406365a 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -13,6 +13,8 @@ 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)). + ## 0.19.2 - Keep default WebGPU bridge assets at `v0.1.83` (unchanged from 0.19.1). diff --git a/website/docs/guides/backend-selection.md b/website/docs/guides/backend-selection.md index 7c33b87ab..189b62157 100644 --- a/website/docs/guides/backend-selection.md +++ b/website/docs/guides/backend-selection.md @@ -320,8 +320,21 @@ exact JS tokenizer/template accounting is unavailable, and the JS runtime still applies its own template and context limits. `engine.chatTemplate` returns this accounting serialization on the opted-in path. It does not replace the model's JS template or the original structured messages sent for generation. -Stored assistant reasoning is omitted from replay/accounting; visible text, -including an empty assistant reply, is preserved. +Stored assistant reasoning is omitted from replay/accounting, except as +`reasoning_content` of an assistant tool call, as native LiteRT-LM sends it; +visible text, including an empty assistant reply, is preserved. + +The same factories run manual tool calling. Tools are sent as +`preface.tools`, the runtime renders them with its own template and parses +the model's calls into `tool_calls`, and `create` returns them as `toolCalls`. +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). 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 @@ -330,15 +343,15 @@ bundles on its GPU_ARTISAN path and can also load standard bundles on GPU (Qwen3 0.6B matched direct JS but is otherwise unqualified there). WASM CPU runs Qwen3 0.6B; the Gemma 4 bundles do not load on CPU. -LiteRT-LM Web rejects tool declarations/results, media and user/system thinking parts, a final +LiteRT-LM Web rejects `ToolChoice.required`, `parallelToolCalls`, tool-result +`content`, media and user/system thinking parts, a final assistant/system message, custom templates (including an empty override), `enableThinking: false`, template kwargs, explicit template clocks and native-only `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. -The remaining #1152 scope is tracked in -[the runtime gap](https://github.com/leehack/llamadart/issues/1152). +`engine.create` for structured history. Automatic tool loops remain unavailable +([#919](https://github.com/leehack/llamadart/issues/919)). ## Measure before choosing diff --git a/website/docs/guides/tool-calling.md b/website/docs/guides/tool-calling.md index f9f68995f..42c93e46d 100644 --- a/website/docs/guides/tool-calling.md +++ b/website/docs/guides/tool-calling.md @@ -614,6 +614,18 @@ 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 +loaded runtime reads `preface.tools`; `supportsToolCalling` reports it, and the +default constructors report `false`. Tools go to the runtime's own template, the +runtime parses the model's calls into `tool_calls`, and `create` returns them as +`toolCalls`. 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)). + 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 normally, and `ToolChoice.auto` allows text without a call. diff --git a/website/docs/platforms/support-matrix.md b/website/docs/platforms/support-matrix.md index b47071224..ede43cb6e 100644 --- a/website/docs/platforms/support-matrix.md +++ b/website/docs/platforms/support-matrix.md @@ -148,7 +148,7 @@ native and web. Model architecture support depends on the pinned runtime; see | LFM2 Python tool argument types | Declared legacy ToolParam types; copied string backslashes preserved | Same Dart parser; inference requires LFM-capable assets | N/A: LFM GGUF format | N/A: LFM GGUF format | | LFM2 auto Python-call grammar | Lazy schema enforcement with prompt penalties preserved; legacy ToolParam declarations | Text-only; requires v0.1.82+ loaded-core `lazyGrammar` and `penaltyPromptTokensWithGrammar` probes; otherwise typed unsupported | N/A: LFM GGUF format | N/A: LFM GGUF format | | LFM2 reasoning tool markers | Stay in reasoning; no executable calls | Same Dart parser; inference requires LFM-capable assets | N/A: LFM GGUF format | N/A: LFM GGUF format | -| Explicit parallel tool flags | Supported Dart tool grammars honor the request independently of history probes | Same Dart routing; enforcement depends on the active grammar capability | Runtime-managed; no new constraint capability | No tool declarations | +| Explicit parallel tool flags | Supported Dart tool grammars honor the request independently of history probes | Same Dart routing; enforcement depends on the active grammar capability | Runtime-managed; no new constraint capability | Rejected: no parallel tool-call switch | | Model-free setup report | Desktop IO only; publication policy, no native/model probe | Typed unsupported; no live browser check | Desktop IO only; publication policy, no native/model probe | Typed unsupported | | Pre-load check | `npu` and options llama.cpp ignores rejected; native library and GPU unchecked | Options the Web runtime ignores rejected; WebGPU and bridge assets unchecked | No runtime on macOS x86_64, Windows arm64 or the x86_64 iOS simulator, and explicit devices the ABI lacks (`gpu` on Linux arm64), and embeddings on Android x86_64, rejected; `LlamaEngine(LiteRtLmBackend())` reports `unknown` | Options the Web runtime ignores, `npu` and the embedding engine rejected; browser runtime unchecked | | LoRA | `ModelParams.loras` at load and `setLoraSource` at runtime, stacked and scaled; aLoRA rejected | Same, with bridge assets whose `getLoraAdapterCapabilities()` reports support ([llama-web-bridge#142](https://github.com/leehack/llama-web-bridge/pull/142)); otherwise rejected | Unsupported by the current advanced engine; see [owner #99](https://github.com/leehack/litert-lm-native/issues/99) | No | @@ -173,9 +173,9 @@ native and web. Model architecture support depends on the pinned runtime; see | 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 | | 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`); final user message required; model/browser qualification is separate | +| Multi-turn `ChatSession` | Yes | Yes | Yes | `LlamaBackend.withTextHistory()` or `LiteRtLmBackend.withTextHistory()` (existing defaults retain single-user-text): system/user/assistant text, assistant tool calls and tool results when the loaded runtime consumes `preface` and exposes `getHistory()` (`@litert-lm/core@0.19.0`); 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 | No: tool declarations and tool messages throw | +| 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 | | 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 | From f2624a4d632cfc7c2ba7145873e0c1a4a9d9bd72 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Mon, 9 Nov 2026 20:25:35 -0500 Subject: [PATCH 2/3] Exercise Web tool turns under the default session budget --- .../unit/backends/litert_lm/litert_lm_backend_web_test.dart | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) 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 8c8e54f32..f74d8314f 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 @@ -700,11 +700,7 @@ void main() { expect(capabilities.supportsToolCalling, isTrue); expect(capabilities.supportsMultiTurnChat, isTrue); - final session = api.ChatSession( - engine, - maxContextTokens: 0, - systemPrompt: 'Use tools.', - ); + final session = api.ChatSession(engine, systemPrompt: 'Use tools.'); final reply = await session .create( const [LlamaTextContent('Weather in Paris and Oslo?')], From 7d4630ffd5fbf32a2e4b2becdbb6c3d0b63067ef Mon Sep 17 00:00:00 2001 From: leehack Date: Mon, 9 Nov 2026 21:22:55 -0500 Subject: [PATCH 3/3] Carry LiteRT-LM Web runtime tool calls structurally and count tools in the session budget A runtime tool call that followed streamed text was lost, because the engine parsed the whole reply as one JSON envelope. The Web backend now reports runtime calls through an internal BackendRuntimeToolCalls seam keyed on the generateChat stream; the parser appends them after any calls parsed from text, so preamble text stays content as on native. The Web session budget now renders tool declarations and assistant tool calls, and the load probe for preface.tools runs only when text history is supported. --- lib/src/backends/backend.dart | 39 +++ .../litert_lm/litert_lm_backend_web.dart | 104 +++++++- lib/src/backends/web/web_backend.dart | 7 + .../engine/chat_completion_stream_parser.dart | 27 ++ lib/src/core/engine/engine.dart | 8 + .../assets/capability_coverage.json | 15 +- .../litert_lm_tool_calling_web_e2e_test.dart | 45 +++- .../litert_lm/litert_lm_backend_web_test.dart | 235 +++++++++++++++++- .../chat_completion_stream_parser_test.dart | 58 +++++ .../litert_text_history_web_driver_test.dart | 63 +++++ tool/testing/litert_text_history_web_e2e.py | 12 +- website/docs/guides/tool-calling.md | 3 +- website/docs/platforms/support-matrix.md | 2 +- 13 files changed, 595 insertions(+), 23 deletions(-) diff --git a/lib/src/backends/backend.dart b/lib/src/backends/backend.dart index da1a75b87..ca4a16634 100644 --- a/lib/src/backends/backend.dart +++ b/lib/src/backends/backend.dart @@ -13,6 +13,7 @@ import '../core/models/inference/next_token_scores.dart'; import '../core/models/inference/state_identity.dart'; import '../core/models/inference/tool_choice.dart'; import '../core/models/chat/chat_message.dart'; +import '../core/models/chat/completion_chunk.dart'; import '../core/models/chat/content_part.dart'; import '../core/models/config/gpu_backend.dart'; import '../core/models/config/gpu_device_info.dart'; @@ -446,6 +447,44 @@ BackendGenerationLimitReporting? generationLimitReporterOf(Object? backend) => ? backend : _generationLimitReporters[backend]; +/// Internal backend probe for tool calls a runtime parsed itself. +/// +/// The calls reach the engine beside the stream rather than as text, so the +/// reply text around them stays content and no output parser can drop them. +abstract class BackendRuntimeToolCalls { + /// The calls the runtime parsed while it produced [generation], a stream + /// this backend returned from `generateChat`, in order. + /// + /// Null while [generation] is open, or when the runtime parsed none. + List? runtimeToolCallsOf( + Stream> generation, + ); +} + +final Expando _runtimeToolCallReporters = + Expando(); + +/// Makes [reporter] report the runtime-parsed tool calls of [backend]. +/// +/// For an exported backend class, which must not expose the internal +/// [BackendRuntimeToolCalls] in its type. +void registerRuntimeToolCallReporter( + Object backend, + BackendRuntimeToolCalls reporter, +) { + _runtimeToolCallReporters[backend] = reporter; +} + +/// The runtime tool-call reporter of [backend]: the backend itself when it +/// implements [BackendRuntimeToolCalls], otherwise one registered with +/// [registerRuntimeToolCallReporter], or null. +BackendRuntimeToolCalls? runtimeToolCallReporterOf(Object? backend) => + backend == null + ? null + : backend is BackendRuntimeToolCalls + ? backend + : _runtimeToolCallReporters[backend]; + /// Internal backend probe for the tokens a runtime prefills for a prompt it /// renders from its own chat template. abstract class BackendRuntimePromptTokenization { 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 3f6d33588..e49e5503f 100644 --- a/lib/src/backends/litert_lm/litert_lm_backend_web.dart +++ b/lib/src/backends/litert_lm/litert_lm_backend_web.dart @@ -9,9 +9,11 @@ import 'dart:math' as math; import 'package:web/web.dart'; +import '../../core/engine/chat_template_renderer.dart'; import '../../core/engine/engine_observer.dart'; import '../../core/models/chat/content_part.dart'; import '../../core/models/chat/chat_message.dart'; +import '../../core/models/chat/completion_chunk.dart'; import '../../core/models/inference/tool_choice.dart'; import '../../core/models/tools/tool_definition.dart'; import '../../core/cache_policy.dart'; @@ -79,6 +81,8 @@ class LiteRtLmBackend _LiteRtLmWebRun? _activeRun; _LiteRtLmWebRun? _queuedRun; final Expando> _conversationDeletes = Expando>(); + final _LiteRtLmWebRuntimeToolCalls _runtimeToolCalls = + _LiteRtLmWebRuntimeToolCalls(); LlamaLogLevel _logLevel = LlamaLogLevel.warn; bool _isReady = false; bool _supportsTextHistory = false; @@ -112,7 +116,9 @@ class LiteRtLmBackend Duration? readyTimeout, }) : _moduleUrl = moduleUrl, _readyTimeout = readyTimeout ?? _engineReadyTimeout, - _preferredBackend = _normalizeBackendOverride(preferredBackend); + _preferredBackend = _normalizeBackendOverride(preferredBackend) { + registerRuntimeToolCallReporter(this, _runtimeToolCalls); + } /// Creates a backend with ordered system/user/assistant text history. /// @@ -334,8 +340,12 @@ class LiteRtLmBackend List> history = const [], List> tools = const [], }) { - final run = _LiteRtLmWebRun(); + // Calls to declared tools go to the engine beside the text; any other + // runtime call stays literal JSON text. + final run = _LiteRtLmWebRun(reportsToolCalls: tools.isNotEmpty); late final StreamController> controller; + // The engine looks calls up by the identity of the stream it was given. + late final Stream> stream = controller.stream; StreamSubscription>? subscription; controller = StreamController>( onListen: () { @@ -367,6 +377,11 @@ class LiteRtLmBackend controller.add, onError: controller.addError, onDone: () { + if (run.toolCalls.isNotEmpty) { + _runtimeToolCalls.calls[stream] = List.unmodifiable( + run.toolCalls, + ); + } _finishRun(run); unawaited(controller.close()); }, @@ -390,7 +405,7 @@ class LiteRtLmBackend .whenComplete(() => _finishRun(run)); }, ); - return controller.stream; + return stream; } /// Runs one generation for [generate]. @@ -443,7 +458,7 @@ class LiteRtLmBackend return; } final stream = _withScopedConsoleGuardedStream( - _streamConversation(conversation, message), + _streamConversation(conversation, message, run), ); await for (final chunk in _applyStopSequences( stream, @@ -940,6 +955,7 @@ class LiteRtLmBackend Stream _streamConversation( _LiteRtLmWebConversation conversation, JSAny message, + _LiteRtLmWebRun run, ) async* { final reader = conversation.sendMessageStreaming(message).getReader(); try { @@ -957,7 +973,7 @@ class LiteRtLmBackend break; } - final text = _extractTextChunk(result.value); + final text = _extractTextChunk(result.value, run); if (text.isNotEmpty) { yield text; } @@ -1049,7 +1065,9 @@ class LiteRtLmBackend return stopIndex; } - String _extractTextChunk(JSAny? value) { + /// The text of the streamed message [value]. Its runtime-parsed tool calls + /// go to [run] when it reports them, otherwise into the text as JSON. + String _extractTextChunk(JSAny? value, _LiteRtLmWebRun run) { if (value == null) { return ''; } @@ -1081,17 +1099,40 @@ class LiteRtLmBackend } } } - // The runtime parses the model's calls into `tool_calls`; the generic - // JSON envelope hands them to the Dart parser, as native LiteRT-LM does. final toolCalls = obj.getProperty('tool_calls'.toJS); if (toolCalls != null && toolCalls.isA() && (toolCalls as JSArray).toDart.isNotEmpty) { - buffer.write(jsonEncode({'tool_calls': toolCalls.dartify()})); + final calls = toolCalls.dartify()! as List; + if (run.reportsToolCalls) { + for (final call in calls) { + run.toolCalls.add(_runtimeToolCall(call, run.toolCalls.length)); + } + } else { + buffer.write(jsonEncode({'tool_calls': calls})); + } } return buffer.toString(); } + /// [call], a runtime `ToolCall`, as the [index]th call of a reply. + LlamaCompletionChunkToolCall _runtimeToolCall(Object? call, int index) { + final map = call is Map ? call : const {}; + final function = map['function'] is Map ? map['function'] as Map : const {}; + final arguments = function['arguments']; + return LlamaCompletionChunkToolCall( + index: index, + id: map['id'] is String ? map['id'] as String : null, + type: 'function', + function: LlamaCompletionChunkFunction( + name: function['name'] is String ? function['name'] as String : null, + arguments: arguments is String + ? arguments + : jsonEncode(arguments ?? const {}), + ), + ); + } + bool _hasMediaParts(List? parts) { if (parts == null) { return false; @@ -1594,17 +1635,40 @@ final class _TextHistoryLiteRtLmBackend extends LiteRtLmBackend // The runtime owns its tokenizer/template. Dart's budget fallback must see // every turn, while generation still receives the original structured input. + // The engine parses with the text-only form and counts the session budget + // from the plain render of the full form, which adds what the preface + // carries for tools: their declarations and each assistant call. static const String _accountingTemplate = '[{% for message in messages %}' '{"role":{{ message["role"] | tojson }},' '"content":{{ (message["content"] or "") | tojson }}}' '{% if not loop.last %},{% endif %}' '{% endfor %}]'; + static const String _toolAccountingTemplate = + '[{% if tools %}{"tools":{{ tools | tojson }}},{% endif %}' + '{% for message in messages %}' + '{"role":{{ message["role"] | tojson }},' + '"content":{{ (message["content"] or "") | tojson }}' + '{% if message["tool_calls"] %}' + '{% if message["reasoning_content"] %}' + ',"reasoning_content":{{ message["reasoning_content"] | tojson }}' + '{% endif %}' + ',"tool_calls":{{ message["tool_calls"] | tojson }}' + '{% endif %}' + '{% if message["name"] %},"name":{{ message["name"] | tojson }}{% endif %}' + '}' + '{% if not loop.last %},{% endif %}' + '{% endfor %}]'; @override Future> modelMetadata(int modelHandle) async { final metadata = await super.modelMetadata(modelHandle); - metadata['tokenizer.chat_template'] = _accountingTemplate; + metadata[parsingChatTemplateMetadataKey] = _accountingTemplate; + metadata['tokenizer.chat_template'] = _toolAccountingTemplate; + if (supportsToolCalling) { + metadata['llamadart.litert_lm_web.chat_scope'] = + 'system-user-assistant-text-and-tools'; + } metadata['llamadart.litert_lm_web.prompt_accounting'] = 'utf8-byte-estimate'; return metadata; @@ -1802,11 +1866,31 @@ final class _TextHistoryLiteRtLmBackend extends LiteRtLmBackend /// One [LiteRtLmBackend.generate] call. final class _LiteRtLmWebRun { + _LiteRtLmWebRun({this.reportsToolCalls = false}); + + /// Whether runtime-parsed tool calls go to [toolCalls] rather than into the + /// text. + final bool reportsToolCalls; + + /// The runtime-parsed tool calls so far, in order. + final List toolCalls = []; + /// Completes with true when a queued run may start, or false when it ends /// without starting. final Completer admission = Completer(); } +/// The runtime-parsed tool calls of each finished generation stream. +final class _LiteRtLmWebRuntimeToolCalls implements BackendRuntimeToolCalls { + final Expando> calls = + Expando>(); + + @override + List? runtimeToolCallsOf( + Stream> generation, + ) => calls[generation]; +} + @JS() extension type _LiteRtLmConsoleGuard._(JSObject _) implements JSObject { external void restore(); diff --git a/lib/src/backends/web/web_backend.dart b/lib/src/backends/web/web_backend.dart index aa28062ff..a7b10858f 100644 --- a/lib/src/backends/web/web_backend.dart +++ b/lib/src/backends/web/web_backend.dart @@ -2,6 +2,7 @@ import '../../core/engine/engine_observer.dart'; import '../../core/exceptions.dart'; import '../../core/models/chat/content_part.dart'; import '../../core/models/chat/chat_message.dart'; +import '../../core/models/chat/completion_chunk.dart'; import '../../core/models/inference/tool_choice.dart'; import '../../core/models/tools/tool_definition.dart'; import '../../core/models/config/log_level.dart'; @@ -53,6 +54,7 @@ class WebAutoBackend BackendGenerationUsageReporting, BackendGenerationLimitReporting, BackendGenerationLimitSupport, + BackendRuntimeToolCalls, BackendChatPromptGeneration, BackendNextTokenScoring, BackendNextTokenScoringSupport, @@ -668,6 +670,11 @@ class WebAutoBackend : null; } + @override + List? runtimeToolCallsOf( + Stream> generation, + ) => runtimeToolCallReporterOf(_delegate)?.runtimeToolCallsOf(generation); + @override LlamaGenerationUsage? generationUsageOf(Stream> generation) { final delegate = _delegate; diff --git a/lib/src/core/engine/chat_completion_stream_parser.dart b/lib/src/core/engine/chat_completion_stream_parser.dart index d68dd0291..738de40e5 100644 --- a/lib/src/core/engine/chat_completion_stream_parser.dart +++ b/lib/src/core/engine/chat_completion_stream_parser.dart @@ -83,6 +83,10 @@ class ChatCompletionStreamParser { /// `ToolChoice.required`. When the parse of the whole reply fails, it is /// parsed as partial output instead and its tool calls are withheld. Any /// other reply that does not parse throws [LlamaInferenceException]. + /// + /// Calls [runtimeToolCalls] returns after [tokenStream] ends, which the + /// runtime parsed itself and never wrote into the text, follow the calls + /// parsed from the text when tool-call parsing is enabled. static Stream parse({ required Stream tokenStream, required LlamaChatTemplateResult templateResult, @@ -94,6 +98,7 @@ class ChatCompletionStreamParser { bool Function()? stoppedAtLimit, bool Function()? cancelled, LlamaGenerationUsage? Function()? usage, + List? Function()? runtimeToolCalls, }) async* { var result = templateResult; var tokens = tokenStream; @@ -128,6 +133,7 @@ class ChatCompletionStreamParser { stoppedAtLimit: stoppedAtLimit, cancelled: cancelled, usage: usage, + runtimeToolCalls: runtimeToolCalls, ); } @@ -142,6 +148,7 @@ class ChatCompletionStreamParser { bool Function()? stoppedAtLimit, bool Function()? cancelled, LlamaGenerationUsage? Function()? usage, + List? Function()? runtimeToolCalls, }) async* { final buffer = StringBuffer(); var streamedContent = ''; @@ -628,6 +635,26 @@ class ChatCompletionStreamParser { final partial = parseOutput(isPartial: true); if (partial.partialToolCalls.isNotEmpty) parsed = partial; } + final runtimeCalls = parseToolCallsEnabled + ? runtimeToolCalls?.call() ?? const [] + : const []; + if (runtimeCalls.isNotEmpty) { + final calls = [...parsed.toolCalls, ...runtimeCalls]; + parsed = ChatParseResult( + content: parsed.content, + reasoningContent: parsed.reasoningContent, + toolCalls: [ + for (var i = 0; i < calls.length; i++) + LlamaCompletionChunkToolCall( + index: i, + id: calls[i].id, + type: calls[i].type, + function: calls[i].function, + ), + ], + partialToolCalls: parsed.partialToolCalls, + ); + } final finalReasoning = parsesLfmToolChannels ? (parsed.reasoningContent ?? '').trimLeft() diff --git a/lib/src/core/engine/engine.dart b/lib/src/core/engine/engine.dart index f55a69775..5c5b383be 100644 --- a/lib/src/core/engine/engine.dart +++ b/lib/src/core/engine/engine.dart @@ -1954,6 +1954,7 @@ class LlamaEngine implements LlamadartEngine { generationLimit = limit; LlamaGenerationUsage? generationUsage; void recordUsage(LlamaGenerationUsage usage) => generationUsage = usage; + List? runtimeToolCalls; final tokenStream = plan.usesNativeChatGeneration ? _generateNativeChat( @@ -1969,6 +1970,7 @@ class LlamaEngine implements LlamadartEngine { templateNow: templateNow, onLimit: recordLimit, onUsage: recordUsage, + onToolCalls: (calls) => runtimeToolCalls = calls, request: request, ) : _generate( @@ -1995,6 +1997,7 @@ class LlamaEngine implements LlamadartEngine { stoppedAtLimit: () => generationLimit != null, cancelled: request.isCancelled, usage: () => generationUsage, + runtimeToolCalls: () => runtimeToolCalls, ).map((chunk) { final limit = generationLimit; if (limit != null && @@ -2525,6 +2528,7 @@ class LlamaEngine implements LlamadartEngine { DateTime? templateNow, void Function(BackendGenerationLimit limit)? onLimit, void Function(LlamaGenerationUsage usage)? onUsage, + void Function(List calls)? onToolCalls, required GenerationRequest request, }) async* { _ensureReady(); @@ -2570,6 +2574,10 @@ class LlamaEngine implements LlamadartEngine { yield token; } _reportGenerationOutcome(stream, onLimit, onUsage); + final calls = runtimeToolCallReporterOf( + backend, + )?.runtimeToolCallsOf(stream); + if (calls != null && calls.isNotEmpty) onToolCalls?.call(calls); } catch (error, stackTrace) { Error.throwWithStackTrace( _generationFailure('Native chat generation', error), diff --git a/packages/llamadart_validation/assets/capability_coverage.json b/packages/llamadart_validation/assets/capability_coverage.json index d72d3b654..c7aa9aa6d 100644 --- a/packages/llamadart_validation/assets/capability_coverage.json +++ b/packages/llamadart_validation/assets/capability_coverage.json @@ -535,7 +535,7 @@ ], "exemption": { "issue": "https://github.com/leehack/llamadart/issues/1196", - "reason": "The existing C06.history and tools packs cover native profiles, not the LiteRT-LM Web preface path that carries history, system prompts and manual tool calls (#1790). Production-path Chrome tests cover ordered text, tool declaration/call/result wire shapes, old/missing APIs and the preface.tools probe, typed rejection and reset/cancellation isolation; the maintained litert-lm-web-text-history and litert-lm-web-tool-calling local runners compare a pinned JS reference with bypass and no-tools controls on an identified browser/model. No versioned Web validation profile exists yet (#1196); media/template parity and automatic tool loops (#919) stay out of scope. No model qualification is inferred from these inventory bindings.", + "reason": "The existing C06.history pack covers native GGUF profiles, not the LiteRT-LM Web preface path that carries history and system prompts (and the tool turns of litert-web-tool-calling-profile). Production-path Chrome tests cover ordered text, old/missing APIs, typed rejection and reset/cancellation isolation; the maintained litert-lm-web-text-history local runner compares a pinned JS reference and preface-bypass controls on an identified browser/model. No versioned Web validation profile exists yet (#1196); media/template parity stays out of scope. No model qualification is inferred from these inventory bindings.", "id": "litert-web-text-history-profile" } }, @@ -584,11 +584,20 @@ }, { "surfaces": [ - "capability:LlamaEngineCapabilities.supportsToolCalling", - "matrix:Tool calling" + "capability:LlamaEngineCapabilities.supportsToolCalling" ], "pack": "tools" }, + { + "surfaces": [ + "matrix:Tool calling" + ], + "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.", + "id": "litert-web-tool-calling-profile" + } + }, { "surfaces": [ "capability:LlamaEngineCapabilities.toolResultMedia", diff --git a/test/e2e/backends/litert_lm_tool_calling_web_e2e_test.dart b/test/e2e/backends/litert_lm_tool_calling_web_e2e_test.dart index 2c277b93f..1ec8e5ad7 100644 --- a/test/e2e/backends/litert_lm_tool_calling_web_e2e_test.dart +++ b/test/e2e/backends/litert_lm_tool_calling_web_e2e_test.dart @@ -88,7 +88,7 @@ void main() { 'module': moduleUrl, 'browser': window.navigator.userAgent, }; - print('LITERT_TOOLS_INPUT ${jsonEncode(identity)}'); + print('LITERT_TOOLS_IDENTITY ${jsonEncode(identity)}'); // The published runtime alone: its conversation parses the model's call // into `tool_calls` and answers from a 0.19.0 tool message. @@ -163,6 +163,17 @@ void main() { ]; const directSystem = {'role': 'system', 'content': system}; + // Asks for text before the call, so the reply can carry both. + const preambleSystem = + 'You are a weather assistant. Start every reply with the sentence ' + '"One moment, checking." and then call get_weather.'; + final directPreamble = await reference( + [ + {'role': 'system', 'content': preambleSystem}, + ], + question, + tools: true, + ); final directCall = await reference([directSystem], question, tools: true); final directCalls = callsOf(directCall); final directNoTools = await reference( @@ -209,6 +220,8 @@ void main() { 'noToolsCalls': callsOf(directNoTools), 'noToolsText': textOf(directNoTools), 'answer': textOf(directAnswer), + 'preambleText': textOf(directPreamble), + 'preambleCalls': callsOf(directPreamble), })}', ); expect( @@ -295,6 +308,32 @@ void main() { ], params: params).collect(); expect(plain.toolCalls, isEmpty); + final preamble = await engine + .create( + const [ + LlamaChatMessage.fromText( + role: LlamaChatRole.system, + text: preambleSystem, + ), + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: question), + ], + tools: [weather], + params: params, + ) + .collect(); + // Whatever text the runtime streams around its calls stays content and + // no call is lost, as in the direct reference. + expect(preamble.toolCalls.map((c) => c.name), [ + for (final c in callsOf(directPreamble)) + ((c! as Map)['function'] as Map)['name'], + ]); + expect( + preamble.text.trim(), + textOf( + directPreamble, + ).replaceAll(RegExp(r'[\s\S]*?'), '').trim(), + ); + // Cancel a tool request after its first chunk, then reuse the engine. session.reset(); final cancelled = Completer(); @@ -330,6 +369,10 @@ void main() { 'callThinkingChars': call.thinking.length, 'answer': used.text, 'noToolsText': plain.text, + 'preambleText': preamble.text, + 'preambleCalls': [ + for (final c in preamble.toolCalls) {'name': c.name, 'arguments': c.arguments}, + ], 'cancelChunks': cancelChunks, 'reuseCall': [ for (final c in reused.toolCalls) {'name': c.name, 'arguments': c.arguments}, 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 f74d8314f..7b1f889bf 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 @@ -699,6 +699,13 @@ void main() { final capabilities = await engine.capabilities; expect(capabilities.supportsToolCalling, isTrue); expect(capabilities.supportsMultiTurnChat, isTrue); + expect( + await engine.getMetadata(), + containsPair( + 'llamadart.litert_lm_web.chat_scope', + 'system-user-assistant-text-and-tools', + ), + ); final session = api.ChatSession(engine, systemPrompt: 'Use tools.'); final reply = await session @@ -794,12 +801,117 @@ void main() { ]); }); - test('ToolChoice.none declares no tools', () async { + for (final (name, spi.LlamaBackend Function() factory, history, probes) in [ + ('the legacy constructor', LiteRtLmBackend.new, true, 0), + ( + 'a runtime without text history', + LiteRtLmBackend.withTextHistory, + false, + 1, + ), + ('a runtime with text history', LiteRtLmBackend.withTextHistory, true, 2), + ]) { + test('$name runs $probes load probes', () async { + final fake = _installQueueFakeEngine( + textHistory: history, + toolDeclarations: true, + ); + final backend = factory(); + addTearDown(backend.dispose); + await backend.modelLoadFromUrl('model.litertlm', const ModelParams()); + expect(fake.conversationsCreated, probes); + expect( + (backend as spi.BackendChatScope).supportsToolCalling, + probes == 2, + ); + }); + } + + test('the session budget counts tool declarations and calls', () async { + final prefaces = []; + _installFakeEngine( + textHistory: true, + toolDeclarations: true, + chunks: [_messageChunk('ok')], + onCreateConversation: (config) => + prefaces.add(config.getProperty('preface'.toJS)?.dartify()), + ); + final engine = LlamaEngine(spi.LlamaBackend.withTextHistory()); + addTearDown(engine.dispose); + await engine.loadModelFromUrl( + 'model.litertlm', + modelParams: const ModelParams(contextSize: 256), + ); + final bulky = 'x' * 1200; + final call = LlamaChatMessage.withContent( + role: LlamaChatRole.assistant, + content: [ + const LlamaThinkingContent('plan'), + LlamaToolCallContent( + name: 'get_weather', + arguments: {'city': bulky}, + rawJson: jsonEncode({'city': bulky}), + ), + ], + ); + const result = LlamaChatMessage.withContent( + role: LlamaChatRole.tool, + content: [LlamaToolResultContent(name: 'get_weather', result: 'ok')], + ); + const user = LlamaChatMessage.fromText( + role: LlamaChatRole.user, + text: 'Weather?', + ); + final accounting = await engine.chatTemplate( + [user, call, result], + tools: [weather], + ); + final serialized = jsonDecode(accounting.prompt) as List; + expect(serialized.first, { + 'tools': [weatherJson], + }); + expect((serialized[2] as Map)['reasoning_content'], 'plan'); + expect( + (((serialized[2] as Map)['tool_calls'] as List).single + as Map)['function']['arguments'], + {'city': bulky}, + ); + expect((serialized[3] as Map)['name'], 'get_weather'); + + final session = api.ChatSession(engine); + session.addMessage(user); + session.addMessage(call); + session.addMessage(result); + session.addMessage( + const LlamaChatMessage.fromText( + role: LlamaChatRole.assistant, + text: 'Sunny.', + ), + ); + await session + .create( + const [LlamaTextContent('And tomorrow?')], + tools: [weather], + params: const GenerationParams(maxTokens: 1), + ) + .collect(); + expect(prefaces.single, { + 'tools': [weatherJson], + }, reason: 'The completed tool turn exceeds the budget once counted.'); + }); + + test('ToolChoice.none declares no tools and keeps a runtime call as ' + 'literal text', () async { final prefaces = []; _installFakeEngine( textHistory: true, toolDeclarations: true, - chunks: [_messageChunk('plain')], + chunks: [ + _messageChunk('plain '), + _toolCallChunk([ + ('get_weather', {'city': 'Paris'}), + ]), + ], onCreateConversation: (config) => prefaces.add(config.getProperty('preface'.toJS)?.dartify()), ); @@ -815,10 +927,127 @@ void main() { toolChoice: api.ToolChoice.none, ) .collect(); - expect(reply.text, 'plain'); + expect(reply.toolCalls, isEmpty); + expect( + reply.text, + 'plain ${jsonEncode({ + 'tool_calls': [ + { + 'type': 'function', + 'function': { + 'name': 'get_weather', + 'arguments': {'city': 'Paris'}, + }, + }, + ], + })}', + ); expect(prefaces, [null]); }); + for (final (name, chunks, text) in <(String, List, String)>[ + ( + 'text before the call', + [ + _messageChunk('Let me check.'), + _toolCallChunk([ + ('get_weather', {'city': 'Paris'}), + ]), + ], + 'Let me check.', + ), + ( + 'text after the call', + [ + _toolCallChunk([ + ('get_weather', {'city': 'Paris'}), + ]), + _messageChunk('Checking now.'), + ], + 'Checking now.', + ), + ( + 'calls and text split across chunks', + [ + _messageChunk('First '), + _toolCallChunk([ + ('get_weather', {'city': 'Paris'}), + ], text: 'Paris, '), + _messageChunk('then '), + _toolCallChunk([ + ('get_weather', {'city': 'Oslo'}), + ]), + _messageChunk('Oslo.'), + ], + 'First Paris, then Oslo.', + ), + ]) { + for (final (route, spi.LlamaBackend Function() factory) in [ + ('router', spi.LlamaBackend.withTextHistory), + ('direct backend', LiteRtLmBackend.withTextHistory), + ]) { + test('keeps runtime tool calls and the reply text with $name ' + '($route)', () async { + final prefaces = []; + _installFakeEngine( + textHistory: true, + toolDeclarations: true, + chunks: const [], + chunksForRun: (run) => run == 0 ? chunks : [_messageChunk('Done.')], + onCreateConversation: (config) => prefaces.add( + config.getProperty('preface'.toJS)?.dartify(), + ), + ); + final engine = LlamaEngine(factory()); + addTearDown(engine.dispose); + await engine.loadModelFromUrl('model.litertlm'); + final session = api.ChatSession(engine); + final reply = await session + .create(const [LlamaTextContent('Weather?')], tools: [weather]) + .collect(); + final cities = name.startsWith('calls') + ? ['Paris', 'Oslo'] + : ['Paris']; + expect(reply.text, text); + expect(reply.finishReason, api.LlamaFinishReason.toolCalls); + expect(reply.toolCalls.map((call) => call.name), [ + for (final _ in cities) 'get_weather', + ]); + expect(reply.toolCalls.map((call) => call.arguments), [ + for (final city in cities) {'city': city}, + ]); + for (final call in reply.toolCalls) { + session.addMessage( + LlamaChatMessage.withContent( + role: LlamaChatRole.tool, + content: [ + LlamaToolResultContent( + id: call.id, + name: call.name, + result: 'ok', + ), + ], + ), + ); + } + await session.create(const [], tools: [weather]).collect(); + final replayed = + ((prefaces.last! as Map)['messages'] as List)[1] as Map; + expect(replayed['content'], text); + expect(replayed['tool_calls'], [ + for (final city in cities) + { + 'type': 'function', + 'function': { + 'name': 'get_weather', + 'arguments': {'city': city}, + }, + }, + ]); + }); + } + } + test('a runtime that ignores preface.tools reports no tool calling and ' 'rejects tools and tool history before inference', () async { var prompts = 0; diff --git a/test/unit/core/engine/chat_completion_stream_parser_test.dart b/test/unit/core/engine/chat_completion_stream_parser_test.dart index 8954e62f3..42f6bba26 100644 --- a/test/unit/core/engine/chat_completion_stream_parser_test.dart +++ b/test/unit/core/engine/chat_completion_stream_parser_test.dart @@ -89,6 +89,64 @@ void main() { ); } + LlamaCompletionChunkToolCall runtimeCall(String city) => + LlamaCompletionChunkToolCall( + index: 0, + type: 'function', + function: LlamaCompletionChunkFunction( + name: 'weather', + arguments: jsonEncode({'city': city}), + ), + ); + + test('runtime tool calls follow the calls parsed from the text', () async { + final rendered = ChatTemplateEngine.render( + templateSource: + '{{ messages | tojson }}{{ tools | tojson }}', + messages: const [ + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'Hi'), + ], + metadata: const {}, + tools: [_weatherTool], + ); + final completion = await ChatCompletionStreamParser.parse( + tokenStream: Stream.fromIterable([ + 'Before ', + '{"name":"weather","arguments":{"city":"Paris"}}', + '', + ]), + templateResult: rendered, + parseToolCallsEnabled: true, + enableThinking: true, + modelName: 'runtime', + completionId: 'runtime-calls', + tools: [_weatherTool], + runtimeToolCalls: () => [runtimeCall('Oslo')], + ).collect(); + expect(completion.text.trim(), 'Before'); + expect(completion.finishReason, LlamaFinishReason.toolCalls); + expect(completion.toolCalls.map((call) => call.arguments['city']), [ + 'Paris', + 'Oslo', + ]); + expect(completion.toolCalls.map((call) => call.id), ['call_0', 'call_1']); + }); + + test('runtime tool calls are ignored when tool parsing is off', () async { + final completion = await ChatCompletionStreamParser.parse( + tokenStream: Stream.fromIterable(['plain']), + templateResult: const LlamaChatTemplateResult(prompt: 'prompt'), + parseToolCallsEnabled: false, + enableThinking: true, + modelName: 'runtime', + completionId: 'runtime-calls-off', + runtimeToolCalls: () => [runtimeCall('Oslo')], + ).collect(); + expect(completion.text, 'plain'); + expect(completion.toolCalls, isEmpty); + expect(completion.finishReason, LlamaFinishReason.stop); + }); + test('streams plain content chunks and a final stop chunk', () async { final chunks = await ChatCompletionStreamParser.parse( tokenStream: Stream.fromIterable(['hel', 'lo']), 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 0dbb92898..73875f40d 100644 --- a/test/unit/tooling/litert_text_history_web_driver_test.dart +++ b/test/unit/tooling/litert_text_history_web_driver_test.dart @@ -47,8 +47,71 @@ void main() { }, timeout: Timeout(_processTimeout + const Duration(seconds: 10)), ); + + for (final (suite, testFile, marker) in [ + ( + null, + 'test/e2e/backends/litert_lm_text_history_web_e2e_test.dart', + 'LITERT_TEXT_HISTORY_INPUT ', + ), + ( + 'text-history', + 'test/e2e/backends/litert_lm_text_history_web_e2e_test.dart', + 'LITERT_TEXT_HISTORY_INPUT ', + ), + ( + 'tool-calling', + 'test/e2e/backends/litert_lm_tool_calling_web_e2e_test.dart', + 'LITERT_TOOLS_INPUT ', + ), + ]) { + test('Web LiteRT driver runs the ${suite ?? 'default'} suite', () async { + final result = + await runBoundedProcess(Platform.isWindows ? 'python' : 'python3', [ + '-B', + '-c', + _suiteSource.replaceAll( + '__SUITE_ARGS__', + suite == null ? '' : ", '--suite', '$suite'", + ), + ], timeout: _processTimeout); + expect(result.exitCode, 0, reason: '${result.stdout}\n${result.stderr}'); + expect(result.stdout, contains('DRIVER_TEST $testFile')); + expect(result.stdout, contains(marker)); + }, timeout: Timeout(_processTimeout + const Duration(seconds: 10))); + } } +const _suiteSource = r''' +import pathlib +import runpy +import sys +import tempfile +from unittest.mock import patch + +sys.path.insert(0, str(pathlib.Path('tool/testing').resolve())) +import serve_static_with_headers + +real_server = serve_static_with_headers.ThreadingTcpServer + +def child(command): + print('DRIVER_TEST ' + command[-1], flush=True) + return 0 + +with tempfile.TemporaryDirectory(prefix='litert_web_driver_') as scratch: + model = pathlib.Path(scratch) / 'tiny.litertlm' + model.write_bytes(b'fixture') + sys.argv = ['litert_text_history_web_e2e.py', '--model-path', str(model)__SUITE_ARGS__] + with patch.object(serve_static_with_headers, 'ThreadingTcpServer', + lambda _, handler: real_server(('127.0.0.1', 0), handler)): + with patch('subprocess.call', side_effect=child): + try: + runpy.run_path('tool/testing/litert_text_history_web_e2e.py', + run_name='__main__') + except SystemExit as exit: + sys.exit(exit.code) +'''; + const _safariPlatformSource = r''' import pathlib import runpy diff --git a/tool/testing/litert_text_history_web_e2e.py b/tool/testing/litert_text_history_web_e2e.py index aff6c67f0..e4b8bb365 100644 --- a/tool/testing/litert_text_history_web_e2e.py +++ b/tool/testing/litert_text_history_web_e2e.py @@ -7,9 +7,12 @@ import subprocess import threading +# Suite name: (test file, marker of the served model identity). SUITES = { - 'text-history': 'test/e2e/backends/litert_lm_text_history_web_e2e_test.dart', - 'tool-calling': 'test/e2e/backends/litert_lm_tool_calling_web_e2e_test.dart', + 'text-history': ('test/e2e/backends/litert_lm_text_history_web_e2e_test.dart', + 'LITERT_TEXT_HISTORY_INPUT'), + 'tool-calling': ('test/e2e/backends/litert_lm_tool_calling_web_e2e_test.dart', + 'LITERT_TOOLS_INPUT'), } from serve_static_with_headers import CoiStaticHandler, ThreadingTcpServer @@ -64,13 +67,14 @@ def log_message(self, *_): thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() try: - print('LITERT_TEXT_HISTORY_INPUT ' + json.dumps(manifest), flush=True) + test_file, marker = SUITES[args.suite] + print(marker + ' ' + json.dumps(manifest), flush=True) return subprocess.call([ 'dart', 'test', '-p', 'safari' if args.browser == 'safari' else 'chrome-webgpu', '--run-skipped', '-t', 'local-only', - SUITES[args.suite], + test_file, ]) finally: server.shutdown() diff --git a/website/docs/guides/tool-calling.md b/website/docs/guides/tool-calling.md index 42c93e46d..7cd471788 100644 --- a/website/docs/guides/tool-calling.md +++ b/website/docs/guides/tool-calling.md @@ -619,7 +619,8 @@ LiteRT-LM Web runs manual tool calling through `LlamaBackend.withTextHistory()` loaded runtime reads `preface.tools`; `supportsToolCalling` reports it, and the default constructors report `false`. Tools go to the runtime's own template, the runtime parses the model's calls into `tool_calls`, and `create` returns them as -`toolCalls`. Add one `LlamaToolResultContent` message per call, as in the +`toolCalls`; text the model writes before or after a call stays the reply's +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 diff --git a/website/docs/platforms/support-matrix.md b/website/docs/platforms/support-matrix.md index ede43cb6e..f7760a39b 100644 --- a/website/docs/platforms/support-matrix.md +++ b/website/docs/platforms/support-matrix.md @@ -173,7 +173,7 @@ native and web. Model architecture support depends on the pinned runtime; see | 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 | | 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, assistant tool calls and tool results when the loaded runtime consumes `preface` and exposes `getHistory()` (`@litert-lm/core@0.19.0`); final user or tool result message required; model/browser qualification is separate | +| 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 |