Created
July 24, 2023 02:41
-
-
Save u007/39f4374208d2740f7be59e555a7d701c to your computer and use it in GitHub Desktop.
openai get token count via TS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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