(params: TotalInputTokenParams)
| 311 | * @returns Total estimated input token count |
| 312 | */ |
| 313 | export function countTotalInputTokens(params: TotalInputTokenParams): number { |
| 314 | const { chatHistory, systemMessage, tools } = params; |
| 315 | |
| 316 | let totalTokens = countChatHistoryTokens(chatHistory, params.model); |
| 317 | |
| 318 | // Add system message tokens if provided and not already in history |
| 319 | if (systemMessage) { |
| 320 | const hasSystemInHistory = chatHistory.some( |
| 321 | (item) => item.message.role === "system", |
| 322 | ); |
| 323 | if (!hasSystemInHistory) { |
| 324 | totalTokens += encode(systemMessage).length; |
| 325 | totalTokens += 4; // Message structure overhead (role + formatting) |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | // Add tool definition tokens |
| 330 | if (tools && tools.length > 0) { |
| 331 | totalTokens += countToolDefinitionTokens(tools); |
| 332 | } |
| 333 | |
| 334 | return totalTokens; |
| 335 | } |
| 336 | |
| 337 | /** |
| 338 | * Parameters for context length validation |
no test coverage detected