计量 Token 使用量

简介

Envoy AI Gateway 提供符合 OpenTelemetry GenAI 语义约定的 Prometheus 指标,包括每个请求的 token 使用量。通过将调用方身份作为指标标签,并通过平台监控栈采集该指标,你可以按部门、namespace 和 model 获得统一的 token 消耗视图。同一份数据还会被 Alauda Cost Management 用于分摊计费。

其流程为:gateway 发出 token 指标,身份信息以标签形式附加,PodMonitor 将指标采集到平台中,MonitorDashboard 进行展示。日常查看不需要直接编写 PromQL。

使用场景

  • 按项目隔离,展示每个部门在不同 model 上的 token 消耗。
  • 跟踪平台范围内哪些 model 产生了最多的 token 使用量。
  • 提供供 Alauda Cost Management 计价并生成分摊计费报告的使用数据。

前提条件

  1. 已配置 llmRequestCosts 的 AIGatewayRoute。请参见 配置 Token 配额。如果没有 llmRequestCosts,gateway 仍会发出 gen_ai_client_token_usage_token,但每个请求的 token 计数都会为 0。

  2. 调用方身份已通过 request headers 传递。请参见 认证消费者。

  3. 集群已启用平台监控。可通过检查 Prometheus operator CRD 来确认:

    kubectl get crd podmonitors.monitoring.coreos.com
  4. 在接入监控之前,先进行一次健全性检查,确认指标确实已经发出。通过 gateway 发送一个请求,然后读取 data-plane proxy pod 上 ExtProc sidecar 的 admin 端口:

    POD=$(kubectl get pod -n envoy-gateway-system \
      -l gateway.envoyproxy.io/owning-gateway-name=<gateway-name> \
      -o jsonpath='{.items[0].metadata.name}')
    kubectl port-forward -n envoy-gateway-system pod/$POD 1064:1064 &
    curl -s http://localhost:1064/metrics | grep gen_ai_client_token_usage_token | head
    # expect lines like: gen_ai_client_token_usage_token_sum{gen_ai_operation_name="chat",...} 42

    如果没有出现任何 gen_ai_* 样本,那么下面的任何采集都不会生效——请先修复 route / ExtProc 的接线。

NOTE

请将 Gateway 和 AIGatewayRoute 创建在专用 namespace 中(例如 maas-system),而不要创建在 Envoy Gateway control-plane namespace envoy-gateway-system 中。放在 control-plane namespace 中的 gateway 可能不会在其 listener 上应用 AI Gateway request-processing filter 和 SecurityPolicy,这会在不报错的情况下破坏 routing 和 policy enforcement。请参见 Envoy AI Gateway。

步骤

为 token 指标添加身份标签

默认情况下,token 指标 gen_ai_client_token_usage_token 只携带 OpenTelemetry GenAI 标准标签(model、provider、operation、token type)。通过在 Envoy AI Gateway controller 中将身份 header 映射为指标标签,可将其扩展为包含调用方身份维度——计费 namespace 和调用方所属部门。

controller 会从 ai-gateway-controller Deployment 上的 CLI flag --metricsRequestHeaderAttributes=<header>:<label>[,<header>:<label>...] 读取映射。如果 controller 是通过 Helm 安装的,则该 chart 会从某个 values 键(例如 controller.metricsRequestHeaderAttributes)渲染此 flag;请提供你的 release name 和 chart 引用,并执行 helm upgrade --reuse-values。如果你是直接管理 Deployment,则需要 patch 其 container args。

这个 flag 是一个单独的、用逗号连接的 <header>:<label> map,不是可重复列表:如果传入两次,controller 只会保留最后一份。平台还自带了默认的键值对(例如 x-user-name:user 和 x-access-meta:client_id),data-plane sidecar 已经会发出这些键值对——因此你必须用现有键值对与新增键值对的并集来重写这一个 flag。遗漏任何一对都会导致该指标标签在所有 proxy 下次重启后消失。

先读取当前 data-plane 实际发出的键值对(proxy sidecar 是事实来源——controller flag 可能已经被缩减过):

PROXY=$(kubectl -n envoy-gateway-system get pod \
  -l gateway.envoyproxy.io/owning-gateway-name=<gateway-name> \
  -o jsonpath='{.items[0].metadata.name}')
kubectl -n envoy-gateway-system get pod "$PROXY" \
  -o jsonpath='{.spec.initContainers[?(@.name=="ai-gateway-extproc")].args}' \
  | jq -r 'index("-metricsRequestHeaderAttributes") as $i | .[$i+1]'
# e.g. x-user-name:user,x-user-namespace:user_namespace,x-access-meta:client_id  (platform defaults)

然后用这整组键值对 再加上 x-user-group:department 重写 controller 的单个 flag。请将下面左侧内容替换为上面命令打印出来的结果——不要遗漏任何一对:

# Locate the flag's argument index on the controller Deployment
IDX=$(kubectl -n envoy-gateway-system get deploy ai-gateway-controller \
  -o jsonpath='{.spec.template.spec.containers[0].args}' \
  | jq 'map(test("^--?metricsRequestHeaderAttributes=")) | index(true)')

# Replace it with the UNION of existing pairs + the new one
kubectl -n envoy-gateway-system patch deploy ai-gateway-controller --type json -p '[
  {"op":"replace","path":"/spec/template/spec/containers/0/args/'"$IDX"'",
   "value":"--metricsRequestHeaderAttributes=x-user-name:user,x-user-namespace:user_namespace,x-access-meta:client_id,x-user-group:department"}
]'
# If the flag is not present anywhere (IDX is null), add it instead with the same full value:
#   --type json -p '[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--metricsRequestHeaderAttributes=...,x-user-group:department"}]'

kubectl -n envoy-gateway-system rollout status deploy ai-gateway-controller

# The mapping is rendered into each data-plane proxy pod's ExtProc sidecar args
# at pod-creation time. A controller-only rollout does NOT update already-running
# proxy pods, so recreate them and wait:
kubectl rollout restart deployment -n envoy-gateway-system \
  -l gateway.envoyproxy.io/owning-gateway-name=<gateway-name>
kubectl rollout status deployment -n envoy-gateway-system \
  -l gateway.envoyproxy.io/owning-gateway-name=<gateway-name>
  • x-user-namespace → user_namespace:请求所计费的 namespace 或 tenant。这是 使用 Cost Management 进行分摊计费 时按 namespace 分组使用的键,因此只要在使用 Cost Management,就应保留它。
  • x-user-group → department:用于 dashboard 的低基数身份维度。由 SecurityPolicy 根据 IdP 的 groups claim 设置。
NOTE

--metricsRequestHeaderAttributes 映射会在创建 proxy pod 时写入 ExtProc sidecar 参数。仅 patch controller 并等待其滚动完成不够——在新的标签出现之前,必须重新创建 proxy pod(上面的 rollout restart)。如果下面的验证返回空输出,说明 proxy pod 并未重新创建。

NOTE

user_namespace(计费 namespace)是可靠的默认分组——只要映射了 x-user-namespace,它就始终存在。department(x-user-group)只有在 IdP 发出单值 group claim 时才是一个有用的低基数维度——标准 OIDC groups claim 是一个数组,claimToHeaders 不支持它,因此在其他情况下 department 会保持为空,请参见 认证消费者。避免使用 per-user 标签(x-user-id):它会产生高基数 series(每个 user × model × token type 一条),因此只有在确实需要按用户报表,并且保留窗口能限制 series 数量时才添加它。

滚动完成后,发送一条新的请求并确认样本上已经有新标签。user_namespace 始终存在;只有在配置了标量 group claim 时,department 才会出现:

curl -s http://localhost:1064/metrics | grep 'user_namespace=' | head

将指标采集到平台中

该指标由 AI Gateway external processor(ExtProc)发出,它作为每个 data-plane proxy pod 的 sidecar 运行(声明为 Kubernetes 原生 sidecar / initContainer),并在 container port 1064(命名为 aigw-metrics)上暴露 Prometheus metrics endpoint。它通过 PodMonitor 直接从 proxy pod 中采集。有关平台工作流,请参见 指标管理。

