Computes Anthropic vision token usage for an image with given dimensions and tier, resizing via binary search to respect long-edge and token caps.
export function anthropicImageTokens(width: number, height: number, tier: AnthropicVisionTier): number {
const { longEdgeMax, tokenCap } = ANTHROPIC_TIER_CAPS[tier];
if (Math.max(width, height) <= longEdgeMax && patchTokens(width, height) <= tokenCap) {
return patchTokens(width, height);
}
const long = Math.max(width, height);
const short = Math.min(width, height);
const tokensAt = (edge: number): number => patchTokens(edge, Math.round((short * edge) / long));
let lo = PATCH_PX;
let hi = Math.min(longEdgeMax, long);
while (lo < hi) {
const mid = Math.ceil((lo + hi + 1) / 2);
if (tokensAt(mid) <= tokenCap) lo = mid;
else hi = mid - 1;
}
return tokensAt(lo);
}
See the full source, get the GitHub permalink, and search 40K more like it.
Get a free API key