Query historical usage by gateway header snapshots (x-trace-id / x-user-id / x-agent-name). Base URL: http://127.0.0.1:9001. Auth: Access tokens.

See Request correlation for header semantics.

Filter rule

The aggregate and paginated list endpoints below require exactly one of trace_id, user_id, or agent_name. Values are the original strings sent in the corresponding request headers. This rule does not apply to the daily model amounts or request-id lookup endpoints.

Aggregate

GET /openapi/trace-usage/aggregate

curl -sS "http://127.0.0.1:9001/openapi/trace-usage/aggregate?trace_id=order-2024-0001" \
  -H "X-Access-Token: $ACCESS_TOKEN"

Query (pick one):

ParamMaps to header
trace_idx-trace-id
user_idx-user-id
agent_namex-agent-name

Example data:

{
  "totalTokens": 123456,
  "promptTokens": 80000,
  "completionTokens": 40000,
  "reasoningTokens": 3456,
  "cachedInputTokens": 12000,
  "totalRequests": 500,
  "okRequests": 480,
  "errorRequests": 20,
  "successRate": 96.00,
  "revenueCredit": 1234,
  "giftCostCredit": 200,
  "paidCostCredit": 1034,
  "avgLatencyMs": 850,
  "avgStreamFirstTokenMs": 120,
  "distinctModels": 5,
  "distinctApiKeys": 3
}

data fields:

FieldTypeDescription
totalTokensnumberTotal tokens (prompt + completion)
promptTokensnumberInput tokens
completionTokensnumberOutput tokens
reasoningTokensnumberReasoning tokens
cachedInputTokensnumberCache-hit input tokens
totalRequestsnumberTotal request count
okRequestsnumberSuccessful requests (status = ok)
errorRequestsnumberFailed requests (status = error)
successRatenumberSuccess rate (0–100, 2 decimal places)
revenueCreditnumberTotal billed credits (revenue side)
giftCostCreditnumberGift-quota billed credits
paidCostCreditnumberPaid-quota billed credits
avgLatencyMsnumber | nullMean end-to-end latency (ms), or null if no data
avgStreamFirstTokenMsnumber | nullMean streaming first-token latency (ms); non-streaming rows excluded
distinctModelsnumberDistinct models involved
distinctApiKeysnumberDistinct API keys involved

Paginated list

GET /openapi/trace-usage/list

curl -sS "http://127.0.0.1:9001/openapi/trace-usage/list?user_id=user-123&page=1&page_size=20" \
  -H "X-Access-Token: $ACCESS_TOKEN"

Additional query params:

ParamDescription
pageDefault 1
page_sizeDefault 20, max 100

Results are ordered by createdAt descending. Example data:

{
  "items": [
    {
      "requestId": "chatcmpl-abc123",
      "createdAt": "2026-06-10T08:30:00.000Z",
      "modelCode": "gpt-4o",
      "protocolSource": "openai",
      "status": "ok",
      "errorCode": null,
      "errorMessage": null,
      "finishReason": "stop",
      "promptTokens": 500,
      "completionTokens": 200,
      "totalTokens": 700,
      "reasoningTokens": 0,
      "cachedInputTokens": 0,
      "revenueCredit": 7,
      "giftCostCredit": 5,
      "paidCostCredit": 2,
      "latencyMs": 850,
      "streamLlmFirstTokenMs": null,
      "userId": "user-123",
      "agentName": "my-agent",
      "traceId": "trace-abc",
      "referer": "https://example.com",
      "clientIp": "1.2.3.4",
      "userAgent": "curl/8.0"
    }
  ],
  "total": 1,
  "page": 1,
  "pageSize": 20
}

data.items[] fields:

FieldTypeDescription
requestIdstring | nullUpstream request ID (OpenAI-compatible id)
createdAtstringRecord creation time (UTC ISO 8601)
modelCodestringRequested model code
protocolSourcestringProtocol source: openai / anthropic
statusstringCall status: ok / error
errorCodestring | nullError code; null on success
errorMessagestring | nullError message; null on success
finishReasonstring | nullUpstream finish_reason (stop, length, etc.)
promptTokensnumberInput tokens
completionTokensnumberOutput tokens
totalTokensnumberTotal tokens
reasoningTokensnumberReasoning tokens
cachedInputTokensnumberCache-hit input tokens
revenueCreditnumberTotal billed credits (revenue side)
giftCostCreditnumberGift-quota billed credits
paidCostCreditnumberPaid-quota billed credits
latencyMsnumber | nullEnd-to-end latency (ms)
streamLlmFirstTokenMsnumber | nullStreaming first-token latency (ms); null for non-streaming
userIdstring | nullOriginal x-user-id header value
agentNamestring | nullOriginal x-agent-name header value
traceIdstring | nullOriginal x-trace-id header value
refererstring | nullReferer header
clientIpstring | nullClient IP
userAgentstring | nullUser-Agent header

