MCPcopy Create free account
hub / github.com/Zoo-Code-Org/Zoo-Code / internalCountTokens

Method internalCountTokens

src/api/providers/vscode-lm.ts:225–302  ·  view source on GitHub ↗

* Private implementation of token counting used internally by VsCodeLmHandler

(text: string | vscode.LanguageModelChatMessage)

Source from the content-addressed store, hash-verified

223 * Private implementation of token counting used internally by VsCodeLmHandler
224 */
225 private async internalCountTokens(text: string | vscode.LanguageModelChatMessage): Promise<number> {
226 // Check for required dependencies
227 if (!this.client) {
228 console.warn("Roo Code <Language Model API>: No client available for token counting")
229 return 0
230 }
231
232 // Validate input
233 if (!text) {
234 console.debug("Roo Code <Language Model API>: Empty text provided for token counting")
235 return 0
236 }
237
238 // Create a temporary cancellation token if we don't have one (e.g., when called outside a request)
239 let cancellationToken: vscode.CancellationToken
240 let tempCancellation: vscode.CancellationTokenSource | null = null
241
242 if (this.currentRequestCancellation) {
243 cancellationToken = this.currentRequestCancellation.token
244 } else {
245 tempCancellation = new vscode.CancellationTokenSource()
246 cancellationToken = tempCancellation.token
247 }
248
249 try {
250 // Handle different input types
251 let tokenCount: number
252
253 if (typeof text === "string") {
254 tokenCount = await this.client.countTokens(text, cancellationToken)
255 } else if (text instanceof vscode.LanguageModelChatMessage) {
256 // For chat messages, ensure we have content
257 if (!text.content || (Array.isArray(text.content) && text.content.length === 0)) {
258 console.debug("Roo Code <Language Model API>: Empty chat message content")
259 return 0
260 }
261 const countMessage = extractTextCountFromMessage(text)
262 tokenCount = await this.client.countTokens(countMessage, cancellationToken)
263 } else {
264 console.warn("Roo Code <Language Model API>: Invalid input type for token counting")
265 return 0
266 }
267
268 // Validate the result
269 if (typeof tokenCount !== "number") {
270 console.warn("Roo Code <Language Model API>: Non-numeric token count received:", tokenCount)
271 return 0
272 }
273
274 if (tokenCount < 0) {
275 console.warn("Roo Code <Language Model API>: Negative token count received:", tokenCount)
276 return 0
277 }
278
279 return tokenCount
280 } catch (error) {
281 // Handle specific error types
282 if (error instanceof vscode.CancellationError) {

Callers 3

countTokensMethod · 0.95
createMessageMethod · 0.95

Calls 5

warnMethod · 0.65
debugMethod · 0.65
countTokensMethod · 0.65
disposeMethod · 0.65

Tested by

no test coverage detected