Introduction
Tracking tokens and costs helps you understand how much you use and spend when working with AI models.
Jump into concepts and practice - no test required
tokens_used = count_tokens(prompt_text) cost = tokens_used * cost_per_token
prompt = "Hello, how are you?" tokens_used = count_tokens(prompt) cost = tokens_used * 0.0001
input_text = "Explain machine learning in simple words." tokens = count_tokens(input_text) cost = tokens * 0.0002
def count_tokens(text): # Simple token count by splitting on spaces return len(text.split()) prompt = "What is AI and how does it work?" cost_per_token = 0.00015 tokens_used = count_tokens(prompt) cost = tokens_used * cost_per_token print(f"Tokens used: {tokens_used}") print(f"Cost: ${cost:.5f}")
response = {'usage': {'prompt_tokens': 50, 'completion_tokens': 30, 'total_tokens': 80}}
print(response['usage']['total_tokens'])tokens = response['usage']['token_total'] print(tokens)What is the likely cause?