在 Alauda 平台上,这个 sidecar 的 PodMonitor 往往已经预装。请先检查——在同一个 endpoint 上再创建一个 PodMonitor 会形成重叠的 scrape pool,导致每个 proxy pod 被抓取两次,进而在不同的 job 标签下产生重复 series,并在 dashboard 和分摊计费查询中把所有 increase()/sum 翻倍(二者都不会按 job 过滤):

kubectl get podmonitor -A \
  -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name}{"\t"}{.spec.podMetricsEndpoints[*].port}{"\n"}{end}'
# The Alauda platform ships `ai-gateway-extproc-metrics` targeting the `aigw-metrics`
# port. If any PodMonitor already lists `aigw-metrics`, SKIP the apply below and go
# straight to the scrape check.

只有在还没有任何 PodMonitor 指向 aigw-metrics 时,才需要先发现你的 Prometheus operator 用来选择 PodMonitor 对象的 label(以便下面的资源能够被正确拾取),然后创建一个:

kubectl get prometheus -A \
  -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name}: {.spec.podMonitorSelector}{"\n"}{end}'
# On the Alauda platform this is typically: prometheus: kube-prometheus

然后应用该 PodMonitor,并将该 label 放在它自己的 metadata.labels 中(不是 selector 中——这是两个不同的概念):

apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
  name: ai-gateway-metrics
  namespace: envoy-gateway-system
  labels:
    prometheus: kube-prometheus   # must match your Prometheus's spec.podMonitorSelector
spec:
  selector:
    matchLabels:
      app.kubernetes.io/managed-by: envoy-gateway
      app.kubernetes.io/component: proxy
  podMetricsEndpoints:
    - port: aigw-metrics
      path: /metrics
      interval: 30s
  • metadata.labels:Prometheus 用来发现 PodMonitor 的方式。没有正确的 label,资源虽然存在,但对 scrape 流程不可见。
  • spec.selector:匹配集群中的所有 Envoy Gateway data-plane proxy pod。若要限制到某个 Gateway,请将其替换为 gateway.envoyproxy.io/owning-gateway-name: <gateway-name> 和 gateway.envoyproxy.io/owning-gateway-namespace: <gateway-namespace>。
  • port: aigw-metrics:ExtProc sidecar 上提供 /metrics 的命名端口,对应 container port 1064。

确认 Prometheus 正在抓取该 sidecar——并且恰好只有一个 scrape pool 覆盖它(两个 pool 意味着重复的 PodMonitor 正在重复计数)。将 Prometheus 端口转发到本地,并按 pool 对活跃目标进行分组:

PROM=$(kubectl -n <prometheus-namespace> get pod -l app.kubernetes.io/name=prometheus \
  -o jsonpath='{.items[0].metadata.name}')
kubectl -n <prometheus-namespace> port-forward $PROM 9090:9090 &

# Wait ~30s after applying a PodMonitor; the operator's config-reload is async.
curl -s 'http://127.0.0.1:9090/api/v1/targets?state=active' \
  | jq '[.data.activeTargets[] | select(.labels.endpoint=="aigw-metrics")]
        | group_by(.scrapePool)
        | map({scrapePool: .[0].scrapePool, targets: length, health: .[0].health})'
# expect: exactly ONE scrape pool covering the sidecar, health="up".
# Two pools => a duplicate PodMonitor; delete the redundant one.

构建统一的使用量 dashboard

创建一个 MonitorDashboard 来展示 token 使用量。使用 namespace、model 和 department 变量,以便使用者过滤,并依赖 User View,确保每个项目只能看到自己的数据。有关平台工作流,请参见 监控 dashboard。

在 ExtProc 的 /metrics endpoint 上,该指标以 Prometheus 文本格式暴露,OpenTelemetry 名称会被规范化为下划线(gen_ai_client_token_usage_token_sum,如上面的前提检查所示)。不过,平台的 scrape 流程会将该 series 以其原始 OpenTelemetry UTF-8 名称存储,并保留点号。因此在 Prometheus 中,该 series 为 gen_ai.client.token.usage_token_sum(以及 histogram 的 _sum/_count/_bucket 变体),必须使用带引号的 {__name__="..."} 形式选择——裸下划线标识符匹配不到任何内容,只会返回空向量。GenAI 内置标签同样使用点号形式(gen_ai.request.model、gen_ai.token.type),需要使用带引号的 UTF-8 label 语法;而通过 header 映射的标签(如 department 和 user_namespace)仍然使用普通标识符:

CAUTION

头部面板应按 user_namespace 分组:只要映射了 x-user-namespace,它就始终存在。department 标签只有在 x-user-group 已填充时才会出现,这要求来自 IdP 的 group claim 是单值——标准 OIDC groups claim 是一个数组,且不受支持,因此否则 sum by (department) 会折叠为一条带空标签的 series。只有在确认该标签存在(grep 'department=' 有输出)之后,才按 department 分组;否则应在 IdP connector 中暴露一个标量 claim。

# Tokens per billed namespace over the last hour
sum by (user_namespace) (
  increase({__name__="gen_ai.client.token.usage_token_sum"}[1h])
)

# Top 5 models by total tokens in the last 24h
topk(5,
  sum by ("gen_ai.request.model") (
    increase({__name__="gen_ai.client.token.usage_token_sum"}[24h])
  )
)

# Output-token share per namespace (proxy for cost; output is the expensive side)
sum by (user_namespace) (
  increase({__name__="gen_ai.client.token.usage_token_sum", "gen_ai.token.type"="output"}[1h])
)

# Optional: per-department view — only once a scalar group claim is configured
# (see the caution above), otherwise this returns an empty result:
#   sum by (department) (increase({__name__="gen_ai.client.token.usage_token_sum"}[1h]))

通过在 Prometheus UI 的 Status → TSDB 页面列出所有 gen_ai* series 名称,或者使用下面的命令,确认该指标可被查询:

curl -s 'http://127.0.0.1:9090/api/v1/label/__name__/values' \
  | jq -r '.data[]' | grep gen_ai

验证

发送几条认证请求,使其解析到不同的 namespace,然后通过在任意 proxy pod 上端口转发 ExtProc sidecar 的 metrics 端口,确认该指标携带身份标签:

POD=$(kubectl get pod -n envoy-gateway-system \
  -l gateway.envoyproxy.io/owning-gateway-name=<gateway-name> \
  -o jsonpath='{.items[0].metadata.name}')
kubectl port-forward -n envoy-gateway-system pod/$POD 1064:1064 &

# Drive a couple of authenticated requests (substitute valid tokens), then read the metric.
for token in '<token-tenant-a>' '<token-tenant-b>'; do
  curl -s -o /dev/null \
    -H "Authorization: Bearer $token" \
    -H 'Content-Type: application/json' \
    -d '{"model":"my-llm","messages":[{"role":"user","content":"hi"}]}' \
    http://<gateway-address>/v1/chat/completions
done

curl -s http://localhost:1064/metrics \
  | grep 'gen_ai_client_token_usage_token_sum{' \
  | grep 'user_namespace='

预期每个计费 namespace 至少有一个样本,例如:

gen_ai_client_token_usage_token_sum{user_namespace="team-a",gen_ai_request_model="my-llm",gen_ai_token_type="input",...} 184
gen_ai_client_token_usage_token_sum{user_namespace="team-b",gen_ai_request_model="my-llm",gen_ai_token_type="input",...} 91

如果你配置了标量 group claim,那么相同样本还会携带 department= 标签(可通过 grep 'department=' 检查)。打开 dashboard,确认 token 使用量已经显示,并且可以按 namespace、model 和 department 进行过滤。

了解更多

下一步

在采集到 token 使用量后,配置 Token 使用量分摊计费,使用 Alauda Cost Management 将该指标计入每个 namespace 的账单。