Token
AgentScope provides a token counter module under agentscope.token to calculate the number of tokens in the given messages, allowing developers to estimate the number of tokens in a prompt before sending it to an API.
Specifically, the following token counters are available:
Provider | Class | Support Image Data | Support Tools |
|---|---|---|---|
Anthropic |
| ✅ | ✅ |
OpenAI |
| ✅ | ✅ |
Gemini |
| ✅ | ✅ |
HuggingFace |
| Depends on the model | Depends on the model |
Tip
The formatter module has integrated the token counters to support prompt truncation. Refer to the Prompt Formatter section for more details.
Note
For DashScope models, the dashscope library doesn’t provide a token counting API. So we recommend using the HuggingFace token counter instead.
We show an example of using the OpenAI token counter to count the number of tokens:
import asynciofrom agentscope.token import OpenAITokenCounterasync def example_token_counting():# Example messagesmessages = [{"role": "user", "content": "Hello!"},{"role": "assistant", "content": "Hi, how can I help you?"},]# OpenAI token countingopenai_counter = OpenAITokenCounter(model_name="gpt-4.1")n_tokens = await openai_counter.count(messages)print(f"Number of tokens: {n_tokens}")asyncio.run(example_token_counting())
Number of tokens: 21
Further Reading
Total running time of the script: (0 minutes 0.969 seconds)
Download Jupyter notebook: task_token.ipynb
Download Python source code: task_token.py