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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +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)).
- Parse Qwen3-Coder XML replies (Qwen3-Coder, Qwen3.5, StepFun3.5-Flash) as llama.cpp does: text from the first `<tool_call>` on that is not a valid call, such as an invalid call or text after the calls, is dropped instead of kept as content, and only the first call counts without `parallelToolCalls`. Qwen3-Coder replies have no reasoning, and StepFun3.5-Flash with thinking off ends its thought at `</think>` or `<tool_call>` ([#1531](https://github.com/leehack/llamadart/issues/1531)).

## 0.19.2

Expand Down
38 changes: 21 additions & 17 deletions lib/src/core/engine/chat_completion_stream_parser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import '../template/handlers/cohere2_moe_handler.dart';
import '../template/handlers/command_r7b_handler.dart';
import '../template/handlers/llama3_handler.dart';
import '../template/peg_chat_parser.dart';
import '../template/template_internal_metadata.dart';
import '../template/thinking_utils.dart';

enum _ToolStreamingMode { undecided, raw, parsed }
Expand Down Expand Up @@ -105,10 +106,9 @@ class ChatCompletionStreamParser {
final markers = closedThoughtMarkers(templateResult.format);
final held = StreamIterator(_heldUntilAny(tokenStream, markers));
if (await held.moveNext()) {
// A Cohere2 MoE or Seed-OSS reply that reaches a marker then parses as
// after the forced-open prompt llama.cpp renders.
if ((templateResult.format == ChatFormat.cohere2Moe.index ||
templateResult.format == ChatFormat.seedOss.index) &&
// Such a reply that reaches a marker then parses as after the
// forced-open prompt llama.cpp renders.
if (reopensClosedThought(templateResult.format) &&
markers.any(held.current.contains)) {
result = _withForcedOpenThought(templateResult);
}
Expand Down Expand Up @@ -616,6 +616,7 @@ class ChatCompletionStreamParser {
thinkingForcedOpen: templateResult.thinkingForcedOpen,
thoughtClosedForThinkingOff: thoughtClosedForThinkingOff,
thinkingForcedClosed: thinkingForcedClosed,
singleToolCall: singleToolCallOf(templateResult),
parser: templateResult.parser,
tools: tools,
);
Expand Down Expand Up @@ -797,20 +798,23 @@ class ChatCompletionStreamParser {
/// [result] with its prompt's thought forced open.
static LlamaChatTemplateResult _withForcedOpenThought(
LlamaChatTemplateResult result,
) => withThinkingForcedClosed(
LlamaChatTemplateResult(
prompt: result.prompt,
format: result.format,
grammar: result.grammar,
grammarLazy: result.grammarLazy,
additionalStops: result.additionalStops,
preservedTokens: result.preservedTokens,
grammarTriggers: result.grammarTriggers,
thinkingForcedOpen: true,
parser: result.parser,
tokenCount: result.tokenCount,
) => withSingleToolCall(
withThinkingForcedClosed(
LlamaChatTemplateResult(
prompt: result.prompt,
format: result.format,
grammar: result.grammar,
grammarLazy: result.grammarLazy,
additionalStops: result.additionalStops,
preservedTokens: result.preservedTokens,
grammarTriggers: result.grammarTriggers,
thinkingForcedOpen: true,
parser: result.parser,
tokenCount: result.tokenCount,
),
closed: thinkingForcedClosedOf(result),
),
closed: thinkingForcedClosedOf(result),
single: singleToolCallOf(result),
);

/// [tokens] with their text held until it contains one of [markers], or
Expand Down
9 changes: 9 additions & 0 deletions lib/src/core/template/chat_format_registry.dart
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ final class ChatFormatTraits {
this.keepsForcedThoughtVerbatim = false,
this.closedThoughtKeepsTagsAsContent = false,
this.takesThoughtOnlyAtReplyStart = false,
this.reopensThoughtClosedForThinkingOff = false,
this.forcedThoughtContentOpenings = const [],
this.mayEmbedToolEnvelopeAfterContent = false,
this.hasRepeatedContentChannels = false,
Expand Down Expand Up @@ -131,6 +132,11 @@ final class ChatFormatTraits {
/// only at the start of the reply, so other thinking tags are content.
final bool takesThoughtOnlyAtReplyStart;

/// Whether llama.cpp keeps open the thought the handler closed for thinking
/// off, so a reply that shows a thinking tag or one of
/// [forcedThoughtContentOpenings] parses as after a forced-open prompt.
final bool reopensThoughtClosedForThinkingOff;

/// 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 @@ -300,6 +306,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
qualifiesJsonSchemaTools: false,
toolCallOpening: CommandR7BHandler.toolCallOpening,
keepsForcedThoughtVerbatim: true,
reopensThoughtClosedForThinkingOff: true,
forcedThoughtContentOpenings:
Cohere2MoeHandler.forcedThoughtContentOpenings,
disabledByResponseSchema: true,
Expand Down Expand Up @@ -384,6 +391,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
toolCallOpening: XmlToolCallFormat.qwen3Coder.toolCallOpening,
closedThoughtKeepsTagsAsContent: true,
keepsForcedThoughtVerbatim: true,
reopensThoughtClosedForThinkingOff: true,
forcedThoughtContentOpenings: [XmlToolCallFormat.qwen3CoderScopeStart],
),
),
Expand Down Expand Up @@ -448,6 +456,7 @@ chatFormatRegistrations = List.unmodifiable(<ChatFormatRegistration>[
qualifiesJsonSchemaTools: false,
toolCallOpening: XmlToolCallFormat.seedOss.toolCallOpening,
keepsForcedThoughtVerbatim: true,
reopensThoughtClosedForThinkingOff: true,
),
),
ChatFormatRegistration(
Expand Down
39 changes: 29 additions & 10 deletions lib/src/core/template/chat_template_engine.dart
Original file line number Diff line number Diff line change
Expand Up @@ -759,6 +759,7 @@ class ChatTemplateEngine {
parseToolCalls: parseToolCalls,
thinkingForcedOpen: rendered.thinkingForcedOpen,
thinkingForcedClosed: thinkingForcedClosedOf(rendered),
singleToolCall: singleToolCallOf(rendered),
parser: rendered.parser,
tools: tools,
);
Expand All @@ -782,6 +783,7 @@ class ChatTemplateEngine {
required bool thinkingForcedOpen,
required bool thinkingForcedClosed,
bool promptOpensNoThought = false,
bool singleToolCall = false,
String? parser,
List<ToolDefinition>? tools,
}) {
Expand All @@ -794,6 +796,7 @@ class ChatTemplateEngine {
thinkingForcedOpen: thinkingForcedOpen,
thinkingForcedClosed: thinkingForcedClosed,
promptOpensNoThought: promptOpensNoThought,
singleToolCall: singleToolCall,
parser: parser,
tools: tools,
);
Expand Down Expand Up @@ -845,6 +848,7 @@ class ChatTemplateEngine {
required bool thinkingForcedOpen,
required bool thinkingForcedClosed,
required bool promptOpensNoThought,
required bool singleToolCall,
String? parser,
List<ToolDefinition>? tools,
}) {
Expand Down Expand Up @@ -910,6 +914,7 @@ class ChatTemplateEngine {
parseToolCalls: parseToolCalls,
thinkingForcedOpen: thinkingForcedOpen,
thoughtTagsAreText: thoughtTagsAreText,
singleToolCall: singleToolCall,
);
} else if (handler is DeepseekV3Handler) {
result = handler.parse(
Expand Down Expand Up @@ -1146,29 +1151,42 @@ bool takesThoughtOnlyAtReplyStart(int 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.
/// for thinking off: the format's thinking tags and its
/// [ChatFormatTraits.forcedThoughtContentOpenings], such as where a Cohere2
/// MoE text or action starts, as llama.cpp ends the thought it keeps open.
List<String> closedThoughtMarkers(int formatIndex) {
final tags = ChatTemplateEngine.thinkingTagsFor(formatIndex);
return [
tags.startTag,
tags.endTag,
if (formatIndex == ChatFormat.cohere2Moe.index)
...Cohere2MoeHandler.forcedThoughtContentOpenings,
..._traitsOf(formatIndex).forcedThoughtContentOpenings,
];
}

/// Whether llama.cpp keeps open the thought that a [formatIndex] handler
/// closed for thinking off, so that a reply showing one of
/// [closedThoughtMarkers] parses as after a forced-open prompt.
bool reopensClosedThought(int formatIndex) =>
_traitsOf(formatIndex).reopensThoughtClosedForThinkingOff;

ChatFormatTraits _traitsOf(int formatIndex) =>
formatIndex < ChatFormat.values.length
? chatFormatRegistration(ChatFormat.values[formatIndex]).traits
: ChatFormatTraits.none;

/// Parses [output] of a render of this engine, whose internal thought mark
/// [ChatTemplateEngine.parse] cannot see.
///
/// llama.cpp keeps open the thought a Seed-OSS or Cohere2 MoE handler closed
/// for thinking off ([thoughtClosedForThinkingOff]), so a reply that shows one
/// of [closedThoughtMarkers] parses as after a forced-open prompt. Without it
/// llama.cpp keeps open the thought a Seed-OSS, Cohere2 MoE or Qwen3-Coder XML
/// handler closed 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, 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.
/// start tag keeps its thinking tags as content. With [singleToolCall], a
/// Qwen3-Coder XML reply has at most one tool call.
ChatParseResult parseRenderedOutput(
int formatIndex,
String output, {
Expand All @@ -1178,6 +1196,7 @@ ChatParseResult parseRenderedOutput(
bool parseToolCalls = true,
bool thinkingForcedOpen = false,
bool thinkingForcedClosed = false,
bool singleToolCall = false,
String? parser,
List<ToolDefinition>? tools,
}) => ChatTemplateEngine._parseOutput(
Expand All @@ -1189,11 +1208,11 @@ ChatParseResult parseRenderedOutput(
thinkingForcedOpen:
thinkingForcedOpen ||
(thoughtClosedForThinkingOff &&
(formatIndex == ChatFormat.seedOss.index ||
formatIndex == ChatFormat.cohere2Moe.index) &&
reopensClosedThought(formatIndex) &&
closedThoughtMarkers(formatIndex).any(output.contains)),
thinkingForcedClosed: thinkingForcedClosed,
promptOpensNoThought: !thoughtClosedForThinkingOff,
singleToolCall: singleToolCall,
parser: parser,
tools: tools,
);
Expand Down
24 changes: 18 additions & 6 deletions lib/src/core/template/handlers/qwen3_coder_xml_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,9 @@ class Qwen3CoderXmlHandler extends ChatTemplateHandler
metadata[internalParallelToolCallsMetadataKey] == 'true';
final toolChoiceNone = toolChoice == ToolChoice.none.name;
final toolChoiceRequired = toolChoice == ToolChoice.required.name;
final thinkingForcedClosed = isThinkingForcedClosed(prompt);
// llama.cpp takes no thought from a reply to a template without one.
final thinkingForcedClosed =
isThinkingForcedClosed(prompt) || !templateSource.contains('<think>');
var thinkingForcedOpen = false;
var thoughtClosed = false;
if (isThinkingForcedOpen(prompt, startTag: '<think>')) {
Expand Down Expand Up @@ -145,9 +147,12 @@ class Qwen3CoderXmlHandler extends ChatTemplateHandler
: const [],
parser: parser,
);
return withThoughtClosedForThinkingOff(
withThinkingForcedClosed(rendered, closed: thinkingForcedClosed),
closed: thoughtClosed,
return withSingleToolCall(
withThoughtClosedForThinkingOff(
withThinkingForcedClosed(rendered, closed: thinkingForcedClosed),
closed: thoughtClosed,
),
single: hasTools && !parallelToolCalls,
);
}

Expand Down Expand Up @@ -306,8 +311,12 @@ class Qwen3CoderXmlHandler extends ChatTemplateHandler
}

/// Parses Qwen XML using declared tool schemas when [tools] is supplied.
/// Invalid calls remain content and cannot become executable tool deltas.
/// With [thoughtTagsAreText], all of [output] is content and tool calls.
///
/// As in llama.cpp, the content ends at the first `<tool_call>`, the calls
/// are those of the valid scopes that follow it, only the first with
/// [singleToolCall], and the rest of the reply is dropped, so an invalid
/// call never becomes an executable tool delta. With [thoughtTagsAreText],
/// all of [output] is content and tool calls.
@override
ChatParseResult parseWithTools(
String output, {
Expand All @@ -316,6 +325,7 @@ class Qwen3CoderXmlHandler extends ChatTemplateHandler
bool parseToolCalls = true,
bool thinkingForcedOpen = false,
bool thoughtTagsAreText = false,
bool singleToolCall = false,
}) {
final result = parseXmlToolCalls(
output,
Expand All @@ -329,6 +339,8 @@ class Qwen3CoderXmlHandler extends ChatTemplateHandler
// (`620d2225`) a forced-open thought as generated.
unescapeReasoning: false,
verbatimForcedThought: true,
endsAtLastCall: true,
maxToolCalls: singleToolCall ? 1 : null,
);
return ChatParseResult(
content: result.content.trim(),
Expand Down
20 changes: 20 additions & 0 deletions lib/src/core/template/template_internal_metadata.dart
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,23 @@ LlamaChatTemplateResult withLfm2AutoGrammarOf(
copy.grammar == source.grammar &&
copy.grammarLazy == source.grammarLazy,
);

final Expando<bool> _singleToolCall = Expando<bool>('llamadart.singleToolCall');

/// Returns [result], marked when [single] as a render whose request allows at
/// most one tool call.
///
/// The Qwen3-Coder XML parse then takes only the first call, as llama.cpp's
/// parser does without parallel tool calls. Internal engine plumbing, not part
/// of the public API.
LlamaChatTemplateResult withSingleToolCall(
LlamaChatTemplateResult result, {
required bool single,
}) {
if (single) _singleToolCall[result] = true;
return result;
}

/// Whether [withSingleToolCall] marked [result].
bool singleToolCallOf(LlamaChatTemplateResult result) =>
_singleToolCall[result] ?? false;
15 changes: 10 additions & 5 deletions lib/src/core/template/thinking_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,8 @@ final Expando<bool> _thinkingForcedClosed = Expando<bool>(
);

/// Returns [result], marked when [closed] as rendered by a template that ended
/// the prompt with an empty thought.
/// the prompt with an empty thought or, for Qwen3-Coder XML, that has no
/// thinking tags.
///
/// Only the template's own render counts, not a thought a handler closes
/// because thinking is off. The DeepSeek V3, Hermes and Qwen3-Coder XML
Expand Down Expand Up @@ -331,14 +332,18 @@ LlamaChatTemplateResult withThoughtClosedForThinkingOff(
bool thoughtClosedForThinkingOffOf(LlamaChatTemplateResult result) =>
_thoughtClosedForThinkingOff[result] ?? false;

/// Returns [copy] with the thought marks of [source], which it copies.
/// Returns [copy] with the thought and tool-call marks of [source], which it
/// copies.
LlamaChatTemplateResult withThoughtMarksOf(
LlamaChatTemplateResult copy,
LlamaChatTemplateResult source,
) => withLfm2AutoGrammarOf(
withThoughtClosedForThinkingOff(
withThinkingForcedClosed(copy, closed: thinkingForcedClosedOf(source)),
closed: thoughtClosedForThinkingOffOf(source),
withSingleToolCall(
withThoughtClosedForThinkingOff(
withThinkingForcedClosed(copy, closed: thinkingForcedClosedOf(source)),
closed: thoughtClosedForThinkingOffOf(source),
),
single: singleToolCallOf(source),
),
source,
);
Expand Down
Loading
Loading