Bird
0
0

You have a dictionary of responses with some missing 'completion_tokens' keys. How do you safely calculate total tokens without errors?

hard📝 Application Q9 of 15
Agentic AI - Agent Observability
You have a dictionary of responses with some missing 'completion_tokens' keys. How do you safely calculate total tokens without errors?
responses = [
  {'usage': {'prompt_tokens': 10, 'completion_tokens': 5}},
  {'usage': {'prompt_tokens': 20}},
  {'usage': {'prompt_tokens': 15, 'completion_tokens': 10}}
]
cost_per_token = 0.0003
# Fill in the blank:
total_tokens = sum(____)
total_cost = total_tokens * cost_per_token
print(f"Total cost: ${total_cost:.4f}")
Aresp['usage']['prompt_tokens'] + resp['usage']['completion_tokens'] for resp in responses
Bresp['usage'].get('prompt_tokens', 0) + resp['usage']['completion_tokens'] for resp in responses
Cresp['usage']['prompt_tokens'] + resp['usage'].get('completion_tokens', 0) for resp in responses
Dresp['usage'].get('total_tokens', 0) for resp in responses
Step-by-Step Solution
Solution:
  1. Step 1: Use get() to handle missing keys

    Use get('completion_tokens', 0) to avoid KeyError if key is missing.
  2. Step 2: Sum prompt tokens plus safe completion tokens

    Sum prompt_tokens plus completion_tokens or zero if missing.
  3. Final Answer:

    resp['usage']['prompt_tokens'] + resp['usage'].get('completion_tokens', 0) for resp in responses -> Option C
  4. Quick Check:

    Use get() for missing keys safely [OK]
Quick Trick: Use get() with default 0 for missing tokens [OK]
Common Mistakes:
  • Not handling missing keys
  • Assuming all keys exist
  • Using wrong default values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Agentic AI Quizzes