Skip to content

Add utility function to calculate number of tokens #49

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/openai/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,39 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.

from __future__ import annotations
# openai/utils/token_counter.py

from typing import List, Dict, Union
import tiktoken

def num_tokens(
text_or_messages: Union[str, List[Dict[str, str]]],
model: str = "gpt-4o"
) -> int:
"""
Calculate the number of tokens for a string or chat messages.

:param text_or_messages: String or list of {"role":..., "content":...} messages.
:param model: Model name for tokenization (defaults to gpt-4o).
:return: Number of tokens.
"""
encoding = tiktoken.encoding_for_model(model)

if isinstance(text_or_messages, str):
return len(encoding.encode(text_or_messages))

elif isinstance(text_or_messages, list):
num_tokens = 0
for msg in text_or_messages:
# Each message has role + content
num_tokens += 3 # Roughly accounts for role/content overhead
num_tokens += len(encoding.encode(msg.get("content", "")))
num_tokens += len(encoding.encode(msg.get("role", "")))
num_tokens += 3 # Every reply has priming tokens
return num_tokens

else:
raise TypeError("Input must be a string or a list of messages.")

import os as _os
import typing as _t
Expand Down