Interface TokenCounter
- Functional Interface:
- This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
Functional interface for counting tokens in messages.
Implementations of this interface provide different strategies for estimating token counts in conversation messages.
Example: TokenCounter counter = messages -> { int total = 0; for (Message msg : messages) { total += msg.getText().length() / 4; } return total; };-
Field Summary
Fields -
Method Summary
Modifier and TypeMethodDescriptionstatic TokenCounterstatic TokenCounterapproximateMsgCounter(int charsPerToken) Creates a token counter with a custom character-to-token ratio.intcountTokens(List<org.springframework.ai.chat.messages.Message> messages) Count the approximate number of tokens in the given messages.
-
Field Details
-
DEFAULT_CHARS_PER_TOKEN
static final int DEFAULT_CHARS_PER_TOKEN- See Also:
-
-
Method Details
-
approximateMsgCounter
-
approximateMsgCounter
Creates a token counter with a custom character-to-token ratio. Handles ToolResponseMessage (processing ToolResponse) and AssistantMessage (processing ToolCall).- Parameters:
charsPerToken- The average number of characters per token- Returns:
- A token counter using the specified ratio
-
countTokens
Count the approximate number of tokens in the given messages.- Parameters:
messages- The list of messages to count tokens for- Returns:
- The estimated token count
-