feat: Token Usage Tracking implementation#383
Open
AjitPadhi-Microsoft wants to merge 10 commits into
Open
Conversation
Coverage Report •
|
Unit Test Results520 tests 520 ✅ 8s ⏱️ Results for commit 6a5bfce. ♻️ This comment has been updated with latest results. |
Contributor
There was a problem hiding this comment.
Pull request overview
Adds LLM token usage telemetry for chat and title-generation flows, plus KQL snippets for monitoring usage and cost in Application Insights.
Changes:
- Added token usage extraction and telemetry emission helpers in chat/history modules.
- Integrated token accumulation into standard and workshop chat streams.
- Added Application Insights KQL queries for usage summaries, breakdowns, and cost estimates.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 7 comments.
| File | Description |
|---|---|
src/api/python/chat.py |
Adds chat token extraction, aggregation, and telemetry emission. |
src/api/python/history.py |
Adds Cosmos history title-generation token telemetry. |
src/api/python/history_sql.py |
Adds SQL history title-generation token telemetry. |
infra/dashboards/token-usage-queries.kql |
Adds monitoring and analytics queries for emitted token events. |
Comments suppressed due to low confidence (1)
src/api/python/chat.py:177
- Telemetry extraction can raise before the chat response is streamed when
usageis present but its token fields are missing or non-numeric (for example, the existing tests' mock Responses objects do not define usage fields). Because this helper is called directly from the request path, a telemetry-shape issue turns an otherwise successful chat response into a 500 instead of simply skipping token telemetry; validate/coerce defensively or catch extraction errors at the call sites.
inp = getattr(usage_obj, "input_tokens", 0) or getattr(usage_obj, "prompt_tokens", 0) or 0
out = getattr(usage_obj, "output_tokens", 0) or getattr(usage_obj, "completion_tokens", 0) or 0
tot = getattr(usage_obj, "total_tokens", 0) or (inp + out)
if tot > 0:
return (int(inp), int(out), int(tot))
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| "user_id": user_id or "", | ||
| "conversation_id": conversation_id or "", | ||
| }) | ||
| logger.info( |
| """Unit tests for token_usage helpers.""" | ||
|
|
||
| from types import SimpleNamespace | ||
| from unittest.mock import MagicMock, patch |
Comment on lines
+222
to
+223
| "agent_count": "1", | ||
| "model_count": "1", |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Purpose
LLM Token Usage Telemetry and Monitoring
Token usage extraction and telemetry emission:
_extract_usage_from_dict,_extract_usage_from_update,_extract_usage_from_response,_track_token_usage) inchat.pyto extract input, output, and total token counts from various response formats and emit three types of telemetry events:LLM_Token_Usage_Summary,LLM_Agent_Token_Usage, andLLM_Model_Token_Usage. These events include relevant metadata such as agent name, model deployment, user ID, and conversation ID._track_title_token_usagehelpers to bothhistory.pyandhistory_sql.pyto emit token usage telemetry for title generation requests. [1] [2]Integration into API flows:
stream_openai_textandstream_openai_text_workshopinchat.pyto accumulate token usage across all response iterations/streaming updates and emit telemetry at the end of each request. [1] [2] [3] [4] [5] [6] [7]Monitoring and Analytics Support
Application Insights KQL queries:
token-usage-queries.kqlfile with a comprehensive set of KQL queries for monitoring LLM token usage, top consumers, cost estimation, usage breakdowns by agent/model/user, and visualizations (area and pie charts). These queries support detailed analysis and reporting in Application Insights.Does this introduce a breaking change?
Golden Path Validation
Deployment Validation
What to Check
Verify that the following are valid
Other Information