Learning · · 4 min read
How to Track Token Usage in Python Chatbot Applications
A practical guide to monitoring prompt and response token counts in Python AI chatbots using Gemini API metadata.
When I started building AI tools on my laptop here in Pundri, I did not pay much attention to context length or token consumption. But as my projects grew, I quickly realized that learning how to track token usage in python chatbot scripts is essential if you want to keep your applications fast, reliable, and efficient. When you send long prompts or maintain multi-turn chat logs, every single word consumes prompt tokens, and every response consumes completion tokens. If you do not monitor these numbers, you can run into unexpected latency, context cutoff issues, or unexpected API rate limits. In this guide, I will share the exact script and method I use to inspect token metrics directly from Google Gemini API response metadata.
Why You Need to Track Token Usage in Python Chatbot Scripts
Many developers wait until an API call fails or truncates before thinking about token counts. When I built features like managing Python chatbot conversation history, I saw how quickly prompt size grows when stacking user messages and system instructions. Here are three practical reasons why tracking tokens early saves you time and effort:
- Rate Limit Management: Hitting token per minute (TPM) limits can cause temporary API errors or HTTP 429 status codes.
- Latency Control: Larger prompt token counts directly increase response processing time, making your chatbot feel sluggish.
- Context Management: Tracking usage lets you prune old history dynamically before the AI model drops important earlier context.
If you are already running into rate issues while building, check out my previous guide on handling API rate limits in Python to see how exponential backoff retries help keep your application responsive.
Understanding Gemini API Token Metadata
Google Gemini API provides token usage metrics directly inside the response object returned by generate_content. You do not need to install complex tokenizer libraries unless you want offline pre-estimation. The response object includes a metadata field that breaks down consumption into three key figures:
- prompt_token_count: The total number of tokens in your system instruction, conversation history, and the user's latest prompt.
- candidates_token_count: The number of tokens generated by the Gemini model in its answer response.
- total_token_count: The sum of input prompt tokens and output response tokens for that request.
Python Code to Track Token Usage in Python Chatbot Applications
Let us look at how to extract these numbers directly in your Python code using the SDK. I run this inside my normal development environment—if you want to see how I configured my local tools, check out how I set up my Python AI development environment.
Here is a clean Python snippet that sends a message to Gemini, reads the returned metadata, and prints out a clear breakdown:
import os
import google.generativeai as genai
# Configure Gemini API key
genai.configure(api_key=os.environ.get("GEMINI_API_KEY"))
# Set up model instance
model = genai.GenerativeModel("gemini-1.5-flash")
def send_message_with_token_tracking(prompt_text: str):
print(f"Sending prompt: '{prompt_text}'...")
# Request response from model
response = model.generate_content(prompt_text)
# Extract metadata safely
metadata = getattr(response, "usage_metadata", None)
if metadata:
prompt_tokens = metadata.prompt_token_count
candidate_tokens = metadata.candidates_token_count
total_tokens = metadata.total_token_count
print("\n--- Token Usage Metrics ---")
print(f"Input Tokens (Prompt): {prompt_tokens}")
print(f"Output Tokens (Response): {candidate_tokens}")
print(f"Total Request Tokens: {total_tokens}")
print("---------------------------\n")
else:
print("Token metadata was not included in response.")
return response.text
if __name__ == "__main__": # Run sample request
user_prompt = "Explain tokenization in AI models in three simple bullet points."
answer = send_message_with_token_tracking(user_prompt)
print("Model Response:\n", answer)
Running this script gives immediate visibility into how many input tokens your prompt consumed versus how many output tokens were spent generating the answer.
Tracking Accumulated Session Usage in Chat Loops
Single prompt tracking is useful for testing, but real chatbots run multi-turn interactive loops. To monitor cumulative consumption during an active chat session, you can build a lightweight tracker class that sums up token counts after each exchange.
class SessionTokenTracker:
def __init__(self):
self.total_prompt_tokens = 0
self.total_completion_tokens = 0
self.total_requests = 0
def add_request(self, metadata):
if not metadata:
return
self.total_requests += 1
p_tokens = metadata.prompt_token_count
c_tokens = metadata.candidates_token_count
self.total_prompt_tokens += p_tokens
self.total_completion_tokens += c_tokens
print(f"[Tracker Log] Request #{self.total_requests} | Prompt: {p_tokens} | Response: {c_tokens} | Cumulative Total: {self.grand_total}")
@property
def grand_total(self):
return self.total_prompt_tokens + self.total_completion_tokens
# Initialize model and tracker
tracker = SessionTokenTracker()
chat_session = model.start_chat(history=[])
def send_chat_user_message(user_input: str):
response = chat_session.send_message(user_input)
tracker.add_request(response.usage_metadata)
return response.text
Tracking cumulative token count after every turn helps you know exactly when to summarize conversation logs before context limits get hit.
Practical Takeaways from Token Monitoring
Adding token monitoring to my scripts was a small code update, but it gave me full clarity on how my applications operate behind the scenes. Instead of wondering why a long conversation felt slower or ran into errors, I now have accurate metrics for every request. If you want to check out other apps I have built with Python, feel free to visit my projects.
I recommend logging prompt tokens and output tokens in all your AI projects. Set up simple conditional warnings when your total session token count reaches your target threshold, so your application can summarize chat history automatically before context overflows.
Frequently asked questions
Why is tracking token usage important in a Python chatbot?
Tracking tokens helps prevent context overflow, manage API rate limits, optimize prompt lengths, and control latency in interactive AI applications.
How does Gemini API report token usage in Python?
The Gemini SDK returns a usage_metadata field in the response object containing prompt_token_count, candidates_token_count, and total_token_count.
Do I need external tokenizer libraries to track tokens with Gemini?
No, you can inspect exact token usage directly from response metadata without external tokenizer packages, though libraries like Tiktoken can be used if offline estimation is needed.