estimateMessageTokens function

int estimateMessageTokens(
  1. List<Map<String, dynamic>> messages
)

Estimate tokens for a list of messages.

Implementation

int estimateMessageTokens(List<Map<String, dynamic>> messages) {
  var total = 0;
  for (final msg in messages) {
    // Base overhead per message
    total += 4;
    final content = msg['content'];
    if (content is String) {
      total += estimateTokens(content);
    } else if (content is List) {
      for (final block in content) {
        if (block is Map<String, dynamic>) {
          if (block['type'] == 'text') {
            total += estimateTokens(block['text'] as String? ?? '');
          } else if (block['type'] == 'tool_use') {
            total += estimateTokens(jsonEncode(block['input']));
          } else if (block['type'] == 'tool_result') {
            total += estimateTokens(block['content'] as String? ?? '');
          }
        }
      }
    }
  }
  return total;
}