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
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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`
Expand Down
40 changes: 30 additions & 10 deletions lib/src/core/engine/chat_completion_stream_parser.dart
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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<LlamaCompletionChunk> parse({
required Stream<String> tokenStream,
required LlamaChatTemplateResult templateResult,
Expand All @@ -86,6 +94,7 @@ class ChatCompletionStreamParser {
required String completionId,
List<ToolDefinition>? tools,
bool Function()? stoppedAtLimit,
bool Function()? cancelled,
LlamaGenerationUsage? Function()? usage,
}) async* {
final buffer = StringBuffer();
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Expand Down
26 changes: 25 additions & 1 deletion lib/src/core/engine/chat_template_renderer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<Map<String, String>> Function();
Expand All @@ -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`
Expand Down Expand Up @@ -64,7 +84,7 @@ class ChatTemplateRenderer {
}) async {
Map<String, String> metadata = {};
try {
metadata = await loadMetadata();
metadata = {...await loadMetadata()};
} catch (error) {
LlamaLogger.instance.warning('Failed to read metadata: $error');
}
Expand All @@ -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 ??
Expand Down
1 change: 1 addition & 0 deletions lib/src/core/engine/engine.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1707,6 +1707,7 @@ class LlamaEngine {
completionId: completionId,
tools: effectiveTools,
stoppedAtLimit: () => generationLimit != null,
cancelled: request.isCancelled,
usage: () => generationUsage,
).map((chunk) {
final limit = generationLimit;
Expand Down
21 changes: 17 additions & 4 deletions lib/src/core/template/chat_template_engine.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -152,17 +154,21 @@ 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',
);
}

var effectiveTemplate = customTemplate;
if (effectiveTemplate != null) {
templateName = 'customTemplate';
LlamaLogger.instance.debug(
'ChatTemplateEngine: Using per-call custom template override',
);
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -326,6 +333,7 @@ class ChatTemplateEngine {
}

var baseResult = _renderTemplate(
templateName,
() => handler.render(
templateSource: effectiveTemplate ?? GenericHandler.chatMlTemplate,
messages: effectiveMessages,
Expand Down Expand Up @@ -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 {
Expand All @@ -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,
Expand Down Expand Up @@ -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, {
Expand Down
17 changes: 16 additions & 1 deletion lib/src/core/template/peg_chat_parser.dart
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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,
Expand All @@ -28,6 +37,8 @@ class PegChatParser {
static final Map<String, _PegArena> _arenaCache = <String, _PegArena>{};

/// Parses [output] with a serialized [parser] definition.
///
/// Throws [LlamaInferenceException] when [output] does not match [parser].
static ChatParseResult parse({
required String parser,
required ChatFormat format,
Expand All @@ -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();
Expand Down
7 changes: 7 additions & 0 deletions lib/src/core/template/template_internal_metadata.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,10 @@ Map<String, dynamic> 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';
Loading
Loading