A helper library for estimating tokens used by messages.
Project description
llm-messages-token-helper
A helper library for estimating tokens used by messages and building messages lists that fit within the token limits of a model. Currently designed to work with the OpenAI GPT models (including GPT-4 turbo with vision). Uses the tiktoken library for tokenizing text and the Pillow library for image-related calculations.
Installation
Install the package:
python3 -m pip install openai-messages-token-helper
Usage
Build a messages list that fits within the max tokens for a model:
from llm_messages_token_helper import build_messages, count_tokens_for_message
messages = build_messages(
model="gpt-35-turbo",
system_prompt="You are a bot.",
new_user_message="That wasn't a good poem.",
past_messages=[
{
"role": "user",
"content": "Write me a poem",
},
{
"role": "assistant",
"content": "Tuna tuna I love tuna",
},
],
few_shots=[
{
"role": "user",
"content": "Write me a poem",
},
{
"role": "assistant",
"content": "Tuna tuna is the best",
},
]
)
Count the number of tokens in a message:
from llm_messages_token_helper import count_tokens
message = {
"role": "user",
"content": "Hello, how are you?",
}
model = "gpt-4"
num_tokens = count_tokens_for_message(model, message)
Count the number of tokens for an image sent to GPT-4-vision:
from llm_messages_token_helper import count_tokens_for_image
image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEA..."
num_tokens = count_tokens_for_image(image)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file llm_messages_token_helper-0.0.1.tar.gz
.
File metadata
- Download URL: llm_messages_token_helper-0.0.1.tar.gz
- Upload date:
- Size: 285.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: python-requests/2.31.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | dfd0547487f74f23ae05398d4a8b6c8b86bb38cd67d8dda93c7969f4f13cccbd |
|
MD5 | 6af835a92f35e89229c54478b352a5a7 |
|
BLAKE2b-256 | b4bfbdb796baaddebcda3cb55ceff686da832d3a2ac21dc443b1326b1f302f98 |
File details
Details for the file llm_messages_token_helper-0.0.1-py3-none-any.whl
.
File metadata
- Download URL: llm_messages_token_helper-0.0.1-py3-none-any.whl
- Upload date:
- Size: 6.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: python-requests/2.31.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 02351d20e4f39660ca4bc592f0a4ad1742fb356ffa989ebbb3c1c8a6312017d0 |
|
MD5 | 506603218d2343956a2eff3bbe3080af |
|
BLAKE2b-256 | 3820afd3f5593af7b1ea5f5d30082ea428df1cbf90d80d2214fc1e5b53bc9c39 |