Count Tokens

Count tokens in text using .CountTokens().

Basic Usage

int count = await "Hello, world!"
    .CountTokens()
    .ExecuteAsync();

Debug.Log($"Token count: {count}");

Input Types

String Input

int count = await "Sample text"
    .CountTokens()
    .ExecuteAsync();

Message Input

var message = new UserMessage("Hello, AI!");
int count = await message
    .CountTokens()
    .ExecuteAsync();

Unity Integration Examples

Example 1: Budget Manager

Example 2: Cost Estimator

Example 3: Real-time Token Counter

Example 4: Conversation Token Tracker

Provider Support

OpenAI

Anthropic

Google

Token Counting vs Tokenization

Method
Returns
Performance
Use Case

.CountTokens()

int

Faster

Budget checks

.Tokenize()

int[]

Slower

Detailed analysis

Best Practices

✅ Good Practices

❌ Bad Practices

Performance Tips

Common Token Counts

Text
Approximate Tokens

Single word

1-2

Short sentence

10-20

Paragraph

50-100

Page of text

300-500

Article

1000-2000

Next Steps

Last updated