renderChat function
Renders a conversation exactly as tokenizer.apply_chat_template does.
Implementation
String renderChat(
List<Map<String, Object?>> messages, {
List<Map<String, Object?>>? tools,
bool addGenerationPrompt = true,
bool enableThinking = true,
bool preserveThinking = false,
}) {
final out = StringBuffer('<|startoftext|>');
var rest = messages;
var system = '';
if (rest.isNotEmpty && rest.first['role'] == 'system') {
if (_truthy(rest.first['content'])) {
system = _parseContent(rest.first['content']);
}
rest = rest.sublist(1);
}
final lines = [
for (final tool in tools ?? const <Map<String, Object?>>[])
if (!_truthy(_function(tool)['defer_loading']) &&
!_truthy(tool['defer_loading']))
_toolToJson(tool),
];
if (lines.isNotEmpty) {
system =
'$system${system.isEmpty ? '' : '\n\n'}<tools>\n${lines.join('\n')}\n</tools>';
}
if (system.isNotEmpty) out.write('<|im_start|>system\n$system<|im_end|>\n');
final lastUser = rest.lastIndexWhere((m) => m['role'] == 'user');
// Items of tool messages waiting to merge into the next one.
var pending = <Object?>[];
for (var i = 0; i < rest.length; i++) {
final message = rest[i];
final role = message['role'] as String;
final next = i + 1 < rest.length ? rest[i + 1] : null;
final plainTool = role == 'tool' && !_truthy(message['additional_tools']);
final items = plainTool ? _toolItems(message['content']) : const [];
if (plainTool &&
next != null &&
next['role'] == 'tool' &&
!_truthy(next['additional_tools']) &&
_truthy(message['tool_call_id']) &&
next['tool_call_id'] == message['tool_call_id']) {
pending = [...pending, ...items];
continue;
}
out.write('<|im_start|>$role\n');
switch (role) {
case 'assistant':
out.write(_assistant(message, preserveThinking || i > lastUser));
case 'tool' when !plainTool:
out.write(_additionalTools(message));
case 'tool' when pending.isNotEmpty:
out.write(_toolResponse([...pending, ...items], tools));
pending = [];
case 'tool':
out.write(_toolResponse(message['content'] ?? '', tools));
default:
if (_truthy(message['content'])) {
out.write(_parseContent(message['content']));
}
}
out.write('<|im_end|>\n');
}
if (addGenerationPrompt) {
out.write('<|im_start|>assistant\n');
out.write(enableThinking ? '<think>' : '<think></think>');
}
return out.toString();
}