|
| 1 | +--- |
| 2 | +title: "Token Counters" |
| 3 | +id: token-counters-api |
| 4 | +description: "Estimate how many tokens a conversation occupies, for features that need a size before sending it to a model." |
| 5 | +slug: "/token-counters-api" |
| 6 | +--- |
| 7 | + |
| 8 | + |
| 9 | +## approximate_counter |
| 10 | + |
| 11 | +### ApproximateTokenCounter |
| 12 | + |
| 13 | +Bases: <code>TokenCounter</code> |
| 14 | + |
| 15 | +Estimates tokens from text length using a flat ratio of characters to tokens. |
| 16 | + |
| 17 | +## Usage Example: |
| 18 | + |
| 19 | +```python |
| 20 | +from haystack.dataclasses import ChatMessage |
| 21 | +from haystack.token_counters import ApproximateTokenCounter |
| 22 | + |
| 23 | +counter = ApproximateTokenCounter(chars_per_token=4.0) |
| 24 | +messages = [ |
| 25 | + ChatMessage.from_user("Hello, how are you?"), |
| 26 | + ChatMessage.from_assistant("I'm good, thank you! How can I assist you today?") |
| 27 | +] |
| 28 | +token_count = counter.count(messages) |
| 29 | +print(f"Estimated token count: {token_count}") |
| 30 | +``` |
| 31 | + |
| 32 | +#### __init__ |
| 33 | + |
| 34 | +```python |
| 35 | +__init__( |
| 36 | + chars_per_token: float = 4.0, |
| 37 | + tokens_per_image: int = 85, |
| 38 | + tokens_per_file: int = 1000, |
| 39 | +) -> None |
| 40 | +``` |
| 41 | + |
| 42 | +Initialize the counter. |
| 43 | + |
| 44 | +**Parameters:** |
| 45 | + |
| 46 | +- **chars_per_token** (<code>float</code>) – How many characters to treat as one token. |
| 47 | +- **tokens_per_image** (<code>int</code>) – Tokens to charge per image, which has no text to measure. The default is what |
| 48 | + OpenAI charges for a small image; raise it if you send large ones. |
| 49 | +- **tokens_per_file** (<code>int</code>) – Tokens to charge per file. A rough stand-in for a short document, since the real |
| 50 | + cost depends on the page count; raise it if you send long ones. |
| 51 | + |
| 52 | +**Raises:** |
| 53 | + |
| 54 | +- <code>ValueError</code> – If `chars_per_token` is not positive. |
| 55 | + |
| 56 | +#### count |
| 57 | + |
| 58 | +```python |
| 59 | +count(messages: list[ChatMessage], tools: ToolsType | None = None) -> int |
| 60 | +``` |
| 61 | + |
| 62 | +Return the estimated number of tokens the given messages occupy. |
| 63 | + |
| 64 | +**Parameters:** |
| 65 | + |
| 66 | +- **messages** (<code>list\[ChatMessage\]</code>) – The messages to measure. |
| 67 | +- **tools** (<code>ToolsType | None</code>) – Tools whose schemas are sent alongside the messages, and so consume tokens too. |
| 68 | + |
| 69 | +**Returns:** |
| 70 | + |
| 71 | +- <code>int</code> – The estimated token count, or `0` when there is nothing to measure. |
| 72 | + |
| 73 | +#### to_dict |
| 74 | + |
| 75 | +```python |
| 76 | +to_dict() -> dict[str, Any] |
| 77 | +``` |
| 78 | + |
| 79 | +Serialize the counter. |
| 80 | + |
| 81 | +**Returns:** |
| 82 | + |
| 83 | +- <code>dict\[str, Any\]</code> – A dictionary representation of the counter. |
| 84 | + |
| 85 | +## tiktoken_counter |
| 86 | + |
| 87 | +### TiktokenCounter |
| 88 | + |
| 89 | +Bases: <code>TokenCounter</code> |
| 90 | + |
| 91 | +Counts tokens locally with `tiktoken`, OpenAI's byte-pair encoder. |
| 92 | + |
| 93 | +Counting is an estimate, and two limits are worth knowing before relying on it: |
| 94 | + |
| 95 | +- **It is text-only**, so images and files get the flat `tokens_per_image` / `tokens_per_file` estimate rather |
| 96 | + than a real count. |
| 97 | +- **It is OpenAI's encoder.** Other providers tokenize differently, so expect the count to drift on them. |
| 98 | + |
| 99 | +## Usage Example: |
| 100 | + |
| 101 | +```python |
| 102 | +from haystack.dataclasses import ChatMessage |
| 103 | +from haystack.token_counters import TiktokenCounter |
| 104 | + |
| 105 | +counter = TiktokenCounter(encoding="o200k_base") |
| 106 | +messages = [ |
| 107 | + ChatMessage.from_user("Hello, how are you?"), |
| 108 | + ChatMessage.from_assistant("I'm good, thank you! How can I assist you today?") |
| 109 | +] |
| 110 | +token_count = counter.count(messages) |
| 111 | +print(f"Token count: {token_count}") |
| 112 | +``` |
| 113 | + |
| 114 | +#### __init__ |
| 115 | + |
| 116 | +```python |
| 117 | +__init__( |
| 118 | + encoding: str = "o200k_base", |
| 119 | + tokens_per_image: int = 85, |
| 120 | + tokens_per_file: int = 1000, |
| 121 | +) -> None |
| 122 | +``` |
| 123 | + |
| 124 | +Initialize the counter. |
| 125 | + |
| 126 | +**Parameters:** |
| 127 | + |
| 128 | +- **encoding** (<code>str</code>) – The `tiktoken` encoding to count with. The default, `o200k_base`, is what current OpenAI |
| 129 | + models use. |
| 130 | +- **tokens_per_image** (<code>int</code>) – Tokens to charge per image, which the tokenizer cannot measure. The default is what |
| 131 | + OpenAI charges for a small image; raise it if you send large ones. |
| 132 | +- **tokens_per_file** (<code>int</code>) – Tokens to charge per file. A rough stand-in for a short document, since the real |
| 133 | + cost depends on the page count; raise it if you send long ones. |
| 134 | + |
| 135 | +**Raises:** |
| 136 | + |
| 137 | +- <code>ImportError</code> – If `tiktoken` is not installed. |
| 138 | + |
| 139 | +#### warm_up |
| 140 | + |
| 141 | +```python |
| 142 | +warm_up() -> None |
| 143 | +``` |
| 144 | + |
| 145 | +Load the encoder, downloading its vocabulary if it is not already cached. |
| 146 | + |
| 147 | +#### count |
| 148 | + |
| 149 | +```python |
| 150 | +count(messages: list[ChatMessage], tools: ToolsType | None = None) -> int |
| 151 | +``` |
| 152 | + |
| 153 | +Return the estimated number of tokens used by the given messages. |
| 154 | + |
| 155 | +**Parameters:** |
| 156 | + |
| 157 | +- **messages** (<code>list\[ChatMessage\]</code>) – The messages to measure. |
| 158 | +- **tools** (<code>ToolsType | None</code>) – Tools whose schemas are sent alongside the messages, and so consume tokens too. |
| 159 | + |
| 160 | +**Returns:** |
| 161 | + |
| 162 | +- <code>int</code> – The estimated token count, or `0` when there is nothing to measure. |
| 163 | + |
| 164 | +#### to_dict |
| 165 | + |
| 166 | +```python |
| 167 | +to_dict() -> dict[str, Any] |
| 168 | +``` |
| 169 | + |
| 170 | +Serialize the counter. |
| 171 | + |
| 172 | +**Returns:** |
| 173 | + |
| 174 | +- <code>dict\[str, Any\]</code> – A dictionary representation of the counter. |
| 175 | + |
| 176 | +## types/protocol |
| 177 | + |
| 178 | +### TokenCounter |
| 179 | + |
| 180 | +Bases: <code>Protocol</code> |
| 181 | + |
| 182 | +Estimates the number tokens used by a list of messages. |
| 183 | + |
| 184 | +Implement `to_dict` so the counter's settings survive serialization. The default `from_dict` passes them straight |
| 185 | +back to the constructor, which is enough for plain values; override it when `to_dict` emitted something that has to |
| 186 | +be rebuilt first, such as a `Secret` or a nested component. |
| 187 | + |
| 188 | +#### count |
| 189 | + |
| 190 | +```python |
| 191 | +count(messages: list[ChatMessage], tools: ToolsType | None = None) -> int |
| 192 | +``` |
| 193 | + |
| 194 | +Return the estimated number of tokens in the given messages. |
| 195 | + |
| 196 | +**Parameters:** |
| 197 | + |
| 198 | +- **messages** (<code>list\[ChatMessage\]</code>) – The messages to measure. |
| 199 | +- **tools** (<code>ToolsType | None</code>) – Tools whose schemas are sent alongside the messages, and so consume tokens too. Pass them to have |
| 200 | + them counted; leave as None to measure the messages alone. |
| 201 | + |
| 202 | +**Returns:** |
| 203 | + |
| 204 | +- <code>int</code> – The estimated token count. |
| 205 | + |
| 206 | +#### to_dict |
| 207 | + |
| 208 | +```python |
| 209 | +to_dict() -> dict[str, Any] |
| 210 | +``` |
| 211 | + |
| 212 | +Serialize the counter to a dictionary. |
| 213 | + |
| 214 | +#### from_dict |
| 215 | + |
| 216 | +```python |
| 217 | +from_dict(data: dict[str, Any]) -> TokenCounter |
| 218 | +``` |
| 219 | + |
| 220 | +Deserialize the counter from a dictionary. |
0 commit comments