diff --git a/example/chat_app/lib/services/chat_generation_service.dart b/example/chat_app/lib/services/chat_generation_service.dart index 58ad32209..3e573a640 100644 --- a/example/chat_app/lib/services/chat_generation_service.dart +++ b/example/chat_app/lib/services/chat_generation_service.dart @@ -257,8 +257,18 @@ class ChatGenerationService { fullThinking += thinking .replaceAll(r'\n', '\n') .replaceAll(r'\r', '\r'); - generatedTokens++; - pendingTokenDelta += 1; + // The whitespace that ends a reply arrives as a chunk of its own + // after the text; counting it would raise this chunk-count fallback + // by one for the same reply. + final isWhitespaceOnly = + content.isNotEmpty && + content.trim().isEmpty && + thinking.trim().isEmpty && + chunk.toolCalls.isEmpty; + if (!isWhitespaceOnly) { + generatedTokens++; + pendingTokenDelta += 1; + } cleanTarget = cleanResponse(fullResponse); if (visibleCleanText.isEmpty && cleanTarget.isNotEmpty) { diff --git a/example/chat_app/test/chat_generation_service_test.dart b/example/chat_app/test/chat_generation_service_test.dart index 1e8147c30..f6e4a5482 100644 --- a/example/chat_app/test/chat_generation_service_test.dart +++ b/example/chat_app/test/chat_generation_service_test.dart @@ -156,6 +156,32 @@ void main() { expect(updates.last.shouldNotify, isTrue); }); + test('does not count the whitespace chunk that ends a reply', () async { + final updates = []; + final result = await service.consumeStream( + stream: Stream.fromIterable( + [ + _chunk(content: '4'), + _chunk(content: '\n'), + _chunk(), + ], + ), + thinkingEnabled: true, + uiNotifyIntervalMs: -1, + cleanResponse: (value) => value, + shouldContinue: () => true, + onUpdate: updates.add, + ); + + expect(result.fullResponse, '4\n'); + expect(updates.last.cleanText, '4\n'); + expect(result.generatedTokens, 2); + expect( + updates.fold(0, (sum, update) => sum + update.generatedTokenDelta), + 2, + ); + }); + test('smooths large streamed chunks and flushes final text', () async { final longChunk = List.filled(260, 'x').join(); final updates = []; diff --git a/example/llamadart_cli/lib/src/chat_runner.dart b/example/llamadart_cli/lib/src/chat_runner.dart index 32df4bcad..8f6a2157e 100644 --- a/example/llamadart_cli/lib/src/chat_runner.dart +++ b/example/llamadart_cli/lib/src/chat_runner.dart @@ -16,6 +16,7 @@ class LlamaCliRunner { final LlamaCliConfig config; final ModelLocator _modelLocator; + final LlamaEngine? _injectedEngine; final List _history = []; LlamaEngine? _engine; @@ -30,8 +31,11 @@ class LlamaCliRunner { bool get _simpleIo => config.simpleIo; /// Creates a runner for one CLI invocation. - LlamaCliRunner(this.config) - : _modelLocator = ModelLocator(modelsDirectory: config.modelsDirectory); + /// + /// [engine] replaces the default llama.cpp engine, for tests. + LlamaCliRunner(this.config, {LlamaEngine? engine}) + : _modelLocator = ModelLocator(modelsDirectory: config.modelsDirectory), + _injectedEngine = engine; /// Starts model resolution, loading, and chat mode. Future run() async { @@ -44,8 +48,7 @@ class LlamaCliRunner { ); _loadedModelPath = modelPath; - final backend = LlamaBackend(); - final engine = LlamaEngine(backend); + final engine = _injectedEngine ?? LlamaEngine(LlamaBackend()); _engine = engine; await LlamaLogging.configure(nativeLevel: LlamaLogLevel.warn); @@ -265,6 +268,10 @@ class LlamaCliRunner { final assistantText = StringBuffer(); final assistantThinking = StringBuffer(); var printedThinkingStart = false; + // A reply keeps the whitespace the model ended it with. It is printed and + // stored only once more text follows, so the transcript and the next + // prompt do not gain it. + var heldWhitespace = ''; try { await for (final chunk in engine.create(messages, params: turnParams)) { final thinking = chunk.thinking; @@ -279,8 +286,13 @@ class LlamaCliRunner { final content = chunk.text; if (content.isNotEmpty) { - assistantText.write(content); - stdout.write(content); + final pending = heldWhitespace + content; + final visible = pending.trimRight(); + heldWhitespace = pending.substring(visible.length); + if (visible.isNotEmpty) { + assistantText.write(visible); + stdout.write(visible); + } } } stdout.writeln(); diff --git a/example/llamadart_cli/test/chat_runner_test.dart b/example/llamadart_cli/test/chat_runner_test.dart new file mode 100644 index 000000000..b6b631a35 --- /dev/null +++ b/example/llamadart_cli/test/chat_runner_test.dart @@ -0,0 +1,267 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:llamadart/llamadart.dart'; +import 'package:llamadart_cli_example/llamadart_cli.dart'; +import 'package:path/path.dart' as p; +import 'package:test/test.dart'; + +void main() { + late Directory tempDir; + late String modelPath; + + setUp(() async { + tempDir = await Directory.systemTemp.createTemp('llamadart_cli_runner_'); + modelPath = p.join(tempDir.path, 'model.gguf'); + await File(modelPath).writeAsBytes(const []); + }); + + tearDown(() async { + await tempDir.delete(recursive: true); + }); + + LlamaCliConfig configFor({required bool simpleIo}) => LlamaCliConfig( + showHelp: false, + modelPathOrUrl: modelPath, + modelsDirectory: tempDir.path, + interactive: true, + interactiveFirst: false, + contextSize: 4096, + gpuLayers: 0, + threads: 1, + threadsBatch: 1, + maxTokens: 8, + temperature: 0, + topK: 40, + topP: 0.95, + minP: 0.05, + repeatPenalty: 1, + fitContext: true, + jinja: true, + instruct: false, + simpleIo: simpleIo, + color: false, + reversePrompts: const [], + ); + + Future runPiped(_QueuedBackend backend, String input) async { + final output = _RecordingStdout(); + final runner = LlamaCliRunner( + configFor(simpleIo: true), + engine: LlamaEngine(backend), + ); + await IOOverrides.runZoned( + () async { + try { + await runner.run(); + } finally { + await runner.dispose(); + } + }, + stdout: () => output, + stdin: () => _PipedStdin(input), + ); + return output.text; + } + + test( + 'a reply ending in a newline is stored and printed without it', + () async { + final backend = _QueuedBackend() + ..queueResponse(['4', '\n']) + ..queueResponse(['6']); + + final transcript = await runPiped(backend, '2+2?\n3+3?\n'); + + expect(backend.prompts, hasLength(2)); + expect( + backend.prompts[1], + '<|im_start|>user\n2+2?<|im_end|>\n' + '<|im_start|>assistant\n4<|im_end|>\n' + '<|im_start|>user\n3+3?<|im_end|>\n' + '<|im_start|>assistant\n', + ); + expect(transcript, endsWith('> \n4\n\n> \n6\n\n\nExiting...\n')); + }, + ); + + test('whitespace inside a reply is printed and stored', () async { + final backend = _QueuedBackend() + ..queueResponse(['a', '\n\n', 'b ', ' ']) + ..queueResponse(['c']); + + final transcript = await runPiped(backend, 'one\ntwo\n'); + + expect(transcript, contains('> \na\n\nb\n\n> \nc\n\n')); + expect(backend.prompts[1], contains('assistant\na\n\nb<|im_end|>')); + }); +} + +class _QueuedBackend implements LlamaBackend { + final List> _responses = >[]; + final List prompts = []; + + void queueResponse(List chunks) => _responses.add(chunks); + + @override + bool get isReady => true; + + @override + Future modelLoad(String path, ModelParams params) async => 1; + + @override + Future modelLoadFromUrl( + String url, + ModelParams params, { + Function(double progress)? onProgress, + }) async => 1; + + @override + Future modelFree(int modelHandle) async {} + + @override + Future contextCreate(int modelHandle, ModelParams params) async => 1; + + @override + Future contextFree(int contextHandle) async {} + + @override + Future getContextSize(int contextHandle) async => 4096; + + @override + Stream> generate( + int contextHandle, + String prompt, + GenerationParams params, { + List? parts, + }) async* { + prompts.add(prompt); + for (final chunk in _responses.removeAt(0)) { + yield utf8.encode(chunk); + } + } + + @override + void cancelGeneration() {} + + @override + Future> tokenize( + int modelHandle, + String text, { + bool addSpecial = true, + }) async => List.filled(utf8.encode(text).length, 0); + + @override + Future detokenize( + int modelHandle, + List tokens, { + bool special = false, + }) async => ''; + + @override + Future> modelMetadata(int modelHandle) async => + { + 'tokenizer.chat_template': + '{% for message in messages %}' + "{{ '<|im_start|>' + message['role'] + '\\n' " + "+ message['content'] + '<|im_end|>' + '\\n' }}" + '{% endfor %}' + "{% if add_generation_prompt %}{{ '<|im_start|>assistant\\n' }}" + '{% endif %}', + }; + + @override + Future setLoraAdapter( + int contextHandle, + String path, + double scale, + ) async {} + + @override + Future removeLoraAdapter(int contextHandle, String path) async {} + + @override + Future clearLoraAdapters(int contextHandle) async {} + + @override + Future getBackendName() async => 'queued-test'; + + @override + bool get supportsUrlLoading => false; + + @override + Future isGpuSupported() async => false; + + @override + Future setLogLevel(LlamaLogLevel level) async {} + + @override + Future dispose() async {} + + @override + Future multimodalContextCreate( + int modelHandle, + String mmProjPath, + ) async => null; + + @override + Future multimodalContextFree(int mmContextHandle) async {} + + @override + Future supportsVision(int mmContextHandle) async => false; + + @override + Future supportsAudio(int mmContextHandle) async => false; + + @override + Future<({int total, int free})> getVramInfo() async => (total: 0, free: 0); + + @override + Future applyChatTemplate( + int modelHandle, + List> messages, { + String? customTemplate, + bool addAssistant = true, + }) async => ''; +} + +class _RecordingStdout implements Stdout { + final StringBuffer _buffer = StringBuffer(); + + String get text => _buffer.toString(); + + @override + void write(Object? object) => _buffer.write(object); + + @override + void writeln([Object? object = '']) => _buffer.writeln(object); + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +class _PipedStdin extends Stream> implements Stdin { + final String _input; + + _PipedStdin(this._input); + + @override + bool get hasTerminal => false; + + @override + StreamSubscription> listen( + void Function(List event)? onData, { + Function? onError, + void Function()? onDone, + bool? cancelOnError, + }) => Stream>.value(utf8.encode(_input)).listen( + onData, + onError: onError, + onDone: onDone, + cancelOnError: cancelOnError, + ); + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} diff --git a/example/tui_coding_agent/test/coding_agent_session_test.dart b/example/tui_coding_agent/test/coding_agent_session_test.dart index 82608340e..ca8ef4ca6 100644 --- a/example/tui_coding_agent/test/coding_agent_session_test.dart +++ b/example/tui_coding_agent/test/coding_agent_session_test.dart @@ -359,7 +359,7 @@ void main() { .where((event) => event.type == SessionEventType.assistantToken) .map((event) => event.message) .join(), - 'First ', + 'First', ); releaseGeneration.complete(); diff --git a/website/docs/guides/generation-and-streaming.md b/website/docs/guides/generation-and-streaming.md index 4abbe2bc1..cdc1c9b9b 100644 --- a/website/docs/guides/generation-and-streaming.md +++ b/website/docs/guides/generation-and-streaming.md @@ -117,7 +117,9 @@ messages.add(completion.message); // Assistant turn for the next request. `engine.complete(messages, ...)` is `engine.create(messages, ...).collect()`, and `session.send('...')` sends one text turn through a `ChatSession` and -collects the reply. +collects the reply. `completion.message` keeps the whitespace the model ended +the reply with; `ChatSession` stores the turn without it, so `trimRight()` the +text of a turn you keep yourself if the next prompt should not carry it. `finishReason` does not tell you that a generation was cancelled. On native llama.cpp and LiteRT-LM, a stream stopped by `engine.cancelGeneration()`,