estimateTokens (utils/tokens.ts)

open-agent-sdk-typescript · src/utils/tokens.ts · typescript · MIT
ai, AI / Agents

TypeScript utilities for estimating token usage and cost for LLM models.

// Source: https://github.com/codeany-ai/open-agent-sdk-typescript | License: MIT | Copyright 2025 CodeAny (https://codeany.ai)
// Provided via justclaw.it.com; keep this notice with the code.
/**
 * Token Estimation & Counting
 *
 * Provides rough token estimation (character-based) and
 * API-based exact counting when available.
 */

/**
 * Rough token estimation: ~4 chars per token (conservative).
 */
export function estimateTokens(text: string): number {
  return Math.ceil(text.length / 4)
}

/**
 * Estimate tokens for a message array.
 */
export function estimateMessagesTokens(
  messages: Array<{ role: string; content: any }>,
): number {
  let total = 0
  for (const msg of messages) {
    if (typeof msg.content === 'string') {
      total += estimateTokens(msg.content)
    } else if 

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key