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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
## Unreleased

- When the prompt opened no thought, take a thought only at the start of the reply, as llama.cpp does: any other thinking tag, such as a `</think>` before any `<think>`, a `<think>` later in the reply or a second `</think>`, is now content in generic, Llama 3, GLM 4.5, Kimi K2, LFM2, Laguna, Granite, MiniCPM5, Mistral Nemo, Apertus, Hunyuan V3 and DeepSeek R1, V3.2 and V4 replies, and after the start of a Hermes or Qwen3-Coder XML reply. The stream used to depend on how the reply was chunked and could repeat text as both content and reasoning ([#1865](https://github.com/leehack/llamadart/issues/1865)).

## 0.19.2

- Keep the default WebGPU bridge assets at `v0.1.83` (unchanged from 0.19.1).
Expand Down
22 changes: 14 additions & 8 deletions lib/src/core/engine/chat_completion_stream_parser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -199,14 +199,20 @@ class ChatCompletionStreamParser {
final verbatimThoughtOpenings = verbatimForcedThought
? traits.forcedThoughtContentOpenings
: const <String>[];
// After a prompt that opens no thought, a Seed-OSS or PEG-parsed reply
// has one only at its start, kept as generated, as the parse takes it.
final leadingThoughtOnly =
final promptOpensNoThought =
!templateResult.thinkingForcedOpen && !thoughtClosedForThinkingOff;
// After a prompt that opens no thought, a reply has a thought only at its
// start in these formats. A Seed-OSS or PEG-parsed reply keeps it as
// generated, as the parse takes it.
final verbatimLeadingThought =
(templateResult.format == ChatFormat.seedOss.index ||
pegParsedWithoutTools) &&
!templateResult.thinkingForcedOpen &&
!thoughtClosedForThinkingOff;
final verbatimThought = verbatimForcedThought || leadingThoughtOnly;
promptOpensNoThought;
final leadingThoughtOnly =
verbatimLeadingThought ||
(promptOpensNoThought && traits.takesThoughtOnlyAtReplyStart);
final verbatimThought = verbatimForcedThought || verbatimLeadingThought;
final endsAtFirstEndTag = verbatimThought || leadingThoughtOnly;
// After a prompt that opens no thought, the parse keeps an end tag before
// any start tag as content, with every thinking tag after it.
final unopenedEndTagIsContent =
Expand Down Expand Up @@ -407,13 +413,13 @@ class ChatCompletionStreamParser {
startTag: startTag,
endTag: endTag,
tagState: thoughtTags,
endsAtFirstEndTag: verbatimThought,
endsAtFirstEndTag: endsAtFirstEndTag,
thoughtContentOpenings: verbatimThoughtOpenings,
bodyOpenings: bodyOpenings,
unopenedEndTagIsContent: unopenedEndTagIsContent,
);
if (split.bodyStarted ||
(verbatimThought &&
(endsAtFirstEndTag &&
split.emissions.any((emission) => emission.endsThinking))) {
verbatimThoughtEnded = true;
}
Expand Down
26 changes: 25 additions & 1 deletion lib/src/core/template/chat_format_registry.dart
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ final class ChatFormatTraits {
this.parsesCallsInsideThoughts = false,
this.keepsForcedThoughtVerbatim = false,
this.closedThoughtKeepsTagsAsContent = false,
this.takesThoughtOnlyAtReplyStart = false,
this.forcedThoughtContentOpenings = const [],
this.mayEmbedToolEnvelopeAfterContent = false,
this.hasRepeatedContentChannels = false,
Expand Down Expand Up @@ -126,6 +127,10 @@ final class ChatFormatTraits {
/// extracts no reasoning, so thinking tags are content.
final bool closedThoughtKeepsTagsAsContent;

/// Whether, after a prompt that opens no thought, the parse takes a thought
/// only at the start of the reply, so other thinking tags are content.
final bool takesThoughtOnlyAtReplyStart;

/// Markers that, with [keepsForcedThoughtVerbatim], also end a forced-open
/// thought when they come before its end tag, and start the content.
final List<String> forcedThoughtContentOpenings;
Expand Down Expand Up @@ -213,6 +218,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
detect: (s) => _hasAll(s, const ['dsml_token', 'DSML', 'function_calls']),
traits: ChatFormatTraits(
qualifiesJsonSchemaTools: false,
takesThoughtOnlyAtReplyStart: true,
mayEmbedToolEnvelopeAfterContent: true,
),
),
Expand All @@ -222,6 +228,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
detect: (s) => _hasAll(s, const ['dsml_token', 'DSML', 'tool_calls']),
traits: ChatFormatTraits(
qualifiesJsonSchemaTools: false,
takesThoughtOnlyAtReplyStart: true,
mayEmbedToolEnvelopeAfterContent: true,
),
),
Expand Down Expand Up @@ -253,6 +260,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
]),
traits: ChatFormatTraits(
qualifiesJsonSchemaTools: true,
takesThoughtOnlyAtReplyStart: true,
mayEmbedToolEnvelopeAfterContent: true,
leavesIncompleteToolCall: _contentContainsAny(const ['<tool_call>']),
),
Expand All @@ -277,6 +285,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
detect: (s) => s.contains('<|tool▁calls▁begin|>'),
traits: ChatFormatTraits(
qualifiesJsonSchemaTools: false,
takesThoughtOnlyAtReplyStart: true,
toolCallOpening: DeepseekR1Handler.toolCallOpening,
disabledByResponseSchema: true,
),
Expand Down Expand Up @@ -306,6 +315,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
]),
traits: ChatFormatTraits(
qualifiesJsonSchemaTools: false,
takesThoughtOnlyAtReplyStart: true,
toolCallOpening: XmlToolCallFormat.minicpm5.toolCallOpening,
),
),
Expand All @@ -325,6 +335,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
detect: (s) => _hasAll(s, const ['elif thinking', '<|tool_call|>']),
traits: ChatFormatTraits(
qualifiesJsonSchemaTools: false,
takesThoughtOnlyAtReplyStart: true,
toolCallOpening: GraniteHandler.toolCallOpening,
),
),
Expand All @@ -335,6 +346,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
_hasAll(s, const ['[gMASK]<sop>', '<arg_key>', '<arg_value>']),
traits: ChatFormatTraits(
qualifiesJsonSchemaTools: true,
takesThoughtOnlyAtReplyStart: true,
mayEmbedToolEnvelopeAfterContent: true,
disabledByResponseSchema: true,
leavesIncompleteToolCall: _contentContainsAny(const ['<tool_call>']),
Expand All @@ -347,6 +359,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
_hasAll(s, const ['<|hy_User{}|>', '<tool_sep{}>', '<arg_key{}>']),
traits: ChatFormatTraits(
qualifiesJsonSchemaTools: true,
takesThoughtOnlyAtReplyStart: true,
toolCallOpening: HunyuanV3Handler.toolCallOpening,
leavesIncompleteToolCall: _contentContainsAny(const [
'<tool_call:opensource>',
Expand All @@ -367,6 +380,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
s.contains('Function calls MUST follow the specified format')),
traits: ChatFormatTraits(
qualifiesJsonSchemaTools: false,
takesThoughtOnlyAtReplyStart: true,
toolCallOpening: XmlToolCallFormat.qwen3Coder.toolCallOpening,
closedThoughtKeepsTagsAsContent: true,
keepsForcedThoughtVerbatim: true,
Expand Down Expand Up @@ -407,6 +421,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
detect: (s) => s.contains('<tool_call>'),
traits: ChatFormatTraits(
qualifiesJsonSchemaTools: true,
takesThoughtOnlyAtReplyStart: true,
toolCallOpening: HermesHandler.toolCallOpening,
keepsForcedThoughtVerbatim: true,
disabledByResponseSchema: true,
Expand Down Expand Up @@ -451,6 +466,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
detect: (s) => _hasAll(s, const ['<|system_start|>', '<|tools_prefix|>']),
traits: ChatFormatTraits(
qualifiesJsonSchemaTools: false,
takesThoughtOnlyAtReplyStart: true,
toolCallOpening: ApertusHandler.toolCallOpening,
requiredKeepsLazyGrammar: true,
),
Expand All @@ -465,6 +481,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
(s.contains('List of tools: [') && !s.contains('<|tool_list_start|>')),
traits: ChatFormatTraits(
qualifiesJsonSchemaTools: false,
takesThoughtOnlyAtReplyStart: true,
toolCallOpening: Lfm2Handler.toolCallOpening,
requiredKeepsLazyGrammar: true,
),
Expand All @@ -488,6 +505,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
]),
traits: ChatFormatTraits(
qualifiesJsonSchemaTools: false,
takesThoughtOnlyAtReplyStart: true,
toolCallOpening: KimiK2Handler.toolCallOpening,
parsesCallsInsideThoughts: true,
),
Expand Down Expand Up @@ -576,7 +594,10 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
ChatFormat.llama3,
Llama3Handler.new,
detect: (s) => s.contains('<|start_header_id|>ipython<|end_header_id|>'),
traits: ChatFormatTraits(qualifiesJsonSchemaTools: false),
traits: ChatFormatTraits(
qualifiesJsonSchemaTools: false,
takesThoughtOnlyAtReplyStart: true,
),
),
// Ministral templates also carry [THINK] and [TOOL_CALLS], so Ministral
// precedes Magistral and Mistral Nemo.
Expand All @@ -602,6 +623,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
detect: (s) => s.contains('[TOOL_CALLS]'),
traits: ChatFormatTraits(
qualifiesJsonSchemaTools: true,
takesThoughtOnlyAtReplyStart: true,
toolCallOpening: MistralHandler.toolCallOpening,
toolChoiceNoneRendersContentOnly: true,
leavesIncompleteToolCall: _contentContainsAny(const ['[TOOL_CALLS]']),
Expand Down Expand Up @@ -652,6 +674,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
GenericHandler.new,
traits: ChatFormatTraits(
qualifiesJsonSchemaTools: true,
takesThoughtOnlyAtReplyStart: true,
toolChoiceNoneRendersContentOnly: true,
leavesIncompleteToolCall: _genericLeavesIncompleteToolCall,
),
Expand All @@ -661,6 +684,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
() => _withoutTemplateToolCalls(ChatFormat.contentOnly),
traits: ChatFormatTraits(
qualifiesJsonSchemaTools: false,
takesThoughtOnlyAtReplyStart: true,
toolChoiceNoneRendersContentOnly: true,
),
),
Expand Down
53 changes: 35 additions & 18 deletions lib/src/core/template/chat_template_engine.dart
Original file line number Diff line number Diff line change
Expand Up @@ -721,9 +721,10 @@ class ChatTemplateEngine {
/// render left the prompt's thought, which a copy of the result loses.
/// The reply then parses as llama.cpp parses it after that prompt, which
/// [parse] cannot tell: thinking tags after the template's own empty thought
/// are content for DeepSeek V3, Hermes and Qwen3-Coder XML, as they are
/// after a prompt that opens no thought in a reply with an end tag before
/// any start tag, which [parse] takes as ending a thought; a Seed-OSS reply
/// are content for DeepSeek V3, Hermes and Qwen3-Coder XML; after a prompt
/// that opens no thought, most formats take a thought only at the start of
/// the reply, and DeepSeek V3 keeps an end tag before any start tag as
/// content, where [parse] takes them as thoughts; a Seed-OSS reply
/// to a prompt that opens no thought has one only when it starts with
/// `<seed:think>`; and a Seed-OSS or Cohere2 MoE thought closed because
/// thinking is off still ends at a thinking tag or, for Cohere2 MoE, at the
Expand Down Expand Up @@ -784,20 +785,26 @@ class ChatTemplateEngine {
String? parser,
List<ToolDefinition>? tools,
}) {
ChatParseResult parse() => _parse(
formatIndex,
output,
isPartial: isPartial,
cancelled: cancelled,
parseToolCalls: parseToolCalls,
thinkingForcedOpen: thinkingForcedOpen,
thinkingForcedClosed: thinkingForcedClosed,
promptOpensNoThought: promptOpensNoThought,
parser: parser,
tools: tools,
);
final ChatParseResult result;
try {
result = _parse(
formatIndex,
output,
isPartial: isPartial,
cancelled: cancelled,
parseToolCalls: parseToolCalls,
thinkingForcedOpen: thinkingForcedOpen,
thinkingForcedClosed: thinkingForcedClosed,
promptOpensNoThought: promptOpensNoThought,
parser: parser,
tools: tools,
);
result =
promptOpensNoThought &&
!thinkingForcedOpen &&
takesThoughtOnlyAtReplyStart(formatIndex)
? withThoughtOnlyAtReplyStart(parse)
: parse();
} on StackOverflowError catch (_, stackTrace) {
// PEG rules recurse once per nesting level of model-controlled output.
Error.throwWithStackTrace(
Expand Down Expand Up @@ -1129,6 +1136,15 @@ class ChatTemplateEngine {
}
}

/// Whether, after a prompt that opens no thought, the parse of [formatIndex]
/// takes a thought only at the start of the reply and keeps other thinking
/// tags as content, as llama.cpp does.
bool takesThoughtOnlyAtReplyStart(int formatIndex) =>
formatIndex < ChatFormat.values.length &&
chatFormatRegistration(
ChatFormat.values[formatIndex],
).traits.takesThoughtOnlyAtReplyStart;

/// The markers that show where a reply ends a thought that a handler closed
/// for thinking off: the format's thinking tags and, for Cohere2 MoE, where
/// its text or action starts, as llama.cpp ends the thought it keeps open.
Expand All @@ -1149,9 +1165,10 @@ List<String> closedThoughtMarkers(int formatIndex) {
/// for thinking off ([thoughtClosedForThinkingOff]), so a reply that shows one
/// of [closedThoughtMarkers] parses as after a forced-open prompt. Without it
/// or [thinkingForcedOpen] the prompt opened no thought, so a Seed-OSS end tag
/// in a reply that does not start with a thought is content, and a DeepSeek
/// V3, Hermes or Qwen3-Coder XML reply with an end tag before any start tag
/// keeps its thinking tags as content.
/// in a reply that does not start with a thought is content, a format with
/// [ChatFormatTraits.takesThoughtOnlyAtReplyStart] takes a thought only at the
/// start of the reply, and a DeepSeek V3 reply with an end tag before any
/// start tag keeps its thinking tags as content.
ChatParseResult parseRenderedOutput(
int formatIndex,
String output, {
Expand Down
61 changes: 54 additions & 7 deletions lib/src/core/template/thinking_utils.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:async';

import '../models/chat/chat_template_result.dart';
import 'template_internal_metadata.dart';

Expand All @@ -12,6 +14,10 @@ typedef ThinkingExtraction = ({String content, String? reasoning});
/// If [startTag] is found without a matching [endTag], all text after
/// [startTag] is treated as reasoning (model may still be thinking).
///
/// Inside [withThoughtOnlyAtReplyStart] and without [thinkingForcedOpen],
/// only a thought that starts [text] is reasoning, and the rest is content in
/// which thinking tags are text.
///
/// Escaped `\n` and `\r` in reasoning become a newline and a carriage return
/// unless [unescape] is false. The content keeps the whitespace at its ends
/// unless [trimContent] is true.
Expand All @@ -23,13 +29,21 @@ ThinkingExtraction extractThinking(
bool unescape = true,
bool trimContent = true,
}) {
final result = _extractThinking(
text,
startTag: startTag,
endTag: endTag,
thinkingForcedOpen: thinkingForcedOpen,
unescape: unescape,
);
final result =
!thinkingForcedOpen && Zone.current[_thoughtOnlyAtReplyStart] == true
? _extractLeadingThought(
text,
startTag: startTag,
endTag: endTag,
unescape: unescape,
)
: _extractThinking(
text,
startTag: startTag,
endTag: endTag,
thinkingForcedOpen: thinkingForcedOpen,
unescape: unescape,
);
// Trim only the overall content ends here, once. The recursion keeps content
// raw so whitespace between stripped thinking blocks (e.g. the space in
// "Hello<think>x</think> world<think>y</think>!") is preserved.
Expand Down Expand Up @@ -108,6 +122,39 @@ String withoutTrailingTagPrefix(String text, Iterable<String> tags) {
return text.substring(0, text.length - cut);
}

final Object _thoughtOnlyAtReplyStart = Object();

/// Runs [parse] with [extractThinking] taking a thought only where it starts
/// the text, as llama.cpp parses a reply to a prompt that opens no thought.
///
/// Handlers extract thinking in many places and shapes, so the parse sets
/// this once around them instead of threading it through each one.
T withThoughtOnlyAtReplyStart<T>(T Function() parse) =>
runZoned(parse, zoneValues: {_thoughtOnlyAtReplyStart: true});

/// Splits off the thought that starts [text], after ASCII whitespace, up to
/// the first [endTag], or to the end when none follows.
ThinkingExtraction _extractLeadingThought(
String text, {
required String startTag,
required String endTag,
required bool unescape,
}) {
final rest = trimLeftAsciiSpace(text);
if (!rest.startsWith(startTag)) return (content: text, reasoning: null);
final thought = rest.substring(startTag.length);
final end = thought.indexOf(endTag);
var reasoning = end == -1 ? thought : thought.substring(0, end);
if (unescape) {
reasoning = reasoning.replaceAll(r'\n', '\n').replaceAll(r'\r', '\r');
}
reasoning = reasoning.trim();
return (
content: end == -1 ? '' : thought.substring(end + endTag.length),
reasoning: reasoning.isEmpty ? null : reasoning,
);
}

ThinkingExtraction _extractThinking(
String text, {
required String startTag,
Expand Down
5 changes: 4 additions & 1 deletion skills/llamadart-chat-streaming/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,10 @@ modalities and speculative strategies before offering them.
Nano v2) stream no `chunk.text` until `</think>` or `<think>` arrives or the
reply ends, so a thought the model still writes never reaches it; Cohere2
MoE waits likewise for a thinking tag, `<|START_TEXT|>` or
`<|START_ACTION|>`. A boolean `enable_thinking` or `thinking` in
`<|START_ACTION|>`. When the prompt opens no thought, most formats stream
only a thought that starts the reply as `chunk.thinking`; a `</think>`
before any `<think>` and thinking tags later in the reply stay in
`chunk.text`, as in llama-server. A boolean `enable_thinking` or `thinking` in
`chatTemplateKwargs` overrides it, as in llama-server, and every chat
template receives the result as `enable_thinking`. A template's own
setting in `chatTemplateKwargs`, such as `reasoning_effort` (Hy3, Cohere2
Expand Down
Loading
Loading