Skip to content

Instantly share code, notes, and snippets.

@u007
Created July 24, 2023 02:41
Show Gist options
  • Save u007/39f4374208d2740f7be59e555a7d701c to your computer and use it in GitHub Desktop.
Save u007/39f4374208d2740f7be59e555a7d701c to your computer and use it in GitHub Desktop.
openai get token count via TS
import * as tiktoken from 'tiktoken'
import { TiktokenModel } from 'tiktoken'
// @thanks https://stackoverflow.com/questions/76216113/how-can-i-count-tokens-before-making-api-call
export const calculateTokenCount = async (text: string, model : TiktokenModel = 'gpt-3.5-turbo') => {
try {
const tk = await tiktoken.encoding_for_model(model)
const encoded = tk.encode(text)
return encoded.length
} catch (error: any) {
console.error('Error:', error.message)
return -1 // Return -1 to indicate an error
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment