Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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).
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 20 additions & 2 deletions doc/testing_matrix.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 5 additions & 2 deletions example/chat_app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 8 additions & 2 deletions example/chat_app/lib/providers/chat_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4449,15 +4449,21 @@ class ChatProvider extends ChangeNotifier {
}

void _updateToolTemplateSupport(Map<String, String> 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) {
_settings = _settings.copyWith(toolsEnabled: false);
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;
}
Expand Down
43 changes: 43 additions & 0 deletions example/chat_app/test/unit_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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(
Expand Down
47 changes: 45 additions & 2 deletions lib/src/backends/backend.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -28,10 +29,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();
Expand Down Expand Up @@ -442,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<LlamaCompletionChunkToolCall>? runtimeToolCallsOf(
Stream<List<int>> generation,
);
}

final Expando<BackendRuntimeToolCalls> _runtimeToolCallReporters =
Expando<BackendRuntimeToolCalls>();

/// 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 {
Expand Down
Loading
Loading