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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
## Unreleased

- Add manual tool calling to LiteRT-LM Web through `LlamaBackend.withTextHistory()` on `@litert-lm/core@0.19.0`: tools reach the model, `create` returns its tool calls, and tool results go back in the next request. `supportsToolCalling` reports whether the loaded runtime reads tool declarations; automatic tool loops, `ToolChoice.required` and `parallelToolCalls` still throw `LlamaUnsupportedException` ([#1790](https://github.com/leehack/llamadart/issues/1790)).
- Report LiteRT-LM Web replies cut off at `maxTokens` or the context size as finish reason `length`, and run automatic tool loops (`sendWithTools`, `completeWithTools`) there, through `LlamaBackend.withTextHistory()` on `@litert-lm/core@0.19.0`. A load probe checks that the runtime reports per-turn token counts; a reply that ends exactly at `maxTokens` is also reported as `length` ([#919](https://github.com/leehack/llamadart/issues/919)).

## 0.19.2

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,8 @@ published native
owner source `0b15fb34` / upstream `7a03724c`. The selected loader requires
macOS 14+ before owned library loads, including legacy libraries and custom
paths. Web LiteRT-LM uses `@litert-lm/core@0.19.0`; through
`LlamaBackend.withTextHistory()` it forwards chat history and supports manual
tool calling.
`LlamaBackend.withTextHistory()` it forwards chat history, supports tool
calling and reports replies cut off at a token limit.

Native overrides accept stable `vMAJOR.MINOR.PATCH` releases and explicit
historical or nightly `bNNNN` artifacts. New nightly wrapper rebuilds use
Expand Down
29 changes: 26 additions & 3 deletions doc/testing_matrix.md
Original file line number Diff line number Diff line change
Expand Up @@ -1206,9 +1206,32 @@ dart run tool/testing/run_local_e2e.dart --scenario litert-lm-web-tool-calling \
--model-path /path/to/Qwen3-0.6B.litertlm --backend cpu --dry-run
```

Use `--backend gpu` with a `-web.litertlm` bundle for WebGPU. Automatic tool
loops stay out of scope until the runtime reports truncation
([#919](https://github.com/leehack/llamadart/issues/919)).
Use `--backend gpu` with a `-web.litertlm` bundle for WebGPU.

### LiteRT-LM Web truncation

`litert-lm-web-truncation` runs the same local server and Chrome
configuration with `test/e2e/backends/litert_lm_truncation_web_e2e_test.dart`
([#919](https://github.com/leehack/llamadart/issues/919)). It downloads no
model. The published runtime alone, with `benchmarkEnabled`, measures a
natural reply's decode steps `n` and replays it at budgets `n + 1`, `n`,
`n - 1` and `n - 2`, then fills a 1024-token context. The adapter must report
`stop` above `n`, `length`/`maxTokens` at and below it, `length`/`contextSize`
for the filled context, complete an automatic `get_weather` loop, and stop a
3-token loop as `truncated` without running the tool. A last phase requests a
65536-token context, above a fixed KV cache such as Qwen3 0.6B's 4096 on WASM
CPU: the runtime's own over-long-prompt rejection names the executor's limit,
and the adapter must report the long reply as `length` at that limit or at
`maxTokens` 8192. Dry-run before
execution:

```bash
dart run tool/testing/run_local_e2e.dart --scenario litert-lm-web-truncation \
--model-path /path/to/Qwen3-0.6B.litertlm --backend cpu --dry-run
```

Use `--backend gpu` with a `-web.litertlm` bundle for WebGPU. Rerun it when
the `@litert-lm/core` pin changes.

### Native LiteRT-LM JSON Schema

Expand Down
13 changes: 8 additions & 5 deletions example/chat_app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,11 +279,11 @@ flutter test --run-skipped -t local-only \
- The chat app explicitly uses `LlamaBackend.withTextHistory()` to forward
ordered system/user/assistant text through the probed LiteRT-LM Web
conversation API. The runtime still applies its own model template.
Function Calling and Thinking controls remain unavailable: the app uses
model-default thinking without changing saved preferences. The library
supports manual LiteRT-LM Web tool calls, but this app runs tool calls
automatically, which needs the truncation report the runtime lacks
([#919](https://github.com/leehack/llamadart/issues/919)). Media and
Thinking controls remain unavailable: the app uses model-default
thinking without changing saved preferences. Function Calling runs when
the loaded runtime reports replies cut off at a token limit
(`@litert-lm/core@0.19.0`,
[#919](https://github.com/leehack/llamadart/issues/919)). Media and
template/thinking controls are outside this slice.
Existing core default backends and the Genkit adapter do not opt in
automatically.
Expand Down Expand Up @@ -372,6 +372,9 @@ layouts) opens a separate screen for the experimental `ImageGenerationEngine`
offload when it fits. Choosing a lower layer count makes it a fixed manual
setting. Reload the model to apply changes.
3. Optionally enable **Function Calling** and edit tool declarations depending on model/template support.
The app runs the model's tool calls itself, on every runtime, and runs
none from a reply that ended at the token limit (finish reason `length`):
it shows a notice instead. Raise **Max generated tokens** and send again.
4. Tap **Load Model** to apply changes.


Expand Down
27 changes: 23 additions & 4 deletions example/chat_app/lib/providers/chat_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'dart:ui' as ui;
import 'package:dio/dio.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:llamadart/backend.dart';
import 'package:llamadart/llamadart.dart';
import 'package:path/path.dart' as p;

Expand Down Expand Up @@ -2062,6 +2063,7 @@ class ChatProvider extends ChangeNotifier {
var hasAudioPartsInTurn = false;
var isCpuMultimodalTurn = false;
var pendingToolCalls = const <LlamaToolCallContent>[];
var toolCallsCutOff = false;
var accountingApplied = false;

try {
Expand Down Expand Up @@ -2261,7 +2263,12 @@ class ChatProvider extends ChangeNotifier {
if (allowToolExecution &&
toolsForTurn != null &&
toolCalls.isNotEmpty) {
pendingToolCalls = toolCalls;
// A reply cut off at a token limit may hold only some of its calls.
if (generationResult.reachedTokenLimit) {
toolCallsCutOff = true;
} else {
pendingToolCalls = toolCalls;
}
}
}
}
Expand All @@ -2284,6 +2291,11 @@ class ChatProvider extends ChangeNotifier {
}

_removeEmptyAssistantPlaceholder();
if (toolCallsCutOff) {
_addInfoMessage(
'The reply reached the token limit, so its tool calls were not run. Raise Max generated tokens and send it again.',
);
}
} catch (e) {
if (!_generationContextMatches(context)) {
return;
Expand Down Expand Up @@ -4449,10 +4461,17 @@ class ChatProvider extends ChangeNotifier {
}

void _updateToolTemplateSupport(Map<String, String> metadata) {
// This app runs the model's calls automatically, which needs the
// truncation report LiteRT-LM Web lacks (#919).
// This app runs the model's calls itself, so it needs a reply cut off at
// a token limit reported; LiteRT-LM Web reports it only on runtimes that
// pass its load probe (#919).
final backend = _chatService.engine.backend;
final unreportedTruncation =
kIsWeb && _engineCapabilities.runtime == LlamaRuntime.liteRtLm;
kIsWeb &&
_engineCapabilities.runtime == LlamaRuntime.liteRtLm &&
(backend is! BackendGenerationLimitSupport ||
(backend as BackendGenerationLimitSupport)
.generationLimitUnsupportedReason !=
null);
if (!_engineCapabilities.supportsToolCalling || unreportedTruncation) {
_detectedChatFormat = ChatFormat.contentOnly;
_templateSupportsTools = false;
Expand Down
9 changes: 9 additions & 0 deletions example/chat_app/lib/services/chat_generation_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,17 @@ class GenerationStreamResult {
final int elapsedMs;
final int decodeElapsedMs;

/// Whether the reply ended at a token limit (finish reason `length`).
final bool reachedTokenLimit;

const GenerationStreamResult({
required this.fullResponse,
required this.fullThinking,
required this.generatedTokens,
required this.firstTokenLatencyMs,
required this.elapsedMs,
required this.decodeElapsedMs,
this.reachedTokenLimit = false,
});
}

Expand Down Expand Up @@ -113,6 +117,7 @@ class ChatGenerationService {
var cleanTarget = '';
var generatedTokens = 0;
var sawFirstToken = false;
var reachedTokenLimit = false;
int? firstTokenLatencyMs;

final effectiveNotifyIntervalMs = uiNotifyIntervalMs <= 0
Expand Down Expand Up @@ -252,6 +257,9 @@ class ChatGenerationService {

final content = chunk.text;
final thinking = thinkingEnabled ? chunk.thinking : '';
if (chunk.choices.firstOrNull?.finishReason == 'length') {
reachedTokenLimit = true;
}

if (!sawFirstToken &&
(content.isNotEmpty ||
Expand Down Expand Up @@ -344,6 +352,7 @@ class ChatGenerationService {
firstTokenLatencyMs: firstTokenLatencyMs,
elapsedMs: streamElapsedMs,
decodeElapsedMs: decodeElapsedMs,
reachedTokenLimit: reachedTokenLimit,
);
}

Expand Down
4 changes: 2 additions & 2 deletions example/chat_app/test/mocks.dart
Original file line number Diff line number Diff line change
Expand Up @@ -235,9 +235,9 @@ class MockLlamaEngine extends LlamaEngine {
supportsStreamBatching: true,
);

MockLlamaEngine()
MockLlamaEngine({MockLlamaBackend? backend})
: super(
MockLlamaBackend(),
backend ?? MockLlamaBackend(),
modelDownloadManager: FakeModelDownloadManager(),
);

Expand Down
113 changes: 96 additions & 17 deletions example/chat_app/test/unit_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -523,8 +523,8 @@ void main() {
},
);

test('loadModel keeps tools off for LiteRT-LM Web tool calling, which '
'reports no truncation', () async {
test('loadModel turns tools on for LiteRT-LM Web tool calling once its '
'runtime reports truncation', () async {
final initialSettings = const ChatSettings(
modelPath: 'https://example.com/gemma-4-web.litertlm',
toolsEnabled: true,
Expand All @@ -534,9 +534,9 @@ void main() {
engine:
_MetadataEngine(const {
'general.architecture': 'litert-lm',
'tokenizer.chat_template':
'{% for message in messages %}{% if loop.last %}{{ message["content"] }}{% endif %}{% endfor %}',
})
'llamadart.chat_template.parsing':
'<tool_call>{% for message in messages %}{{ message["content"] }}{% endfor %}',
}, backend: _LimitReportingBackend(null))
..loadedCapabilities = const LlamaEngineCapabilities(
isSupported: true,
runtime: LlamaRuntime.liteRtLm,
Expand All @@ -552,18 +552,55 @@ void main() {

await provider.loadModel();

expect(provider.templateSupportsTools, isFalse);
expect(provider.settings.toolsEnabled, isFalse);
expect(
provider.messages.map((message) => message.text),
contains(
kIsWeb
? contains('runs tool calls automatically')
: contains('template is content-only'),
),
);
expect(provider.templateSupportsTools, isTrue);
expect(provider.settings.toolsEnabled, isTrue);
});

for (final (name, backend) in [
('has no truncation report', MockLlamaBackend()),
('reports no truncation', _LimitReportingBackend('No token counts.')),
]) {
test('loadModel keeps tools off on the Web for LiteRT-LM tool calling '
'whose runtime $name', () async {
final initialSettings = const ChatSettings(
modelPath: 'https://example.com/gemma-4-web.litertlm',
toolsEnabled: true,
);
final provider = ChatProvider(
chatService: MockChatService(
engine:
_MetadataEngine(const {
'general.architecture': 'litert-lm',
'llamadart.chat_template.parsing':
'<tool_call>{% for message in messages %}{{ message["content"] }}{% endfor %}',
}, backend: backend)
..loadedCapabilities = const LlamaEngineCapabilities(
isSupported: true,
runtime: LlamaRuntime.liteRtLm,
supportsMultiTurnChat: true,
supportsToolCalling: true,
),
),
settingsService: MockSettingsService()..settings = initialSettings,
enableWebModelPrefetch: false,
initialSettings: initialSettings,
);
addTearDown(provider.dispose);

await provider.loadModel();

// Native LiteRT-LM keeps tools on.
expect(provider.templateSupportsTools, !kIsWeb);
expect(provider.settings.toolsEnabled, !kIsWeb);
if (kIsWeb) {
expect(
provider.messages.map((message) => message.text),
contains(contains('runs tool calls automatically')),
);
}
});
}

test(
'loadModel detects tool support from the LiteRT-LM parsing template',
() async {
Expand Down Expand Up @@ -601,7 +638,7 @@ void main() {
expect(provider.templateSupportsTools, isTrue);
expect(provider.settings.toolsEnabled, isTrue);
},
// Native LiteRT-LM: on the Web the app keeps tools off (#919).
// On the Web the app needs the runtime's truncation report (#919).
testOn: 'vm',
);

Expand Down Expand Up @@ -1624,6 +1661,34 @@ void main() {
expect(singlePassProvider.messages.last.text, 'It is sunny in Seoul.');
});

test('does not run the tool calls of a reply cut off at the token '
'limit', () async {
final engine = _SinglePassToolCallEngine(callFinishReason: 'length');
final cutOffProvider = ChatProvider(
chatService: MockChatService(engine: engine),
settingsService: mockSettingsService,
initialSettings: const ChatSettings(modelPath: 'test_model.gguf'),
);

await cutOffProvider.loadModel();
cutOffProvider.updateToolsEnabled(true);
cutOffProvider.resetToolDeclarations();

await cutOffProvider.sendMessage('what time is it?');

expect(engine.createCallCount, 1);
expect(
cutOffProvider.messages.expand(
(m) => m.parts?.whereType<LlamaToolResultContent>() ?? const [],
),
isEmpty,
);
expect(
cutOffProvider.messages.last.text,
contains('reached the token limit, so its tool calls were not run'),
);
});

test(
'parses FunctionGemma tool-call text into structured tool parts',
() async {
Expand Down Expand Up @@ -2676,7 +2741,7 @@ void main() {
class _MetadataEngine extends MockLlamaEngine {
final Map<String, String> metadata;

_MetadataEngine(this.metadata);
_MetadataEngine(this.metadata, {super.backend});

@override
Future<Map<String, String>> getMetadata() async => metadata;
Expand Down Expand Up @@ -2818,6 +2883,10 @@ class _ToolCaptureEngine extends MockLlamaEngine {
}

class _SinglePassToolCallEngine extends MockLlamaEngine {
_SinglePassToolCallEngine({this.callFinishReason});

/// The finish reason of the reply that carries the call.
final String? callFinishReason;
int createCallCount = 0;

@override
Expand Down Expand Up @@ -2872,12 +2941,22 @@ class _SinglePassToolCallEngine extends MockLlamaEngine {
),
],
),
finishReason: callFinishReason,
),
],
);
}
}

/// A backend whose runtime reports, or cannot report, token-limit truncation.
class _LimitReportingBackend extends MockLlamaBackend
implements BackendGenerationLimitSupport {
_LimitReportingBackend(this.generationLimitUnsupportedReason);

@override
final String? generationLimitUnsupportedReason;
}

class _ThinkingControlCaptureEngine extends MockLlamaEngine {
GenerationParams? lastParams;
bool? lastEnableThinking;
Expand Down
Loading
Loading