render method

Lfm2Prompt render(
  1. Iterable<ChatMessage> messages, {
  2. Iterable<AIFunctionDeclaration> tools = const <AIFunctionDeclaration>[],
  3. bool enableThinking = false,
  4. bool addGenerationPrompt = true,
})

Renders messages (with optional tools) into an LFM2 prompt.

enableThinking is ignored — LFM2's default template has no reasoning channel. When addGenerationPrompt is true a trailing <|im_start|>assistant\n is appended.

Implementation

Lfm2Prompt render(
  Iterable<ChatMessage> messages, {
  Iterable<AIFunctionDeclaration> tools = const <AIFunctionDeclaration>[],
  bool enableThinking = false,
  bool addGenerationPrompt = true,
}) {
  final all = messages.toList();
  final toolList = tools.toList();
  final out = StringBuffer();
  final images = <Uint8List>[];

  // System turn: an explicit leading system message and/or the tool list.
  var loopStart = 0;
  final system = StringBuffer();
  if (all.isNotEmpty && _roleOf(all.first) == 'system') {
    system.write(all.first.text);
    loopStart = 1;
  }
  if (toolList.isNotEmpty) {
    if (system.isNotEmpty) system.write('\n');
    system
      ..write('List of tools: ')
      ..write(_formatDeclarations(toolList));
    if (toolCallSyntax == LfmToolCallSyntax.json) {
      system.write('\nOutput function calls as JSON.');
    }
  }
  if (system.isNotEmpty) {
    out
      ..write(imStart)
      ..write('system\n')
      ..write(system)
      ..write(imEnd)
      ..write('\n');
  }

  for (final msg in all.sublist(loopStart)) {
    final role = _roleOf(msg);
    out
      ..write(imStart)
      ..write(role)
      ..write('\n')
      ..write(_contentFor(msg, role, images))
      ..write(imEnd)
      ..write('\n');
  }

  if (addGenerationPrompt) {
    out
      ..write(imStart)
      ..write('assistant\n');
  }

  return Lfm2Prompt(
    text: out.toString(),
    stopSequences: stopSequences,
    images: images,
  );
}