groupMessagesByApiRound function
Group messages by API round. The preamble (all messages up to and including the first assistant message) forms group 0. Each subsequent assistant message starts a new group (the assistant + all following user/attachment messages until the next assistant).
Implementation
List<List<CompactMessage>> groupMessagesByApiRound(
List<CompactMessage> messages,
) {
if (messages.isEmpty) return [];
final groups = <List<CompactMessage>>[];
var currentGroup = <CompactMessage>[];
bool seenFirstAssistant = false;
for (final msg in messages) {
if (msg.type == MessageRole.assistant) {
if (!seenFirstAssistant) {
// Include this assistant in the preamble group
currentGroup.add(msg);
groups.add(currentGroup);
currentGroup = <CompactMessage>[];
seenFirstAssistant = true;
} else {
// Start a new group with this assistant
if (currentGroup.isNotEmpty) {
groups.add(currentGroup);
}
currentGroup = [msg];
}
} else {
currentGroup.add(msg);
}
}
if (currentGroup.isNotEmpty) {
groups.add(currentGroup);
}
return groups;
}