diff --git a/CHANGELOG.md b/CHANGELOG.md index 4adfb52c0..97eca323f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,17 @@ +## Unreleased + +- A chat template that fails to render now names its source in the + `LlamaInferenceException` message: the model's `tokenizer.chat_template` + or its `tool_use` variant, `ModelParams.chatTemplate`, or `customTemplate` + ([#820](https://github.com/leehack/llamadart/issues/820)). +- A `ToolChoice.required` reply cut short by a cancel, or by `maxTokens` on + a backend that reports a token limit, no longer throws a raw + `StateError`; it ends with `stop` or `length` and no tool calls, as with + `ToolChoice.auto`. **Behavior change:** other output a PEG parser cannot + parse, including in `ChatTemplateEngine.parse`, throws + `LlamaInferenceException` instead of `StateError` + ([#890](https://github.com/leehack/llamadart/issues/890)). + ## 0.12.2 - Pair this release with Apple companions `llamadart_llama_cpp_flutter` diff --git a/lib/src/core/engine/chat_completion_stream_parser.dart b/lib/src/core/engine/chat_completion_stream_parser.dart index 6c8abc324..66b925850 100644 --- a/lib/src/core/engine/chat_completion_stream_parser.dart +++ b/lib/src/core/engine/chat_completion_stream_parser.dart @@ -1,11 +1,13 @@ import 'dart:async'; +import '../exceptions.dart'; import '../llama_logger.dart'; import '../models/chat/chat_template_result.dart'; import '../models/chat/completion_chunk.dart'; import '../models/inference/generation_usage.dart'; import '../models/tools/tool_definition.dart'; import '../template/chat_format.dart'; +import '../template/chat_parse_result.dart'; import '../template/chat_template_engine.dart'; import '../template/handlers/apertus_handler.dart'; import '../template/handlers/command_r7b_handler.dart'; @@ -77,6 +79,12 @@ class ChatCompletionStreamParser { /// the call set is not safe to execute. Otherwise parsed calls finish with /// `tool_calls`, and a reply without calls finishes with `stop`. /// The final chunk carries what [usage] returns after [tokenStream] ends. + /// + /// A reply that ended at a limit, or that [cancelled] reports cancelled, + /// may stop short of what a PEG parser requires, such as the tool call of + /// `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]. static Stream parse({ required Stream tokenStream, required LlamaChatTemplateResult templateResult, @@ -86,6 +94,7 @@ class ChatCompletionStreamParser { required String completionId, List? tools, bool Function()? stoppedAtLimit, + bool Function()? cancelled, LlamaGenerationUsage? Function()? usage, }) async* { final buffer = StringBuffer(); @@ -350,14 +359,26 @@ class ChatCompletionStreamParser { } final fullOutput = buffer.toString(); - final parsed = ChatTemplateEngine.parse( - templateResult.format, - fullOutput, - parseToolCalls: parseToolCallsEnabled, - thinkingForcedOpen: templateResult.thinkingForcedOpen, - parser: templateResult.parser, - tools: tools, - ); + final endedAtLimit = stoppedAtLimit?.call() == true; + ChatParseResult parseOutput({required bool isPartial}) => + ChatTemplateEngine.parse( + templateResult.format, + fullOutput, + isPartial: isPartial, + parseToolCalls: parseToolCallsEnabled, + thinkingForcedOpen: templateResult.thinkingForcedOpen, + parser: templateResult.parser, + tools: tools, + ); + ChatParseResult parsed; + var parsedAsPartial = false; + try { + parsed = parseOutput(isPartial: false); + } on LlamaInferenceException { + if (!endedAtLimit && cancelled?.call() != true) rethrow; + parsed = parseOutput(isPartial: true); + parsedAsPartial = true; + } final finalReasoning = parsed.reasoningContent ?? ''; final reasoningDelta = _computeFinalReconciliationDelta( @@ -403,8 +424,7 @@ class ChatCompletionStreamParser { 'toolCallCount=${parsed.toolCalls.length}', ); - final endedAtLimit = stoppedAtLimit?.call() == true; - if (parsed.hasToolCalls && !endedAtLimit) { + if (parsed.hasToolCalls && !endedAtLimit && !parsedAsPartial) { final toolCallsWithIds = parsed.toolCalls .map( (toolCall) => LlamaCompletionChunkToolCall( diff --git a/lib/src/core/engine/chat_template_renderer.dart b/lib/src/core/engine/chat_template_renderer.dart index 3b1dbcd37..63f2c7781 100644 --- a/lib/src/core/engine/chat_template_renderer.dart +++ b/lib/src/core/engine/chat_template_renderer.dart @@ -7,6 +7,7 @@ import '../models/inference/tool_choice.dart'; import '../models/tools/tool_definition.dart'; import '../template/chat_template_engine.dart'; import '../template/media_placeholders.dart'; +import '../template/template_internal_metadata.dart'; /// Loads model metadata for chat-template rendering. typedef ChatTemplateMetadataLoader = Future> Function(); @@ -32,6 +33,25 @@ class ChatTemplateRenderer { ), ); + /// Names the template [render] uses when no `tool_use` variant or + /// `customTemplate` applies, for render-failure messages. + /// + /// A non-empty [modelTemplate] is `ModelParams.chatTemplate`; otherwise + /// [metadataTemplate] is the model's `tokenizer.chat_template`, and without + /// it the built-in ChatML fallback is used. + static String templateSourceName({ + String? modelTemplate, + String? metadataTemplate, + }) { + if (modelTemplate != null && modelTemplate.isNotEmpty) { + return 'ModelParams.chatTemplate'; + } + if (metadataTemplate != null) { + return "the model's tokenizer.chat_template"; + } + return 'the built-in ChatML fallback template'; + } + /// Renders a chat template and optionally counts prompt tokens. /// /// A non-empty [modelTemplate] replaces the model's `tokenizer.chat_template` @@ -64,7 +84,7 @@ class ChatTemplateRenderer { }) async { Map metadata = {}; try { - metadata = await loadMetadata(); + metadata = {...await loadMetadata()}; } catch (error) { LlamaLogger.instance.warning('Failed to read metadata: $error'); } @@ -75,6 +95,10 @@ class ChatTemplateRenderer { } else { templateSource = metadata['tokenizer.chat_template']; } + metadata[internalTemplateSourceNameMetadataKey] = templateSourceName( + modelTemplate: modelTemplate, + metadataTemplate: metadata['tokenizer.chat_template'], + ); final effectiveResponseFormat = responseFormat ?? diff --git a/lib/src/core/engine/engine.dart b/lib/src/core/engine/engine.dart index be829b2df..720c41120 100644 --- a/lib/src/core/engine/engine.dart +++ b/lib/src/core/engine/engine.dart @@ -1707,6 +1707,7 @@ class LlamaEngine { completionId: completionId, tools: effectiveTools, stoppedAtLimit: () => generationLimit != null, + cancelled: request.isCancelled, usage: () => generationUsage, ).map((chunk) { final limit = generationLimit; diff --git a/lib/src/core/template/chat_template_engine.dart b/lib/src/core/template/chat_template_engine.dart index 70233e66a..3f7fcd222 100644 --- a/lib/src/core/template/chat_template_engine.dart +++ b/lib/src/core/template/chat_template_engine.dart @@ -125,7 +125,9 @@ class ChatTemplateEngine { /// any other shape throws `LlamaUnsupportedException`. /// /// A template that fails to render, by raising or through invalid syntax, - /// throws `LlamaInferenceException` with the template's message. + /// throws `LlamaInferenceException` with the template's message. The + /// message names the template: [customTemplate], the `tool_use` variant in + /// [metadata], or [templateSource]. /// /// [mediaMarker] is written where each image, audio or video part was. /// Pass one that message text cannot hold to tell the parts from a @@ -152,10 +154,13 @@ class ChatTemplateEngine { final allowToolCalls = hasTools && toolChoice != ToolChoice.none; final effectiveTools = allowToolCalls ? tools : null; var metadataTemplate = templateSource; + var templateName = + metadata[internalTemplateSourceNameMetadataKey] ?? 'templateSource'; if (allowToolCalls && metadata.containsKey('tokenizer.chat_template.tool_use')) { metadataTemplate = metadata['tokenizer.chat_template.tool_use']; + templateName = "the model's tokenizer.chat_template.tool_use"; LlamaLogger.instance.debug( 'ChatTemplateEngine: Using tool_use template variant', ); @@ -163,6 +168,7 @@ class ChatTemplateEngine { var effectiveTemplate = customTemplate; if (effectiveTemplate != null) { + templateName = 'customTemplate'; LlamaLogger.instance.debug( 'ChatTemplateEngine: Using per-call custom template override', ); @@ -279,6 +285,7 @@ class ChatTemplateEngine { 'for template that accesses content as list', ); var rendered = _renderTemplate( + templateName, () => handler.renderWithMultimodalContent( templateSource: effectiveTemplate ?? GenericHandler.chatMlTemplate, messages: effectiveMessages, @@ -326,6 +333,7 @@ class ChatTemplateEngine { } var baseResult = _renderTemplate( + templateName, () => handler.render( templateSource: effectiveTemplate ?? GenericHandler.chatMlTemplate, messages: effectiveMessages, @@ -353,9 +361,11 @@ class ChatTemplateEngine { /// Runs a handler [render], turning an [Exception] that is not already a /// [LlamaException] (a template's own `raise_exception`, a failure the /// Jinja runtime throws as an `Exception`, invalid template syntax) into a - /// [LlamaInferenceException]. An [Error] the renderer throws, such as an - /// integer division by zero or a stack overflow, is left as it is. + /// [LlamaInferenceException] that names the template by [templateName]. An + /// [Error] the renderer throws, such as an integer division by zero or a + /// stack overflow, is left as it is. static LlamaChatTemplateResult _renderTemplate( + String templateName, LlamaChatTemplateResult Function() render, ) { try { @@ -367,7 +377,7 @@ class ChatTemplateEngine { const prefix = 'Exception: '; Error.throwWithStackTrace( LlamaInferenceException( - 'The chat template failed to render: ' + 'The chat template from $templateName failed to render: ' '${cause.startsWith(prefix) ? cause.substring(prefix.length) : cause}', ), stackTrace, @@ -497,6 +507,9 @@ class ChatTemplateEngine { /// /// Content that ends [output] keeps the whitespace after it, as llama.cpp /// does, unless [isPartial] is true: more output may follow a partial one. + /// + /// Output that a PEG [parser] cannot parse throws + /// [LlamaInferenceException]. static ChatParseResult parse( int formatIndex, String output, { diff --git a/lib/src/core/template/peg_chat_parser.dart b/lib/src/core/template/peg_chat_parser.dart index d114bfb7f..176ec9048 100644 --- a/lib/src/core/template/peg_chat_parser.dart +++ b/lib/src/core/template/peg_chat_parser.dart @@ -1,5 +1,6 @@ import 'dart:convert'; +import '../exceptions.dart'; import '../models/chat/completion_chunk.dart'; import 'chat_format.dart'; import 'chat_parse_result.dart'; @@ -20,6 +21,14 @@ ChatFormat? pegParseFormat(ChatFormat format, String? parser) { }; } +// llama.cpp's `common_chat_format_name` spelling, as its errors use. +String _formatName(ChatFormat format) => switch (format) { + ChatFormat.pegSimple => 'peg-simple', + ChatFormat.pegNative => 'peg-native', + ChatFormat.pegConstructed => 'peg-constructed', + _ => format.name, +}; + /// Runtime PEG parser for llama.cpp `parser.save()` payloads. /// /// This executes serialized PEG parsers and maps AST tags to chat payloads, @@ -28,6 +37,8 @@ class PegChatParser { static final Map _arenaCache = {}; /// Parses [output] with a serialized [parser] definition. + /// + /// Throws [LlamaInferenceException] when [output] does not match [parser]. static ChatParseResult parse({ required String parser, required ChatFormat format, @@ -47,7 +58,11 @@ class PegChatParser { final ctx = _PegParseContext(input: output, isPartial: isPartial); final parseResult = arena.parse(ctx); if (parseResult.isFail) { - throw StateError('Failed to parse input at pos ${parseResult.end}.'); + throw LlamaInferenceException( + 'The model output does not match the expected ${_formatName(format)} ' + 'format: the parse failed at character ${parseResult.end} of ' + '${output.length}.', + ); } final message = _PegChatMessage(); diff --git a/lib/src/core/template/template_internal_metadata.dart b/lib/src/core/template/template_internal_metadata.dart index 3b31157b2..8d41ed0c6 100644 --- a/lib/src/core/template/template_internal_metadata.dart +++ b/lib/src/core/template/template_internal_metadata.dart @@ -41,3 +41,10 @@ Map chatTemplateKwargsFromMetadata( /// /// Value is serialized as an ISO-8601 timestamp string in UTC. const String internalTemplateNowMetadataKey = 'llamadart.internal.now'; + +/// Internal metadata key naming where the `templateSource` of +/// `ChatTemplateEngine.render` came from, such as `ModelParams.chatTemplate`. +/// +/// A template that fails to render is named by it in the error. +const String internalTemplateSourceNameMetadataKey = + 'llamadart.internal.template_source_name'; 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 77c279014..9ea8c8363 100644 --- a/test/unit/core/engine/chat_completion_stream_parser_test.dart +++ b/test/unit/core/engine/chat_completion_stream_parser_test.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'dart:math'; import 'package:llamadart/src/core/engine/chat_completion_stream_parser.dart'; +import 'package:llamadart/src/core/exceptions.dart'; import 'package:llamadart/src/core/llama_logger.dart'; import 'package:llamadart/src/core/models/chat/chat_message.dart'; import 'package:llamadart/src/core/models/chat/chat_role.dart'; @@ -10,6 +11,7 @@ import 'package:llamadart/src/core/models/chat/chat_template_result.dart'; import 'package:llamadart/src/core/models/chat/completion.dart'; import 'package:llamadart/src/core/models/chat/completion_chunk.dart'; import 'package:llamadart/src/core/models/config/log_level.dart'; +import 'package:llamadart/src/core/models/inference/tool_choice.dart'; import 'package:llamadart/src/core/models/tools/tool_definition.dart'; import 'package:llamadart/src/core/models/tools/tool_param.dart'; import 'package:llamadart/src/core/template/chat_format.dart'; @@ -18,6 +20,7 @@ import 'package:llamadart/src/core/template/chat_template_handler.dart'; import 'package:llamadart/src/core/template/handlers/ministral_handler.dart'; import 'package:llamadart/src/core/template/handlers/qwen3_coder_xml_handler.dart'; import 'package:llamadart/src/core/template/handlers/solar_open_handler.dart'; +import 'package:llamadart/src/core/template/template_internal_metadata.dart'; import 'package:test/test.dart'; void main() { @@ -519,6 +522,149 @@ void main() { ]); }); + group('a Ministral PEG reply cut short', () { + LlamaChatTemplateResult ministral(ToolChoice toolChoice) => + MinistralHandler().render( + templateSource: '{{ messages[0]["content"] }}', + messages: const [ + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'hi'), + ], + metadata: {internalToolChoiceMetadataKey: toolChoice.name}, + tools: [_weatherTool], + ); + + Future> parse( + ToolChoice toolChoice, + List tokens, { + bool atLimit = false, + bool cancelled = false, + }) => ChatCompletionStreamParser.parse( + tokenStream: Stream.fromIterable(tokens), + templateResult: ministral(toolChoice), + parseToolCallsEnabled: toolChoice != ToolChoice.none, + enableThinking: true, + modelName: 'Ministral-3-3B-Reasoning', + completionId: 'cut-short', + tools: [_weatherTool], + stoppedAtLimit: () => atLimit, + cancelled: () => cancelled, + ).toList(); + + String joined( + List chunks, + String? Function(LlamaCompletionChunkDelta delta) field, + ) => + chunks.map((chunk) => field(chunk.choices.single.delta) ?? '').join(); + + List calls( + List chunks, + ) => chunks + .expand( + (chunk) => + chunk.choices.single.delta.toolCalls ?? + const [], + ) + .toList(); + + const partialCall = '[TOOL_CALLS]weather[ARGS]{"city":"Par'; + const completeCall = '[TOOL_CALLS]weather[ARGS]{"city":"Paris"}'; + + for (final toolChoice in [ToolChoice.required, ToolChoice.auto]) { + group('with ${toolChoice.name}', () { + for (final (name, atLimit, cancelled, finishReason) in const [ + ('at a limit', true, false, 'length'), + ('by a cancel', false, true, 'stop'), + ]) { + test('ends $name before any output with $finishReason', () async { + final chunks = await parse( + toolChoice, + const [], + atLimit: atLimit, + cancelled: cancelled, + ); + + expect(chunks.last.choices.single.finishReason, finishReason); + expect(joined(chunks, (delta) => delta.content), isEmpty); + expect(calls(chunks), isEmpty); + }); + + test('ends $name in a tool call with $finishReason and no ' + 'calls', () async { + final chunks = await parse( + toolChoice, + const ['[THINK]Check.[/THINK]', partialCall], + atLimit: atLimit, + cancelled: cancelled, + ); + + expect(chunks.last.choices.single.finishReason, finishReason); + expect(joined(chunks, (delta) => delta.thinking), 'Check.'); + expect(joined(chunks, (delta) => delta.content), isEmpty); + expect(calls(chunks), isEmpty); + }); + } + + test('keeps a complete call after a cancel', () async { + final chunks = await parse(toolChoice, const [ + completeCall, + ], cancelled: true); + + expect(chunks.last.choices.single.finishReason, 'tool_calls'); + expect( + calls(chunks).single.function?.arguments, + '{"city":"Paris"}', + ); + }); + }); + } + + test('ends a required reply cut short in its thought without a ' + 'call', () async { + final chunks = await parse(ToolChoice.required, const [ + '[THINK]Check', + ' the city.', + ], atLimit: true); + + expect(chunks.last.choices.single.finishReason, 'length'); + expect(joined(chunks, (delta) => delta.thinking), 'Check the city.'); + expect(joined(chunks, (delta) => delta.content), isEmpty); + expect(calls(chunks), isEmpty); + }); + + for (final (name, tokens) in const [ + ('no output', []), + ('text without a call', ['It is sunny.']), + ('a partial call', [partialCall]), + ]) { + test('throws a typed exception for a required reply that ended ' + 'normally with $name', () async { + await expectLater( + parse(ToolChoice.required, tokens), + throwsA( + isA().having( + (error) => error.message, + 'message', + startsWith( + 'The model output does not match the expected peg-native ' + 'format: the parse failed at character ', + ), + ), + ), + ); + }); + } + + test('none and auto replies that ended normally still parse', () async { + final none = await parse(ToolChoice.none, const ['It is sunny.']); + expect(none.last.choices.single.finishReason, 'stop'); + expect(joined(none, (delta) => delta.content), 'It is sunny.'); + + final auto = await parse(ToolChoice.auto, const ['It is sunny.']); + expect(auto.last.choices.single.finishReason, 'stop'); + expect(joined(auto, (delta) => delta.content), 'It is sunny.'); + }); + }); + test('carries tool schemas into specialized final parsing', () async { const namespace = ']<]minimax[>['; final tool = ToolDefinition( diff --git a/test/unit/core/engine/chat_template_renderer_test.dart b/test/unit/core/engine/chat_template_renderer_test.dart index 3b9e0333b..d4db1d99e 100644 --- a/test/unit/core/engine/chat_template_renderer_test.dart +++ b/test/unit/core/engine/chat_template_renderer_test.dart @@ -1,4 +1,5 @@ import 'package:llamadart/src/core/engine/chat_template_renderer.dart'; +import 'package:llamadart/src/core/exceptions.dart'; import 'package:llamadart/src/core/models/chat/chat_message.dart'; import 'package:llamadart/src/core/models/chat/chat_role.dart'; import 'package:llamadart/src/core/models/tools/tool_definition.dart'; @@ -96,6 +97,92 @@ void main() { ); }); + test('a render failure names the template that failed', () async { + const raising = "{{ raise_exception('roles must alternate') }}"; + Future expectNamed( + String name, { + Map metadata = const { + 'tokenizer.chat_template': raising, + 'tokenizer.chat_template.tool_use': raising, + }, + String? modelTemplate, + String? customTemplate, + List? tools, + }) async { + await expectLater( + ChatTemplateRenderer.render( + loadMetadata: () async => metadata, + tokenize: (text, {bool addSpecial = true}) async => const [], + messages: const [ + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'hi'), + ], + tools: tools, + modelTemplate: modelTemplate, + customTemplate: customTemplate, + includeTokenCount: false, + ), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The chat template from $name failed to render: ' + 'roles must alternate', + ), + ), + ); + } + + final tools = [ + ToolDefinition( + name: 'noop', + description: 'Does nothing', + parameters: const [], + handler: (_) async => null, + ), + ]; + + await expectNamed("the model's tokenizer.chat_template"); + await expectNamed( + "the model's tokenizer.chat_template.tool_use", + tools: tools, + ); + await expectNamed('ModelParams.chatTemplate', modelTemplate: raising); + await expectNamed( + 'ModelParams.chatTemplate', + modelTemplate: raising, + tools: tools, + ); + await expectNamed( + 'customTemplate', + metadata: const {'tokenizer.chat_template': '{{ "ok" }}'}, + modelTemplate: '{{ "ok" }}', + customTemplate: raising, + ); + }); + + test('templateSourceName names the ChatML fallback when no template ' + 'is set', () { + expect( + ChatTemplateRenderer.templateSourceName(), + 'the built-in ChatML fallback template', + ); + expect( + ChatTemplateRenderer.templateSourceName(modelTemplate: ''), + 'the built-in ChatML fallback template', + ); + expect( + ChatTemplateRenderer.templateSourceName(metadataTemplate: 'm'), + "the model's tokenizer.chat_template", + ); + expect( + ChatTemplateRenderer.templateSourceName( + modelTemplate: 'o', + metadataTemplate: 'm', + ), + 'ModelParams.chatTemplate', + ); + }); + test('modelTemplate renders when metadata cannot be read', () async { final result = await ChatTemplateRenderer.render( loadMetadata: () async => throw StateError('no metadata'), diff --git a/test/unit/core/engine/engine_test.dart b/test/unit/core/engine/engine_test.dart index 1827b7c32..824093be5 100644 --- a/test/unit/core/engine/engine_test.dart +++ b/test/unit/core/engine/engine_test.dart @@ -666,6 +666,80 @@ class HeldOutputBackend extends MockLlamaBackend }) => _held(); } +/// Streams [output], then holds the generation open until +/// [cancelGeneration] ends it, as the llama.cpp backend does. +class _OutputUntilCancelBackend extends MockLlamaBackend { + _OutputUntilCancelBackend(this.output, Map metadata) + : super(modelMetadataResponse: metadata); + + final List output; + final Completer started = Completer(); + final Completer _cancelled = Completer(); + + @override + Stream> generate( + int contextHandle, + String prompt, + GenerationParams params, { + List? parts, + }) async* { + started.complete(); + for (final text in output) { + yield utf8.encode(text); + } + await _cancelled.future; + } + + @override + void cancelGeneration() { + super.cancelGeneration(); + if (!_cancelled.isCompleted) _cancelled.complete(); + } +} + +/// Reports that every generation ended at `maxTokens`, for a Ministral +/// template. +class _MinistralLimitBackend extends MockLlamaBackend + implements BackendGenerationLimitReporting { + _MinistralLimitBackend() + : super( + modelMetadataResponse: const { + 'tokenizer.chat_template': + '{#- [SYSTEM_PROMPT] [TOOL_CALLS] [ARGS] -#}' + '{% for message in messages %}{{ message["content"] }}' + '{% endfor %}', + }, + ); + + final Expando _limits = + Expando(); + + @override + Stream> generate( + int contextHandle, + String prompt, + GenerationParams params, { + List? parts, + }) { + late final Stream> tracked; + tracked = super + .generate(contextHandle, prompt, params, parts: parts) + .transform( + StreamTransformer, List>.fromHandlers( + handleDone: (sink) { + _limits[tracked] = BackendGenerationLimit.maxTokens; + sink.close(); + }, + ), + ); + return tracked; + } + + @override + BackendGenerationLimit? generationLimitOf(Stream> generation) => + _limits[generation]; +} + class MockModelResolver implements ModelResolver { MockModelResolver(this.target); @@ -2486,35 +2560,59 @@ void main() { } }); - test( - 'create throws a typed exception when the chat template raises', - () async { - final raising = MockLlamaBackend( - modelMetadataResponse: { - 'tokenizer.chat_template': - "{{ raise_exception('Conversation roles must alternate') }}", - }, - ); - final raisingEngine = LlamaEngine(raising); - addTearDown(raisingEngine.dispose); - await raisingEngine.loadModel('qwen-test.gguf'); - - await expectLater( - raisingEngine.create(const [ - LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'hi'), - ]).drain(), - throwsA( + for (final overridden in [false, true]) { + final source = overridden + ? 'ModelParams.chatTemplate' + : "the model's tokenizer.chat_template"; + test('create, chatTemplate and ChatSession throw a typed exception ' + 'naming $source when it fails to render', () async { + const raising = + "{{ raise_exception('Conversation roles must alternate') }}"; + const invalid = '{% for message in messages %}{{ message.content'; + for (final (template, cause) in const [ + (raising, 'Conversation roles must alternate'), + (invalid, 'ParserException: '), + ]) { + final backend = MockLlamaBackend( + modelMetadataResponse: { + 'tokenizer.chat_template': overridden + ? '{{ messages[0].content }}' + : template, + }, + ); + final failing = LlamaEngine(backend); + addTearDown(failing.dispose); + await failing.loadModel( + 'qwen-test.gguf', + modelParams: overridden + ? ModelParams(chatTemplate: template) + : const ModelParams(), + ); + final throwsNamed = throwsA( isA().having( (error) => error.message, 'message', - 'The chat template failed to render: ' - 'Conversation roles must alternate', + startsWith( + 'The chat template from $source failed to render: $cause', + ), ), - ), - ); - expect(raising.lastGenerationPrompt, isNull); - }, - ); + ); + const hi = [ + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'hi'), + ]; + + await expectLater(failing.create(hi).drain(), throwsNamed); + await expectLater(failing.chatTemplate(hi), throwsNamed); + await expectLater( + ChatSession( + failing, + ).create(const [LlamaTextContent('hi')]).drain(), + throwsNamed, + ); + expect(backend.lastGenerationPrompt, isNull); + } + }); + } test( 'multimodal projector can be unloaded without unloading model', @@ -5164,6 +5262,136 @@ void main() { }); }); + group('LlamaEngine Ministral replies cut short', () { + const ministralTemplate = + '{#- [SYSTEM_PROMPT] [TOOL_CALLS] [ARGS] -#}' + '{% for message in messages %}[INST]{{ message["content"] }}[/INST]' + '{% endfor %}'; + const metadata = {'tokenizer.chat_template': ministralTemplate}; + const messages = [ + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'Weather?'), + ]; + final weatherTool = ToolDefinition( + name: 'get_weather', + description: 'Get weather', + parameters: [ToolParam.string('city', required: true)], + handler: (_) async => 'ok', + ); + const partialCall = '[TOOL_CALLS]get_weather[ARGS]{"ci'; + + Future load(LlamaBackend backend) async { + final engine = LlamaEngine(backend); + addTearDown(engine.dispose); + await engine.loadModel('ministral.gguf'); + return engine; + } + + for (final toolChoice in ToolChoice.values) { + for (final output in const [ + [], + [partialCall], + ]) { + final state = output.isEmpty ? 'before any output' : 'in a tool call'; + test('create with ${toolChoice.name} ends with stop when cancelled ' + '$state', () async { + final backend = _OutputUntilCancelBackend(output, metadata); + final engine = await load(backend); + final chunks = []; + final done = engine + .create(messages, tools: [weatherTool], toolChoice: toolChoice) + .forEach(chunks.add); + await backend.started.future; + await pumpEventQueue(); + engine.cancelGeneration(); + await done; + + expect(chunks.last.choices.single.finishReason, 'stop'); + expect( + chunks.expand( + (chunk) => chunk.choices.single.delta.toolCalls ?? [], + ), + isEmpty, + ); + }); + } + + test('ChatSession.create with ${toolChoice.name} reports a cancel ' + 'before any output as cancelled', () async { + final backend = _OutputUntilCancelBackend(const [], metadata); + final engine = await load(backend); + final session = ChatSession(engine); + final done = session + .create( + [const LlamaTextContent('Weather?')], + tools: [weatherTool], + toolChoice: toolChoice, + ) + .drain(); + await backend.started.future; + await pumpEventQueue(); + engine.cancelGeneration(); + + await expectLater( + done, + throwsA( + isA().having( + (error) => error.message, + 'message', + 'Generation was cancelled before any output.', + ), + ), + ); + }); + + test('create with ${toolChoice.name} ends with length when maxTokens ' + 'cuts a tool call short', () async { + final backend = _MinistralLimitBackend()..generationText = partialCall; + final engine = await load(backend); + + final chunks = await engine + .create( + messages, + params: const GenerationParams(maxTokens: 6), + tools: [weatherTool], + toolChoice: toolChoice, + ) + .toList(); + + expect(chunks.last.choices.single.finishReason, 'length'); + expect( + chunks.expand((chunk) => chunk.choices.single.delta.toolCalls ?? []), + isEmpty, + ); + }); + } + + test('create with required throws a typed exception for a reply that ' + 'ended without a call', () async { + final backend = MockLlamaBackend(modelMetadataResponse: metadata) + ..generationText = 'It is sunny.'; + final engine = await load(backend); + + await expectLater( + engine + .create( + messages, + tools: [weatherTool], + toolChoice: ToolChoice.required, + ) + .drain(), + throwsA( + isA().having( + (error) => error.message, + 'message', + startsWith( + 'The model output does not match the expected peg-native format', + ), + ), + ), + ); + }); + }); + group('LlamaEngine source URL redaction', () { late List logs; diff --git a/test/unit/core/template/chat_template_engine_test.dart b/test/unit/core/template/chat_template_engine_test.dart index 212588c5e..fd8bd99bf 100644 --- a/test/unit/core/template/chat_template_engine_test.dart +++ b/test/unit/core/template/chat_template_engine_test.dart @@ -549,7 +549,7 @@ void main() { metadata: const {}, ), throwsRenderFailure( - 'The chat template failed to render: ' + 'The chat template from templateSource failed to render: ' 'Conversation roles must alternate', ), ); @@ -592,7 +592,7 @@ void main() { metadata: const {}, ), throwsRenderFailure( - 'The chat template failed to render: ' + 'The chat template from templateSource failed to render: ' 'Conversation roles must alternate', ), ); @@ -606,7 +606,10 @@ void main() { metadata: const {}, ), throwsRenderFailure( - startsWith('The chat template failed to render: ParserException'), + startsWith( + 'The chat template from templateSource failed to render: ' + 'ParserException', + ), ), ); }); diff --git a/test/unit/core/template/peg_chat_parser_test.dart b/test/unit/core/template/peg_chat_parser_test.dart index 97d042643..fba91223f 100644 --- a/test/unit/core/template/peg_chat_parser_test.dart +++ b/test/unit/core/template/peg_chat_parser_test.dart @@ -1,7 +1,15 @@ import 'dart:convert'; +import 'package:llamadart/src/core/exceptions.dart'; +import 'package:llamadart/src/core/models/chat/chat_message.dart'; +import 'package:llamadart/src/core/models/chat/chat_role.dart'; +import 'package:llamadart/src/core/models/inference/tool_choice.dart'; +import 'package:llamadart/src/core/models/tools/tool_definition.dart'; +import 'package:llamadart/src/core/models/tools/tool_param.dart'; import 'package:llamadart/src/core/template/chat_format.dart'; import 'package:llamadart/src/core/template/chat_template_engine.dart'; +import 'package:llamadart/src/core/template/handlers/ministral_handler.dart'; +import 'package:llamadart/src/core/template/template_internal_metadata.dart'; import 'package:test/test.dart'; import 'package:llamadart/src/core/template/peg_chat_parser.dart'; @@ -93,6 +101,61 @@ void main() { ); }); + group('with a Ministral ToolChoice.required parser', () { + String requiredParser() => MinistralHandler() + .render( + templateSource: '{{ messages[0]["content"] }}', + messages: const [ + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: 'hi'), + ], + metadata: {internalToolChoiceMetadataKey: ToolChoice.required.name}, + tools: [ + ToolDefinition( + name: 'weather', + description: 'Weather', + parameters: [ToolParam.string('city', required: true)], + ), + ], + ) + .parser!; + + for (final (output, end) in const [ + ('', 0), + ('[THINK]Check.[/THINK]', 21), + ('[TOOL_CALLS]weather[ARGS]{"ci', 0), + ]) { + test('throws a typed exception for ${jsonEncode(output)}', () { + expect( + () => ChatTemplateEngine.parse( + ChatFormat.ministral.index, + output, + parser: requiredParser(), + ), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The model output does not match the expected peg-native ' + 'format: the parse failed at character $end of ' + '${output.length}.', + ), + ), + ); + }); + + test('parses ${jsonEncode(output)} as partial output', () { + final result = ChatTemplateEngine.parse( + ChatFormat.ministral.index, + output, + isPartial: true, + parser: requiredParser(), + ); + + expect(result.content, isEmpty); + }); + } + }); + test('rethrows parse failures for partial PEG parse', () { expect( () => ChatTemplateEngine.parse( diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 5669068ba..79ce912b8 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -7,6 +7,20 @@ For canonical full release notes, use: - [`CHANGELOG.md`](https://github.com/leehack/llamadart/blob/main/CHANGELOG.md) +## Unreleased + +- A chat template that fails to render now names its source in the + `LlamaInferenceException` message: the model's `tokenizer.chat_template` + or its `tool_use` variant, `ModelParams.chatTemplate`, or `customTemplate` + ([#820](https://github.com/leehack/llamadart/issues/820)). +- A `ToolChoice.required` reply cut short by a cancel, or by `maxTokens` on + a backend that reports a token limit, no longer throws a raw + `StateError`; it ends with `stop` or `length` and no tool calls, as with + `ToolChoice.auto`. **Behavior change:** other output a PEG parser cannot + parse, including in `ChatTemplateEngine.parse`, throws + `LlamaInferenceException` instead of `StateError` + ([#890](https://github.com/leehack/llamadart/issues/890)). + ## 0.12.2 - Pair this release with Apple companions `llamadart_llama_cpp_flutter` diff --git a/website/docs/guides/template-engine-internals.md b/website/docs/guides/template-engine-internals.md index d300b1158..3048eedac 100644 --- a/website/docs/guides/template-engine-internals.md +++ b/website/docs/guides/template-engine-internals.md @@ -85,7 +85,10 @@ sequenceDiagram space in every other string `generate` reads as a part. Messages without media render as they are. - A template that fails to render, by raising or through invalid syntax, - throws `LlamaInferenceException` with the template's message. + throws `LlamaInferenceException` with the template's message. The message + names the template: the model's `tokenizer.chat_template` or its + `tool_use` variant, `ModelParams.chatTemplate`, or a per-call + `customTemplate`. - Routing workarounds mirror llama.cpp behavior for schema mode, tool-choice behavior, and system-message adaptation. @@ -106,6 +109,19 @@ sequenceDiagram - On completion, final parse produces stable tool-call structures and finish reason semantics. - PEG-backed parse paths are used when parser payloads are present. +- A reply that a cancel or a generation limit cut short may not hold what + the PEG parser requires, such as the tool call of `ToolChoice.required`. + It is parsed as partial output instead: its content and thinking are kept, + its tool calls are withheld, and it finishes with `length` at a limit and + `stop` on a cancel, as with `ToolChoice.auto`. A limit counts only on a + backend that reports a token limit, such as native llama.cpp; on one that + does not, such as LiteRT-LM, a reply cut short by `maxTokens` is parsed as + a complete one. A reply parsed as complete that does not parse throws + `LlamaInferenceException`. +- This deliberately differs from upstream llama.cpp (`b10549`), whose server + fails a cut-short `required` reply with a parse error. llamadart withholds + the calls and finishes with `length` or `stop` instead + ([#890](https://github.com/leehack/llamadart/issues/890)). ## Tool-call parsing