prepareVisionPrompt function

VisionPrompt prepareVisionPrompt(
  1. List<Map<String, Object?>> messages, {
  2. required Lfm3Tokenizer tokenizer,
  3. required Lfm3VlConfig config,
  4. required List<int> imageTokenCounts,
  5. List<Map<String, Object?>>? tools,
  6. bool enableThinking = true,
  7. bool preserveThinking = false,
})

Tokenizes a VL conversation and repeats each image placeholder to match imageTokenCounts, in message/content order, as the upstream processor does. These counts are VisionImageInput.imageTokens (or encoder row counts). Checks tokenizer/config special-token agreement and rejects unbound image or video tokens, including placeholders embedded in plain text.

Implementation

VisionPrompt prepareVisionPrompt(
  List<Map<String, Object?>> messages, {
  required Lfm3Tokenizer tokenizer,
  required Lfm3VlConfig config,
  required List<int> imageTokenCounts,
  List<Map<String, Object?>>? tools,
  bool enableThinking = true,
  bool preserveThinking = false,
}) {
  final imageCount = messages.fold(
    0,
    (count, message) =>
        count +
        _imageCount(message['content'], toolItems: message['role'] == 'tool'),
  );
  if (imageCount != imageTokenCounts.length ||
      imageTokenCounts.any((n) => n <= 0)) {
    throw ArgumentError('one positive token count is required per image part');
  }
  for (final token in {
    '<|image|>': config.imageTokenId,
    '<|vision_start|>': config.visionStartTokenId,
    '<|vision_end|>': config.visionEndTokenId,
    '<|video|>': config.videoTokenId,
  }.entries) {
    if (tokenizer.addedTokenId(token.key) != token.value) {
      throw FormatException('VL tokenizer/config mismatch for ${token.key}');
    }
  }
  final raw = tokenizer.encode(
    renderVisionChat(
      messages,
      tools: tools,
      enableThinking: enableThinking,
      preserveThinking: preserveThinking,
    ),
  );
  final ids = <int>[];
  final spans = <VisionTokenSpan>[];
  for (var at = 0; at < raw.length; at++) {
    final id = raw[at];
    if (id == config.videoTokenId) {
      throw UnsupportedError('video input is not supported');
    }
    if (id != config.imageTokenId) {
      ids.add(id);
      continue;
    }
    if (spans.length >= imageCount ||
        at == 0 ||
        at + 1 >= raw.length ||
        raw[at - 1] != config.visionStartTokenId ||
        raw[at + 1] != config.visionEndTokenId) {
      throw ArgumentError('unbound or malformed image placeholder');
    }
    final count = imageTokenCounts[spans.length];
    spans.add(VisionTokenSpan(ids.length, count));
    ids.addAll(List.filled(count, id));
  }
  if (spans.length != imageCount) {
    throw ArgumentError('rendered image count mismatch');
  }
  return VisionPrompt._(ids, spans, config.text.hiddenSize);
}