Pagination fields:

FieldTypeDescription
itemsarrayCurrent page of records
totalnumberTotal matching record count
pagenumberCurrent page number
pageSizenumberPage size

Request input, output and raw usage by request-id

GET /openapi/request-logs?request_id=...

curl -sS --get "http://127.0.0.1:9001/openapi/request-logs" \
  -H "X-Access-Token: $ACCESS_TOKEN" \
  --data-urlencode "request_id=$REQUEST_ID"

request_id is required and comes from the gateway's x-request-id response header, not the upstream request ID (the Anthropic request-id header may contain an upstream ID). Supply one non-blank value, up to 128 characters. No time range or trace / user / agent selector is required. Only requests belonging to the access token's tenant can be queried. Text, image, video, audio and decision requests are supported.

Example response:

{
  "code": 0,
  "data": {
    "requestId": "req_example",
    "usageSource": "text",
    "userInputText": { "messages": [{ "role": "user", "content": "Hello" }] },
    "responseText": { "choices": [{ "message": { "role": "assistant", "content": "Hi" } }] },
    "usage": { "prompt_tokens": 10, "completion_tokens": 2, "total_tokens": 12 }
  },
  "message": "success"
}

userInputText and responseText are request and response JSON snapshots stored in Elasticsearch. They return null when missing, expired or unavailable. usage is decoded from the raw upstream usage recorded in the database, preserving upstream field names and values without deriving them from platform billing fields. Complementary streaming or polling observations are merged, with the last non-null value winning for each field; token counts are not added. Missing upstream usage returns null.

All business responses from this endpoint use HTTP 200: code = 180001 means invalid query parameters, 180002 means no request was found within the current tenant (including requests belonging to another tenant), and 401 means the access token is missing or invalid.

Daily model usage amounts

GET /-/openapi/usage/daily-by-model

Use the same X-Access-Token authentication to query daily model amounts for the token's account.

curl -sS --get "http://127.0.0.1:9001/-/openapi/usage/daily-by-model" \
  -H "X-Access-Token: $ACCESS_TOKEN" \
  --data-urlencode "from=2026-11-01" \
  --data-urlencode "to=2026-11-08"
ParameterRequiredDescription
fromYesFirst date in YYYY-MM-DD, inclusive in Asia/Shanghai
toYesLast date in YYYY-MM-DD, inclusive in Asia/Shanghai; must not precede from
model_codeNoExact public model code, up to 256 characters; omit for all models

Example response at 100 credits per CNY:

{
  "code": 0,
  "data": {
    "timezone": "Asia/Shanghai",
    "currency": "CNY",
    "items": [
      { "date": "2026-11-01", "usageSource": "text", "modelCode": "gpt-4o-mini", "requests": 100, "estCredits": 1234, "amount": 12.34 }
    ]
  },
  "message": "success"
}

requests includes successful and failed calls. usageSource is text, image, video, audio or decision; identical model codes in different modalities remain separate. estCredits matches the usage dashboard's estimated billing value, including token-package usage valuation, rather than the wallet-debit ledger. amount uses the current site currency and rate, rounded to two decimal places, not a historical exchange-rate snapshot.

Only completed hourly statistics are included. The current hour and unfinished statistics appear later. All results are ordered by date, modality and model code ascending, without pagination or a top-100 limit. Missing dates and models are omitted; no matching data returns items: [].

All business responses use HTTP 200. Missing or repeated parameters, invalid calendar dates, reversed ranges, blank filters or overlong filters return code = 190001. Missing or invalid access tokens return 401.

Errors

HTTPcodeScenario
401401Missing X-Access-Token, or token invalid / disabled / expired
40040001Invalid filter (exactly one of the three params required)

Invalid filter body:

{
  "code": 40001,
  "message": "必须且只能提供 trace_id、user_id、agent_name 中的一个",
  "data": null
}

Related