buildMessages method

List<ChatMessage> buildMessages(
  1. String question,
  2. List<RagSource> sources, {
  3. List<ChatMessage> history = const [],
  4. List<RagSource>? included,
})

The prompt for question over sources, after history.

Writes into included (when given) exactly the sources that fitted the maxContextChars budget, so a caller can report the evidence the model actually saw rather than everything retrieved.

Implementation

List<ChatMessage> buildMessages(
  String question,
  List<RagSource> sources, {
  List<ChatMessage> history = const [],
  List<RagSource>? included,
}) {
  final context = StringBuffer('<sources>\n');
  var used = 0;
  for (final s in sources) {
    final entry = StringBuffer()
      ..write('<source number="${s.number}"')
      ..write(s.documentId == null ? '' : ' document="${s.documentId}"')
      ..write('>\n')
      ..write(s.text)
      ..write('\n</source>\n');
    // The wrapper counts too, so the stated cap is the real one.
    if (used > 0 && used + entry.length > maxContextChars) continue;
    used += entry.length;
    context.write(entry);
    included?.add(s);
  }
  context.write('</sources>\n\nQuestion: $question');
  return [...history, ChatMessage.user(context.toString())];
}