Last active
June 10, 2023 17:28
-
-
Save mnemotiv/696f273784ad60919209ae67cfff8fd6 to your computer and use it in GitHub Desktop.
Node.js/TypeScript: ChatGPT API (gpt-3.5-turbo) messages token calculator
This file contains hidden or 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
// Author: mnemotiv | |
// Donate: https://donate.stripe.com/9AQbJM4xC62P0xieUU | |
// Don't forget to run this first: | |
// npm i @dqbd/tiktoken | |
import { get_encoding } from '@dqbd/tiktoken'; | |
import type { ChatCompletionRequestMessage } from 'openai'; | |
const countTokens = (messages: ChatCompletionRequestMessage[]): number => { | |
const tokenizer = get_encoding('cl100k_base'); | |
return messages | |
.map( | |
(message) => Object.entries(message) | |
.map( | |
([key, value]) => tokenizer.encode(value).length - (key === 'name' ? 1 : 0), | |
) | |
.reduce((a, b) => a + b, 4), | |
) | |
.reduce((a, b) => a + b, 2); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment