Advanced

Best Practices

Master prompt optimization, context window management, token-efficient formatting, production monitoring, and avoid common tokenization pitfalls.

Prompt Optimization for Fewer Tokens

Writing token-efficient prompts saves money without sacrificing output quality:

Be Direct and Concise

Remove filler words, unnecessary politeness, and redundant instructions. AI models do not need pleasantries to produce good output.

Before & After
# BEFORE (~85 tokens):
"Hi there! I would really appreciate your help with
something. Could you please take a look at the text
below and provide me with a brief summary of the main
points? I'd like the summary to be concise and capture
the key ideas. Thank you so much in advance!"

# AFTER (~10 tokens):
"Summarize the key points of this text:"

# Same quality output, ~88% fewer input tokens

Use Abbreviations and Shorthand in System Prompts

System prompts are sent with every request, so even small savings multiply across thousands of calls:

System Prompt Optimization
# VERBOSE system prompt (~120 tokens):
"You are a professional software developer who specializes
in writing Python code. When the user asks you to write code,
always include type hints, docstrings, and follow PEP 8
coding standards. Handle edge cases and include error handling.
Format all code using markdown code blocks with the Python
language identifier."

# OPTIMIZED system prompt (~35 tokens):
"Expert Python dev. Always: type hints, docstrings, PEP 8,
error handling, edge cases. Use ```python code blocks."

Fitting Within Context Windows

When your content exceeds the model's context window, you need strategies to manage it:

When to Truncate vs. Summarize

Approach Best When Trade-off
Truncate (cut off) Recent context is most important (chat history) Loses older information entirely
Summarize All context matters but is too long Costs extra API call, may lose details
Sliding window Ongoing conversations Keeps recent + summary of older
RAG (retrieval) Large knowledge bases More complex architecture needed
Python (Sliding Window)
import tiktoken

def trim_messages(messages, max_tokens=4000, model="gpt-4o"):
    """Keep the most recent messages within the token limit."""
    enc = tiktoken.encoding_for_model(model)
    total = 0
    trimmed = []

    # Always keep system message
    system_msg = messages[0] if messages[0]["role"] == "system" else None
    if system_msg:
        total += len(enc.encode(system_msg["content"])) + 4
        trimmed.append(system_msg)

    # Add messages from newest to oldest
    user_msgs = messages[1:] if system_msg else messages
    for msg in reversed(user_msgs):
        msg_tokens = len(enc.encode(msg["content"])) + 4
        if total + msg_tokens > max_tokens:
            break
        total += msg_tokens
        trimmed.insert(1 if system_msg else 0, msg)

    return trimmed

Token-Efficient Formatting

The format you use for data and instructions affects token count significantly:

  • Plain text over JSON: JSON's structural characters (braces, colons, quotes) add 30-50% more tokens. Use plain text or CSV format when possible.
  • Markdown over HTML: Markdown is much more compact than HTML. # Title uses far fewer tokens than <h1>Title</h1>.
  • Numbered lists over verbose bullets: Use 1. Item instead of - The first item is: Item.
  • Shorter variable names in examples: In code examples within prompts, use short but clear names.
Format Comparison
# JSON format (~45 tokens):
{"users": [{"name": "Alice", "role": "admin"}, {"name": "Bob", "role": "user"}]}

# CSV format (~15 tokens):
name,role
Alice,admin
Bob,user

# Plain text (~12 tokens):
Alice (admin), Bob (user)

Monitoring Token Usage in Production

Track token usage to catch anomalies and optimize over time:

Python (Token Usage Tracker)
import logging
from datetime import datetime

logger = logging.getLogger("token_usage")

def log_usage(response, model, endpoint):
    usage = response.usage
    cost = calculate_cost(model, usage.prompt_tokens, usage.completion_tokens)

    logger.info(
        "API Call | model=%s | input=%d | output=%d | "
        "total=%d | cost=$%.4f | endpoint=%s | time=%s",
        model,
        usage.prompt_tokens,
        usage.completion_tokens,
        usage.total_tokens,
        cost,
        endpoint,
        datetime.now().isoformat(),
    )

    # Alert on unusually high token counts
    if usage.total_tokens > 10000:
        logger.warning(
            "High token usage detected: %d tokens ($%.4f)",
            usage.total_tokens,
            cost,
        )

Common Tokenization Gotchas

Watch out for these surprising tokenization behaviors that can catch developers off guard:

1. Whitespace Matters

Leading and trailing spaces, multiple spaces, and newlines all consume tokens. A single space is often attached to the next word's token, but extra spaces create additional tokens.

2. Numbers Are Unpredictable

Numbers are not tokenized digit-by-digit. 2024 might be one or two tokens, while 123456789 could be several tokens with unexpected splits. Always check with Tiktokenizer.

3. Non-ASCII Characters Cost More

Emojis, accented characters, and CJK characters typically use 2-4 tokens each, even though they are single characters.

4. Repeated Text Is Not "Free"

Unlike compression algorithms, tokenizers do not benefit from repeated patterns. Copying the same paragraph 10 times uses 10x the tokens.

5. Prompt Templates Add Up

If your prompt template includes boilerplate instructions, those tokens are charged on every request. A 200-token template across 10,000 daily requests = 2 million input tokens per day.

Common mistake: Developers often estimate token counts by dividing word count by 4. This approximation is only valid for standard English text. Code, JSON, URLs, and non-English text will be significantly higher. Always use an actual tokenizer for accurate counts.

Frequently Asked Questions

Tiktokenizer uses OpenAI's tiktoken library, which provides tokenizers for OpenAI models. Claude uses a different tokenizer, so counts from Tiktokenizer are approximate for Claude. However, the cl100k_base tokenizer gives a reasonable estimate (usually within 10-15%) for Claude token counts. For exact Claude counts, use Anthropic's token counting API endpoint.

No. Tiktokenizer runs entirely in your browser using WebAssembly. Your text never leaves your computer, making it safe to use with confidential or proprietary content.

Each tokenizer has a different vocabulary and was trained on different data. A larger vocabulary (like o200k_base with 200K tokens) can represent more common patterns as single tokens, resulting in lower token counts. Older tokenizers with smaller vocabularies split text into more, smaller tokens.

Multi-turn conversations accumulate tokens because the full history is sent with each request. Strategies include: (1) summarize older messages into a brief context summary, (2) use a sliding window that keeps only the last N messages, (3) implement RAG to retrieve relevant past context instead of sending everything, (4) periodically ask the model to summarize the conversation so far.

Not necessarily. Extremely short prompts may sacrifice output quality. The goal is to find the right balance: remove unnecessary verbosity while keeping enough context and instructions for the model to produce high-quality output. Test both shorter and longer prompts to find the sweet spot for your use case.

Congratulations! You have completed the Tiktokenizer course. You now understand tokenization, can count tokens accurately, estimate API costs, and optimize your prompts for efficiency. Use these skills to build cost-effective, well-optimized AI applications.

Ready to Go Deeper?

Live instructor-led courses from our partners. Affiliate disclosure.