Skip to content

Instantly share code, notes, and snippets.

@archatas
Created February 19, 2025 23:28
Show Gist options
  • Save archatas/98feba17f5be98b868564fc216c47f5d to your computer and use it in GitHub Desktop.
Save archatas/98feba17f5be98b868564fc216c47f5d to your computer and use it in GitHub Desktop.
Count OpenAI tokens for text
import tiktoken
encoding = tiktoken.get_encoding("o200k_base")
def num_tokens_from_messages(messages):
entire_input = ""
for message in messages:
entire_input += message["content"] + " "
tokens = encoding.encode(entire_input)
return len(tokens)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment