-
Notifications
You must be signed in to change notification settings - Fork 650
feat(adk): expose gen_ai.client.token.usage Prometheus metric #2149
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
braghettos
wants to merge
2
commits into
kagent-dev:main
Choose a base branch
from
braghettos:observability-token-metrics
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+503
−1
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| # GenAI token-usage metrics | ||
|
|
||
| kagent's **Go ADK** agent runtime records the OpenTelemetry GenAI-semconv metric | ||
| [`gen_ai.client.token.usage`](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-metrics/#metric-gen_aiclienttokenusage) | ||
| using the native Prometheus client library and exposes it for scraping. It lets you graph and alert | ||
| on token spend per model / provider without parsing traces. | ||
|
|
||
| ## What is emitted | ||
|
|
||
| A Prometheus histogram, served at **`/metrics`** on the agent's HTTP port: | ||
|
|
||
| | Prometheus name | OTel semconv | Notes | | ||
| | --- | --- | --- | | ||
| | `gen_ai_client_token_usage` | `gen_ai.client.token.usage` | histogram, semconv-recommended buckets | | ||
|
|
||
| Labels (semconv attributes, dots → underscores): | ||
|
|
||
| | Label | Values | | ||
| | --- | --- | | ||
| | `gen_ai_token_type` | `input`, `output` (output = candidate + reasoning tokens) | | ||
| | `gen_ai_operation_name` | `chat` | | ||
| | `gen_ai_provider_name` | well-known value, e.g. `openai`, `anthropic`, `gcp.vertex_ai`, `aws.bedrock`, `azure.ai.openai` | | ||
| | `gen_ai_request_model` | configured model, e.g. `gpt-4o` | | ||
| | `gen_ai_response_model` | model the provider served (falls back to request model) | | ||
| | `error_type` | set on failed requests; empty otherwise | | ||
|
|
||
| One observation is recorded per LLM call (streaming partial chunks are not double-counted). | ||
|
|
||
| ## Configuration | ||
|
|
||
| - **Runtime**: available on Declarative agents with `runtime: go`. (The Python runtime is not yet | ||
| instrumented.) | ||
| - **No flag to enable**: the `/metrics` endpoint is always served, and the controller adds Prometheus | ||
| pod annotations to Go-runtime agent Deployments automatically: | ||
|
|
||
| ```yaml | ||
| metadata: | ||
| annotations: | ||
| prometheus.io/scrape: "true" | ||
| prometheus.io/port: "<agent-port>" | ||
| prometheus.io/path: "/metrics" | ||
| ``` | ||
|
|
||
| ### Scraping it | ||
|
|
||
| Any Prometheus-compatible scraper that honors pod annotations will pick agents up. With an | ||
| OpenTelemetry Collector, add a `prometheus` receiver job with pod discovery: | ||
|
|
||
| ```yaml | ||
| receivers: | ||
| prometheus: | ||
| config: | ||
| scrape_configs: | ||
| - job_name: kagent-agents | ||
| kubernetes_sd_configs: [{ role: pod }] | ||
| relabel_configs: | ||
| - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape] | ||
| regex: "true" | ||
| action: keep | ||
| - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path] | ||
| target_label: __metrics_path__ | ||
| - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port] | ||
| regex: ([^:]+)(?::\d+)?;(\d+) | ||
| replacement: $$1:$$2 | ||
| target_label: __address__ | ||
| ``` | ||
|
|
||
| ## Verifying | ||
|
|
||
| ```bash | ||
| # 1. exec into a Go-runtime agent pod and curl its metrics endpoint | ||
| kubectl exec <go-agent-pod> -- wget -qO- localhost:<agent-port>/metrics | grep gen_ai_client_token_usage | ||
|
|
||
| # 2. after chatting with the agent you should see series like: | ||
| # gen_ai_client_token_usage_count{gen_ai_token_type="input",gen_ai_provider_name="gcp.vertex_ai", | ||
| # gen_ai_request_model="gemini-2.5-flash",gen_ai_response_model="gemini-2.5-flash", | ||
| # gen_ai_operation_name="chat",error_type=""} 1 | ||
| ``` | ||
|
|
||
| <!-- TODO: add a Grafana/Prometheus screenshot of gen_ai_client_token_usage once a cluster with a | ||
| scrape target is available. --> | ||
|
|
||
| ## Follow-ups | ||
|
|
||
| - Optional OTLP **push** (in addition to the scrape endpoint) via the OpenTelemetry | ||
| [Prometheus→OTLP bridge](https://pkg.go.dev/go.opentelemetry.io/contrib/bridges/prometheus), for | ||
| environments that push to an OTLP collector rather than scrape. | ||
| - Python ADK runtime instrumentation. |
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| package a2a | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| "github.com/prometheus/client_golang/prometheus" | ||
| adkmodel "google.golang.org/adk/model" | ||
| adksession "google.golang.org/adk/session" | ||
| "google.golang.org/genai" | ||
| ) | ||
|
|
||
| // gatherTokenUsageCount returns the total number of observations recorded on the | ||
| // gen_ai_client_token_usage histogram (summed across all label series). | ||
| func gatherTokenUsageCount(t *testing.T) uint64 { | ||
| t.Helper() | ||
| mfs, err := prometheus.DefaultGatherer.Gather() | ||
| if err != nil { | ||
| t.Fatalf("gather: %v", err) | ||
| } | ||
| var total uint64 | ||
| for _, mf := range mfs { | ||
| if mf.GetName() != "gen_ai_client_token_usage" { | ||
| continue | ||
| } | ||
| for _, m := range mf.GetMetric() { | ||
| total += m.GetHistogram().GetSampleCount() | ||
| } | ||
| } | ||
| return total | ||
| } | ||
|
|
||
| // TestExecutor_StreamingUsageNotDoubleCounted verifies that streamed LLM calls | ||
| // record one input + one output observation per call, not one per stream chunk. | ||
| // Partial events are skipped even when they carry usage metadata. | ||
| func TestExecutor_StreamingUsageNotDoubleCounted(t *testing.T) { | ||
| e := &KAgentExecutor{modelName: "gemini-2.5-flash", providerName: "gcp.vertex_ai"} | ||
| usage := &genai.GenerateContentResponseUsageMetadata{PromptTokenCount: 10, CandidatesTokenCount: 5} | ||
|
|
||
| before := gatherTokenUsageCount(t) | ||
|
|
||
| const numCalls, chunksPerCall = 3, 4 | ||
| for range numCalls { | ||
| // Streaming partial chunks that also carry usage — must be skipped. | ||
| for range chunksPerCall { | ||
| e.recordTokenUsage(&adksession.Event{LLMResponse: adkmodel.LLMResponse{Partial: true, UsageMetadata: usage}}) | ||
| } | ||
| // Final aggregated (non-partial) event — the one that counts. | ||
| e.recordTokenUsage(&adksession.Event{LLMResponse: adkmodel.LLMResponse{UsageMetadata: usage}}) | ||
| } | ||
|
|
||
| // One input + one output observation per LLM call, regardless of chunk count. | ||
| if got, want := gatherTokenUsageCount(t)-before, uint64(numCalls*2); got != want { | ||
| t.Fatalf("token usage observations = %d, want %d (must count %d LLM calls, not %d stream chunks)", | ||
| got, want, numCalls, numCalls*(chunksPerCall+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
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I guess we'd need to expose metrics on the controller generated objects as well.