Bird
Raised Fist0
Agentic AIml~20 mins

Token usage and cost tracking in Agentic AI - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Token Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
1:30remaining
Understanding Token Counting in Language Models

When using a language model, why is it important to count tokens instead of characters or words?

ABecause words are always single tokens, so counting words is the same as counting tokens.
BBecause characters are always longer than tokens, so counting characters is less efficient.
CBecause tokens represent the smallest units the model processes, which may be parts of words, ensuring accurate cost and usage tracking.
DBecause tokens are only used for billing, not for model input processing.
Attempts:
2 left
💡 Hint

Think about how language models break down text internally.

Predict Output
intermediate
1:30remaining
Calculating Token Usage from Model Output

Given the following Python code that simulates token counting for a model response, what is the printed output?

Agentic AI
def count_tokens(text):
    # Simple token count: split by spaces
    return len(text.split())

input_text = "Hello world! This is a test."
output_text = "Hello! This test is simple."

input_tokens = count_tokens(input_text)
output_tokens = count_tokens(output_text)
total_tokens = input_tokens + output_tokens
print(total_tokens)
A12
B10
C9
D11
Attempts:
2 left
💡 Hint

Count the words in both input and output texts separately, then add.

Hyperparameter
advanced
2:00remaining
Choosing the Right Token Limit for Cost Efficiency

You have a language model with a maximum token limit of 4096 tokens per request. You want to maximize the amount of information processed while minimizing cost. Which strategy best balances token usage and cost?

ASet a token limit slightly below 4096 to leave room for model-generated tokens and avoid errors, optimizing cost and usage.
BAlways use the full 4096 tokens to get the most output regardless of cost.
CUse only 512 tokens per request to save cost, even if it means sending multiple requests.
DIgnore token limits and send as much text as possible; the model will truncate automatically.
Attempts:
2 left
💡 Hint

Consider both model constraints and cost when setting token limits.

Metrics
advanced
1:30remaining
Calculating Cost from Token Usage

A language model charges $0.0004 per 1,000 tokens. If a user sends a prompt of 1,200 tokens and receives a response of 800 tokens, what is the total cost for this interaction?

A$0.0004
B$0.0008
C$0.00032
D$0.00048
Attempts:
2 left
💡 Hint

Add input and output tokens, then multiply by cost per 1,000 tokens.

🔧 Debug
expert
2:00remaining
Identifying Token Counting Bug in Code

Consider this Python function intended to count tokens by splitting text on spaces. It is used to track token usage for cost calculation. What error or issue will this code cause when processing the text "Hello,world!"?

def count_tokens(text):
    return len(text.split(' '))

print(count_tokens("Hello,world!"))
AIt returns 1 because split(' ') does not split on multiple spaces correctly.
BIt returns 2, correctly counting tokens separated by spaces.
CIt raises a TypeError because split(' ') is invalid syntax.
DIt returns 3 because punctuation is counted as separate tokens.
Attempts:
2 left
💡 Hint

Try running the split method on a string with punctuation and spaces.

Practice

(1/5)
1. What is a token in the context of AI language models?
easy
A. A programming language used for AI
B. A type of AI model architecture
C. A small piece of text like a word or part of a word
D. A hardware component for AI processing

Solution

  1. Step 1: Understand the definition of a token

    A token is a small piece of text that AI models use to understand language. It can be a word or part of a word.
  2. Step 2: Differentiate tokens from other AI terms

    Tokens are not models, programming languages, or hardware. They are units of text input.
  3. Final Answer:

    A small piece of text like a word or part of a word -> Option C
  4. Quick Check:

    Token = small text piece [OK]
Hint: Tokens are text pieces, not models or hardware [OK]
Common Mistakes:
  • Confusing tokens with AI models
  • Thinking tokens are programming languages
  • Assuming tokens are hardware parts
2. Which of the following is the correct way to track token usage in a Python script using an AI API?
easy
A. tokens_used = response['total_tokens']
B. tokens_used = response['usage']['total_tokens']
C. tokens_used = response['usage']['tokens']
D. tokens_used = response['token_count']

Solution

  1. Step 1: Identify the correct key for token usage in API response

    Most AI APIs return token usage under response['usage']['total_tokens'].
  2. Step 2: Compare options with common API response structure

    Only tokens_used = response['usage']['total_tokens'] matches the standard nested key for total tokens used.
  3. Final Answer:

    tokens_used = response['usage']['total_tokens'] -> Option B
  4. Quick Check:

    Correct key path = response['usage']['total_tokens'] [OK]
Hint: Look for nested 'usage' then 'total_tokens' key [OK]
Common Mistakes:
  • Using wrong key names like 'token_count'
  • Missing nested 'usage' dictionary
  • Assuming flat keys for token counts
3. Given the following code snippet, what will be printed?
response = {'usage': {'prompt_tokens': 50, 'completion_tokens': 30, 'total_tokens': 80}}
print(response['usage']['total_tokens'])
medium
A. 80
B. 30
C. 50
D. Error

Solution

  1. Step 1: Access the 'total_tokens' key in the nested dictionary

    The code accesses response['usage']['total_tokens'], which is 80.
  2. Step 2: Confirm the print output

    Printing this value outputs 80 without error.
  3. Final Answer:

    80 -> Option A
  4. Quick Check:

    response['usage']['total_tokens'] = 80 [OK]
Hint: Check nested dictionary keys carefully [OK]
Common Mistakes:
  • Confusing prompt_tokens with total_tokens
  • Mixing completion_tokens with total_tokens
  • Assuming code causes error
4. You wrote this code to track token usage but get a KeyError:
tokens = response['usage']['token_total']
print(tokens)
What is the likely cause?
medium
A. The 'usage' key is missing in the response
B. The response variable is not defined
C. The print statement syntax is incorrect
D. The key 'token_total' does not exist in the response dictionary

Solution

  1. Step 1: Check the key names in the response dictionary

    The correct key is 'total_tokens', not 'token_total'.
  2. Step 2: Understand KeyError cause

    Using a wrong key name causes KeyError because that key does not exist.
  3. Final Answer:

    The key 'token_total' does not exist in the response dictionary -> Option D
  4. Quick Check:

    Wrong key name causes KeyError [OK]
Hint: Verify exact key names in API response [OK]
Common Mistakes:
  • Assuming similar key names exist
  • Ignoring case sensitivity in keys
  • Thinking print syntax causes error
5. You want to estimate the cost of an AI request. The model charges $0.002 per 1000 tokens. If your request uses 2500 tokens, what is the total cost?
hard
A. $0.005
B. $0.0025
C. $0.05
D. $0.0005

Solution

  1. Step 1: Calculate cost per token

    Cost per token = $0.002 / 1000 = $0.000002 per token.
  2. Step 2: Multiply by number of tokens used

    Total cost = 2500 tokens * $0.000002 = $0.005.
  3. Final Answer:

    $0.005 -> Option A
  4. Quick Check:

    2500 tokens x $0.002/1000 = $0.005 [OK]
Hint: Multiply tokens by cost per token (divide by 1000 first) [OK]
Common Mistakes:
  • Multiplying by 0.002 directly without dividing by 1000
  • Using wrong token count
  • Confusing decimals in cost calculation