Member-only story
Avoid token attacks on GPT-3 apps with Tiktoken
Count GPT-3 tokens before further processing
1 min readJan 25, 2023
Most production GPT-3 apps use character count/word count to throttle free/paid usage! But GPT-3 operates on tokens!
With non-English languages, GPT-3 can get 15–20x more expensive because of the high token count. To understand this, read this article.
An attacker could enter seemingly innocuous 4 lines of text in a non-English language but cost you ~800 tokens. So instead of character or word count, use tiktoken to count and throttle!
#pip install tiktoken
import tiktoken
text = """జిబ్రాల్టర్ జలసంధి, అట్లాంటిక్ మహాసముద్రాన్ని మధ్యధరా సముద్రానికి కలిపే ఒక సన్నని జలసంధి.
ఐరోపా లోని ఐబీరియన్ ద్వీపకల్పాన్ని ఆఫ్రికాలోని మొరాకో నుండి ఇది వేరు చేస్తుంది.
స్పెయిన్ లోని పాయింట్ మారోక్వి, మొరాకోలోని పాయింట్ సైర్స్ మధ్య,
13 కి.మీ. వెడల్పున్న ఈ జలసంధి రెండు ఖండాలనూ వేరు చేస్తోంది."""
encoding = tiktoken.get_encoding("gpt2")
num_tokens = len(encoding.encode(text))
print ("Token count: ",num_tokens)
#Token count: 788
Feel free to find me on Twitter for daily short-form content!