TokenCounter¶
Token counting using tiktoken.
Quick Example¶
from mamba_agents.tokens import TokenCounter
counter = TokenCounter(encoding="cl100k_base")
# Count text tokens
count = counter.count("Hello, world!")
# Count message tokens
messages = [
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi!"},
]
count = counter.count_messages(messages)
API Reference¶
TokenCounter
¶
Token counting using tiktoken.
Provides methods for counting tokens in text and message lists. Token counts are approximate and may vary from actual model tokenization.
Initialize the token counter.
| PARAMETER | DESCRIPTION |
|---|---|
config
|
Optional tokenizer configuration.
TYPE:
|
Source code in src/mamba_agents/tokens/counter.py
count
¶
Count tokens in text.
| PARAMETER | DESCRIPTION |
|---|---|
text
|
The text to count tokens in.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
Approximate token count. |
count_messages
¶
Count tokens in a message list.
Estimates tokens for a list of chat messages, accounting for message structure overhead.
| PARAMETER | DESCRIPTION |
|---|---|
messages
|
List of message dictionaries with 'role' and 'content'.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
Approximate total token count. |
Source code in src/mamba_agents/tokens/counter.py
count_with_margin
¶
Count tokens with safety margin.
| PARAMETER | DESCRIPTION |
|---|---|
text
|
The text to count.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
Token count plus safety margin. |
Source code in src/mamba_agents/tokens/counter.py
fits_context
¶
Check if text fits within a context window.
| PARAMETER | DESCRIPTION |
|---|---|
text
|
The text to check.
TYPE:
|
max_tokens
|
Maximum token count.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if text fits (with safety margin). |
Source code in src/mamba_agents/tokens/counter.py
get_encoding_for_model
¶
Get the appropriate encoding for a model.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
Model name or identifier.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Encoding name to use. |