From fbfb6d3c9de5fd4c46310f18d8ccaef9b4a3feab Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 15 Oct 2026 05:50:36 -0400 Subject: [PATCH] test: cover speech, smoke and tool-loop gaps; positional image checksum error - STT capabilities report a disposed attached LlamaEngine (#924 item 3) - Chrome TTS failed-task case and litert_lm_asr_smoke subprocess tests (#924 items 1, 2) - Dartdoc: await or handle task.result immediately (#924 item 5) - Document addMessage-override messages on rollback; implements-ChatSession _appended test (#892 items 2, 3) - rolledBack Dartdoc/guide: resend after truncated (#907 item 2) - Image checksum mismatch names the main file by position (#907 item 3) - Cancel-over-truncation tool-loop test (#907 item 4, M05) --- CHANGELOG.md | 9 ++ .../core/engine/chat_session_tool_loop.dart | 14 +- .../core/image/image_generation_engine.dart | 37 +++-- lib/src/core/speech/speech_to_text.dart | 12 +- lib/src/core/speech/text_to_speech.dart | 4 +- .../engine/chat_session_tool_loop_test.dart | 65 ++++++++ .../image_generation_engine_io_test.dart | 82 +++++++++++ .../image/image_generation_engine_test.dart | 56 +++++++ .../unit/core/speech/speech_to_text_test.dart | 30 ++++ .../core/speech/text_to_speech_web_test.dart | 34 +++++ .../tooling/litert_lm_asr_smoke_test.dart | 139 ++++++++++++++++++ website/docs/changelog/recent-releases.md | 9 ++ website/docs/guides/tool-calling.md | 10 +- 13 files changed, 484 insertions(+), 17 deletions(-) create mode 100644 test/unit/core/image/image_generation_engine_io_test.dart create mode 100644 test/unit/tooling/litert_lm_asr_smoke_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 4adfb52c0..920802d70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +## Unreleased + +- An attached `SpeechToTextEngine` whose `LlamaEngine` was disposed now + reports the disposed engine, instead of asking to load a model + ([#924](https://github.com/leehack/llamadart/issues/924)). +- A `ModelLoadOptions.sha256` mismatch in `ImageGenerationEngine.load` names + the main file by position, not by its local path or URL + ([#907](https://github.com/leehack/llamadart/issues/907)). + ## 0.12.2 - Pair this release with Apple companions `llamadart_llama_cpp_flutter` diff --git a/lib/src/core/engine/chat_session_tool_loop.dart b/lib/src/core/engine/chat_session_tool_loop.dart index 5111536c3..5a16846b6 100644 --- a/lib/src/core/engine/chat_session_tool_loop.dart +++ b/lib/src/core/engine/chat_session_tool_loop.dart @@ -115,7 +115,10 @@ class LlamaToolLoopResult { /// /// To resume a rolled-back turn, add [messages] back with /// `ChatSession.addMessage`, answer [pendingToolCalls], and call - /// `completeWithTools(const [], ...)`. + /// `completeWithTools(const [], ...)`. After + /// [LlamaToolLoopStopReason.truncated], raise `maxTokens` and send the + /// turn again instead: [messages] ends with the partial reply, and + /// templates such as Ministral 3's can reject the next user turn after it. final bool rolledBack; /// Creates a tool loop result. @@ -236,8 +239,13 @@ extension ChatSessionToolLoopExtension on ChatSession { /// [LlamaToolLoopResult.rolledBack]. /// For empty [parts] that is the open turn being continued, including the /// messages added before this call, such as the app's tool results. - /// Messages that other callers added meanwhile stay. Older turns that - /// context trimming dropped stay dropped, as after [ChatSession.create]. + /// Messages that other callers added meanwhile stay. Messages that a + /// [ChatSession.addMessage] override appends while the loop adds a + /// message, including those a synchronous listener adds from inside the + /// override, belong to the turn: a rollback removes them too, and they are + /// neither in [LlamaToolLoopResult.messages] nor reported to + /// [onMessageAdded]. Older turns that context trimming dropped stay + /// dropped, as after [ChatSession.create]. /// [LlamaToolLoopResult.rolledBack] reports a rollback, /// [LlamaToolLoopResult.messages] keeps the turn, and [onMessageAdded] has /// already reported the messages this call added. diff --git a/lib/src/core/image/image_generation_engine.dart b/lib/src/core/image/image_generation_engine.dart index ab4bc9d3a..70f28fc82 100644 --- a/lib/src/core/image/image_generation_engine.dart +++ b/lib/src/core/image/image_generation_engine.dart @@ -96,7 +96,9 @@ class ImageGenerationTask { /// The generated images. /// /// Throws the task's [LlamaException] when it fails, and - /// [LlamaStateException] when it is cancelled. + /// [LlamaStateException] when it is cancelled. Await this future or attach + /// an error handler as soon as you read it: a stored future that fails + /// before it has a handler reports an uncaught async error. Future get result => _result; late final Future _result = done.then( @@ -407,15 +409,30 @@ class ImageGenerationEngine { }; final effectiveStore = store ?? ModelFileStore(); - final paths = await resolveModelSourceFiles( - sources, - store: effectiveStore, - download: download, - onProgress: onProgress, - operation: 'Image model loading', - knownSizes: knownSizes, - assetType: 'image model', - ); + final List paths; + try { + paths = await resolveModelSourceFiles( + sources, + store: effectiveStore, + download: download, + onProgress: onProgress, + operation: 'Image model loading', + knownSizes: knownSizes, + assetType: 'image model', + ); + } on LlamaModelException catch (error) { + // The download manager names a local file by its path; image errors + // name files by position. ModelLoadOptions.sha256 applies only to a + // single (main) file. + if (download.sha256 == null || + !error.message.startsWith('Checksum mismatch')) { + rethrow; + } + throw LlamaModelException( + 'Checksum mismatch for ${describeImageModelFile(0)}: its SHA-256 ' + 'does not match ModelLoadOptions.sha256.', + ); + } void throwIfCancelled() { if (download.cancelToken?.isCancelled ?? false) { throw LlamaStateException('Image model loading was cancelled.'); diff --git a/lib/src/core/speech/speech_to_text.dart b/lib/src/core/speech/speech_to_text.dart index 40c621072..5f7a0ff7a 100644 --- a/lib/src/core/speech/speech_to_text.dart +++ b/lib/src/core/speech/speech_to_text.dart @@ -469,7 +469,9 @@ class SpeechToTextTask { /// The final transcript. /// /// Throws the task's [LlamaException] when it fails, and - /// [LlamaStateException] when it is cancelled. + /// [LlamaStateException] when it is cancelled. Await this future or attach + /// an error handler as soon as you read it: a stored future that fails + /// before it has a handler reports an uncaught async error. Future get result => _result; late final Future _result = done.then( @@ -933,6 +935,14 @@ class SpeechToTextEngine { } final engine = _engine!; + if (engine.isDisposed) { + return const SpeechToTextCapabilities( + isSupported: false, + unsupportedReason: + 'The attached LlamaEngine is disposed. Create a new LlamaEngine ' + 'and attach a new SpeechToTextEngine.', + ); + } if (speechToTextRequiresBackendCapability) { final backend = engine.backend; final speechBackend = backend is BackendPromptSpeechToTextSupport diff --git a/lib/src/core/speech/text_to_speech.dart b/lib/src/core/speech/text_to_speech.dart index e3263bdeb..b4200f05c 100644 --- a/lib/src/core/speech/text_to_speech.dart +++ b/lib/src/core/speech/text_to_speech.dart @@ -373,7 +373,9 @@ class TextToSpeechTask { /// The complete synthesized audio. /// /// Throws the task's [LlamaException] when it fails, and - /// [LlamaStateException] when it is cancelled. + /// [LlamaStateException] when it is cancelled. Await this future or attach + /// an error handler as soon as you read it: a stored future that fails + /// before it has a handler reports an uncaught async error. Future get result => _result; late final Future _result = done.then( diff --git a/test/unit/core/engine/chat_session_tool_loop_test.dart b/test/unit/core/engine/chat_session_tool_loop_test.dart index c47585ab7..27135756e 100644 --- a/test/unit/core/engine/chat_session_tool_loop_test.dart +++ b/test/unit/core/engine/chat_session_tool_loop_test.dart @@ -998,6 +998,38 @@ void main() { expect(session.history.last.content, 'Sunny'); }); + test('takes precedence over a cut-off reply and rolls it back', () async { + final earlier = [ + _text(LlamaChatRole.user, 'Hi'), + _text(LlamaChatRole.assistant, 'Hello'), + ]; + earlier.forEach(session.addMessage); + engine.replies + ..add(scriptedCalls([('a', 'weather', '{}')])) + ..add(() async* { + engine.cancelGeneration(); + yield scriptedChunk(content: 'It is sun', finishReason: 'length'); + }); + + final result = await session.sendWithTools( + 'Weather', + tools: [_tool('weather', (_) async => 'sunny')], + ); + + expect(result.stopReason, LlamaToolLoopStopReason.cancelled); + expect(result.completion.finishReason, LlamaFinishReason.length); + expect(result.text, 'It is sun'); + expect(result.rounds, 1); + expect(result.rolledBack, isTrue); + expect(session.history, orderedEquals(earlier)); + expect(_roles(result.messages), [ + LlamaChatRole.user, + LlamaChatRole.assistant, + LlamaChatRole.tool, + LlamaChatRole.assistant, + ]); + }); + test('reported as a stream error keeps a partial answer', () async { engine.replies ..add(scriptedCalls([('a', 'weather', '{}')])) @@ -1325,6 +1357,39 @@ void main() { expect(session.systemPrompt, 'Be brief.'); }); + test('a class that implements ChatSession over an addMessage that stores ' + 'copies rolls the copies back', () async { + final copying = _CopyingSession(engine); + [ + _text(LlamaChatRole.user, 'Hi'), + _text(LlamaChatRole.assistant, 'Hello'), + ].forEach(copying.addMessage); + final delegate = _DelegatingSession(copying); + engine.replies + ..add(scriptedCalls([('a', 'weather', '{}')])) + ..add(scriptedCalls([('b', 'weather', '{}')])); + + final result = await delegate.sendWithTools( + 'Weather', + tools: [_tool('weather', (_) async => 'sunny')], + maxRounds: 1, + ); + + expect(result.stopReason, LlamaToolLoopStopReason.maxRounds); + expect(result.rolledBack, isTrue); + expect(_roles(result.messages), [ + LlamaChatRole.user, + LlamaChatRole.assistant, + LlamaChatRole.tool, + LlamaChatRole.assistant, + ]); + expect(_toolResults(copying), isEmpty); + expect( + [for (final message in copying.history) message.content], + ['Hi', 'Hello'], + ); + }); + test('completeWithTools sends media parts as the user turn', () async { engine.replies.add(scriptedAnswer('A cat.')); diff --git a/test/unit/core/image/image_generation_engine_io_test.dart b/test/unit/core/image/image_generation_engine_io_test.dart new file mode 100644 index 000000000..b6710da66 --- /dev/null +++ b/test/unit/core/image/image_generation_engine_io_test.dart @@ -0,0 +1,82 @@ +@TestOn('vm') +library; + +import 'dart:io'; + +import 'package:llamadart/llamadart.dart'; +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_runtime_status.dart'; +import 'package:llamadart/src/core/image/image_generation_driver.dart'; +import 'package:path/path.dart' as p; +import 'package:test/test.dart'; + +void main() { + late Directory directory; + + setUp(() { + directory = Directory.systemTemp.createTempSync('llamadart_image_io_'); + debugImageGenerationDriverOverride = _ProbeOnlyDriver(); + }); + tearDown(() { + debugImageGenerationDriverOverride = null; + directory.deleteSync(recursive: true); + }); + + test('the default download manager\'s local checksum mismatch names the ' + 'main file by position, not by path', () async { + final secretDirectory = Directory(p.join(directory.path, 'secret-user')) + ..createSync(); + final model = File(p.join(secretDirectory.path, 'private-sd.gguf')) + ..writeAsStringSync('weights'); + + await expectLater( + ImageGenerationEngine.load( + ImageGenerationModel(ModelSource.path(model.path)), + download: ModelLoadOptions(sha256: '0' * 64), + store: ModelFileStore( + downloadManager: DefaultModelDownloadManager.appPrivate( + cacheDirectory: p.join(directory.path, 'cache'), + ), + ), + ), + throwsA( + isA().having( + (error) => '$error', + 'toString', + allOf( + contains( + 'Checksum mismatch for the main file: its SHA-256 does not ' + 'match ModelLoadOptions.sha256.', + ), + isNot(contains('secret-user')), + isNot(contains('private-sd')), + isNot(contains(directory.path)), + ), + ), + ), + ); + }); +} + +/// A driver that only probes and sizes files; nothing reaches the runtime. +final class _ProbeOnlyDriver implements ImageGenerationDriver { + @override + String get operatingSystem => 'linux'; + + @override + Future probeInBackground() async => + StableDiffusionRuntimeStatus.available( + version: 'master-929', + commit: '3f8527a', + devices: parseStableDiffusionDeviceList('CPU\tHost\n'), + ); + + @override + int? fileSize(String path) { + final file = File(path); + return file.existsSync() ? file.lengthSync() : null; + } + + @override + dynamic noSuchMethod(Invocation invocation) => + throw UnimplementedError('${invocation.memberName}'); +} diff --git a/test/unit/core/image/image_generation_engine_test.dart b/test/unit/core/image/image_generation_engine_test.dart index 5cc7548b8..da7779c34 100644 --- a/test/unit/core/image/image_generation_engine_test.dart +++ b/test/unit/core/image/image_generation_engine_test.dart @@ -1036,6 +1036,56 @@ void main() { }); } + for (final (name, source, message) in [ + ( + 'local', + _local(_model), + 'Checksum mismatch for local model file: $_model.', + ), + ( + 'remote', + _remote, + 'Checksum mismatch for hf://owner/sdxs@0123abc/sdxs.gguf.', + ), + ]) { + test('a checksum mismatch for a single $name file names it by ' + 'position', () async { + downloads.checksumError = LlamaModelException(message); + + await expectLater( + load(_sdxs(source), download: ModelLoadOptions(sha256: 'a' * 64)), + throwsA( + isA().having( + (error) => error.message, + 'message', + allOf( + equals( + 'Checksum mismatch for the main file: its SHA-256 does not ' + 'match ModelLoadOptions.sha256.', + ), + isNot(contains('sdxs')), + isNot(contains('/models')), + ), + ), + ), + ); + expect(driver.started, isEmpty); + }); + } + + test( + 'another model error from a checksummed load passes through', + () async { + final failure = LlamaModelException('Local model file does not exist.'); + downloads.checksumError = failure; + + await expectLater( + load(_sdxs(), download: ModelLoadOptions(sha256: 'a' * 64)), + throwsA(same(failure)), + ); + }, + ); + test('a checksum for several files is rejected before anything ' 'downloads', () async { await expectLater( @@ -2087,6 +2137,9 @@ final class _FakeDownloads implements ModelDownloadManager { /// a checkpoint and `.safetensors` files to a TAESD. final Map remoteHeaders = {}; Object? error; + + /// Thrown for any file when the load sets [ModelLoadOptions.sha256]. + Object? checksumError; Completer? gate; static String cachePath(ModelSource source) => @@ -2099,6 +2152,9 @@ final class _FakeDownloads implements ModelDownloadManager { ModelDownloadProgressCallback? onProgress, }) async { calls.add((source, options)); + if (options.sha256 != null && checksumError != null) { + throw checksumError!; + } final path = source.isLocal ? source.path! : cachePath(source); if (!source.isLocal) { final failure = error; diff --git a/test/unit/core/speech/speech_to_text_test.dart b/test/unit/core/speech/speech_to_text_test.dart index f844a8335..2ae8af571 100644 --- a/test/unit/core/speech/speech_to_text_test.dart +++ b/test/unit/core/speech/speech_to_text_test.dart @@ -36,6 +36,36 @@ void main() { expect(capabilities.unsupportedReason, contains('Load a model')); }); + test( + 'reports a disposed attached LlamaEngine, not a missing model', + () async { + await _loadSpeechModel(llamaEngine); + await llamaEngine.dispose(); + + final capabilities = await speechEngine.capabilities; + expect(capabilities.isSupported, isFalse); + expect( + capabilities.unsupportedReason, + 'The attached LlamaEngine is disposed. Create a new LlamaEngine and ' + 'attach a new SpeechToTextEngine.', + ); + await expectLater( + speechEngine.transcribe( + const SpeechToTextRequest( + audio: SpeechAudioFileInput('/tmp/a.wav'), + ), + ), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('The attached LlamaEngine is disposed.'), + ), + ), + ); + }, + ); + test('reports exact first-backend capabilities', () async { await _loadSpeechModel(llamaEngine); diff --git a/test/unit/core/speech/text_to_speech_web_test.dart b/test/unit/core/speech/text_to_speech_web_test.dart index e04c8b7c9..e998f11d2 100644 --- a/test/unit/core/speech/text_to_speech_web_test.dart +++ b/test/unit/core/speech/text_to_speech_web_test.dart @@ -49,6 +49,37 @@ void main() { expect(backend.lastRequest?.speakerAudioBytes, isNotEmpty); }); + test('typed text-to-speech reports a Web synthesis failure through done ' + 'and result, not events', () async { + final backend = _WebBackend()..synthesisError = StateError('bridge failed'); + final engine = LlamaEngine(backend); + addTearDown(engine.dispose); + await engine.loadModelFromUrl('https://example.com/qwen3-tts.gguf'); + await engine.loadMultimodalProjector( + 'https://example.com/qwen3-tts-mmproj.gguf', + ); + final speechEngine = TextToSpeechEngine.attach( + engine, + adapter: const Qwen3TtsAdapter(), + ); + + final task = await speechEngine.synthesize( + const TextToSpeechRequest(text: 'Fail on Web.'), + ); + + expect(await task.events.toList(), isEmpty); + final completion = await task.done; + expect(completion.state, TextToSpeechCompletionState.failed); + expect(completion.error, isA()); + await expectLater(task.result, throwsA(same(completion.error))); + + backend.synthesisError = null; + final retry = await speechEngine.synthesize( + const TextToSpeechRequest(text: 'Retry on Web.'), + ); + expect((await retry.done).state, TextToSpeechCompletionState.completed); + }); + test('load reports the Web model fetch from 0 to 0.5', () async { final backend = _WebBackend(); final progress = []; @@ -97,6 +128,7 @@ void main() { class _WebBackend implements LlamaBackend, BackendTextToSpeech { bool _ready = false; BackendTextToSpeechRequest? lastRequest; + Object? synthesisError; String? modelUrl; String? projectorUrl; @@ -168,6 +200,8 @@ class _WebBackend implements LlamaBackend, BackendTextToSpeech { void Function(BackendTextToSpeechProgress progress)? onProgress, }) async { lastRequest = request; + final error = synthesisError; + if (error != null) throw error; return BackendTextToSpeechResult( samples: Float32List.fromList([0.25, -0.25]), sampleRateHz: 24000, diff --git a/test/unit/tooling/litert_lm_asr_smoke_test.dart b/test/unit/tooling/litert_lm_asr_smoke_test.dart new file mode 100644 index 000000000..8644881a0 --- /dev/null +++ b/test/unit/tooling/litert_lm_asr_smoke_test.dart @@ -0,0 +1,139 @@ +@TestOn('vm') +library; + +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:path/path.dart' as path; +import 'package:test/test.dart'; + +void main() { + late Directory directory; + late String modelPath; + late String tokenizerPath; + + setUp(() { + directory = Directory.systemTemp.createTempSync('litert_asr_smoke_'); + modelPath = path.join(directory.path, 'model.tflite'); + tokenizerPath = path.join(directory.path, 'tokenizer.json'); + }); + tearDown(() => directory.deleteSync(recursive: true)); + + String writeWav( + String name, { + int sampleRateHz = 16000, + int channels = 1, + int? declaredDataLength, + }) { + const pcmLength = 320; + final bytes = ByteData(44 + pcmLength); + void ascii(int offset, String value) { + for (var index = 0; index < value.length; index++) { + bytes.setUint8(offset + index, value.codeUnitAt(index)); + } + } + + ascii(0, 'RIFF'); + bytes.setUint32(4, 36 + pcmLength, Endian.little); + ascii(8, 'WAVE'); + ascii(12, 'fmt '); + bytes.setUint32(16, 16, Endian.little); + bytes.setUint16(20, 1, Endian.little); + bytes.setUint16(22, channels, Endian.little); + bytes.setUint32(24, sampleRateHz, Endian.little); + bytes.setUint32(28, sampleRateHz * channels * 2, Endian.little); + bytes.setUint16(32, channels * 2, Endian.little); + bytes.setUint16(34, 16, Endian.little); + ascii(36, 'data'); + bytes.setUint32(40, declaredDataLength ?? pcmLength, Endian.little); + final file = File(path.join(directory.path, name)) + ..writeAsBytesSync(bytes.buffer.asUint8List()); + return file.path; + } + + Future runSmoke(List args) => Process.run( + Platform.resolvedExecutable, + ['--disable-dart-dev', 'tool/litert_lm_asr_smoke.dart', ...args], + ); + + test('prints usage and exits 64 with fewer than five arguments', () async { + final result = await runSmoke([modelPath, tokenizerPath]); + + expect(result.exitCode, 64, reason: '${result.stderr}'); + expect( + result.stderr, + contains( + 'Usage: dart run tool/litert_lm_asr_smoke.dart ' + ' ', + ), + ); + }); + + test('rejects an unsupported preset and an empty expectation', () async { + final wav = writeWav('ok.wav'); + + final preset = await runSmoke([ + modelPath, + tokenizerPath, + wav, + 'gemma-asr', + 'hello', + ]); + expect(preset.exitCode, isNot(0)); + expect(preset.stderr, contains('(preset): is not supported: "gemma-asr"')); + + final expected = await runSmoke([ + modelPath, + tokenizerPath, + wav, + 'moonshine-tiny', + ' ', + ]); + expect(expected.exitCode, isNot(0)); + expect(expected.stderr, contains('(expected): must not be empty')); + }); + + test('rejects audio that is not nonempty mono 16 kHz PCM16 WAV', () async { + final notWav = File(path.join(directory.path, 'audio.wav')) + ..writeAsBytesSync(List.filled(64, 0)); + final cases = { + notWav.path: 'ASR smoke fixture must be a RIFF/WAVE file.', + writeWav('8k.wav', sampleRateHz: 8000): + 'must contain nonempty mono 16 kHz PCM16 audio.', + writeWav('stereo.wav', channels: 2): + 'must contain nonempty mono 16 kHz PCM16 audio.', + writeWav('truncated.wav', declaredDataLength: 4096): + 'ASR smoke WAV contains a truncated chunk.', + }; + + for (final MapEntry(key: wav, value: message) in cases.entries) { + final result = await runSmoke([ + modelPath, + tokenizerPath, + wav, + 'whisper-tiny', + 'hello', + ]); + expect(result.exitCode, isNot(0), reason: wav); + expect(result.stderr, contains(message), reason: wav); + } + }); + + test('a valid WAV reaches SpeechToTextEngine.load', () async { + final result = await runSmoke([ + modelPath, + tokenizerPath, + writeWav('ok.wav'), + 'Parakeet-CTC', + 'hello', + ]); + + expect(result.exitCode, isNot(0)); + expect( + result.stderr, + contains('Local model file does not exist: $modelPath'), + ); + expect(result.stderr, contains('SpeechToTextEngine.load')); + expect(result.stdout, isNot(contains('RESULT litert_lm_asr'))); + }); +} diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 5669068ba..a23a29f96 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -7,6 +7,15 @@ For canonical full release notes, use: - [`CHANGELOG.md`](https://github.com/leehack/llamadart/blob/main/CHANGELOG.md) +## Unreleased + +- An attached `SpeechToTextEngine` whose `LlamaEngine` was disposed now + reports the disposed engine, instead of asking to load a model + ([#924](https://github.com/leehack/llamadart/issues/924)). +- A `ModelLoadOptions.sha256` mismatch in `ImageGenerationEngine.load` names + the main file by position, not by its local path or URL + ([#907](https://github.com/leehack/llamadart/issues/907)). + ## 0.12.2 - Pair this release with Apple companions `llamadart_llama_cpp_flutter` diff --git a/website/docs/guides/tool-calling.md b/website/docs/guides/tool-calling.md index 779d17f75..14f3c9bd4 100644 --- a/website/docs/guides/tool-calling.md +++ b/website/docs/guides/tool-calling.md @@ -124,7 +124,10 @@ which some templates, such as Ministral 3's and Mistral Small 3.2's, cannot render before a new user turn. `completeWithTools(const [], ...)` continues the open turn, so its rollback also removes that turn's earlier messages, including the tool results you added. Messages that other code added during -the loop stay. Older turns that context trimming dropped stay dropped, as +the loop stay, except those an `addMessage` override appends while the loop +adds a message (or that a listener adds from inside that override): the +rollback removes them with the turn, and they are neither in +`result.messages` nor reported to `onMessageAdded`. Older turns that context trimming dropped stay dropped, as after `create`. A rollback edits the history without calling `addMessage` or `reset`, so a `ChatSession` subclass that mirrors the history should check `result.rolledBack`. @@ -134,7 +137,10 @@ their side effects: `result.messages` holds every message of the turn, including their results, and `onMessageAdded` has already reported the ones the call added. To resume a rolled-back turn, add `result.messages` back, answer `result.pendingToolCalls`, and call -`completeWithTools(const [], tools: ...)`. +`completeWithTools(const [], tools: ...)`. After `truncated`, raise +`maxTokens` and send the turn again instead: `result.messages` ends with the +partial reply, and templates such as Ministral 3's can reject the next user +turn after it. On WebGPU a cancel ends generation with a stream error; the loop still reports it as `cancelled`.