tokenCountWithEstimation function
Estimate total token count across messages.
Implementation
int tokenCountWithEstimation(List<SessionMessage> messages) {
var total = 0;
for (final msg in messages) {
total += msg.inputTokens ?? 0;
total += msg.outputTokens ?? 0;
total += msg.cacheReadInputTokens ?? 0;
total += msg.cacheCreationInputTokens ?? 0;
}
// Fallback: if no token info, estimate from content.
if (total == 0) {
for (final msg in messages) {
for (final block in msg.content) {
if (block.text != null) {
total += roughTokenCountEstimation(block.text!);
}
}
}
}
return total;
}