Skip to content

Bug: Token usage always 0 for non-native OpenAI-compatible endpoints (e.g., Alibaba Bailian) #45038

Description

@xiaochangtongxue

Problem

Token usage statistics always show 0 for non-native OpenAI-compatible endpoints like Alibaba Bailian (百炼), even when the API correctly returns usage data.

Root Cause

The issue is in the OpenAI-completions response parser. The code expects input_tokens and output_tokens fields:

// model-selection-_2UcLVem.js line ~103206
input: response.usage?.input_tokens ?? 0,
output: response.usage?.output_tokens ?? 0,
totalTokens: response.usage?.total_tokens ?? 0

However, Bailian API returns prompt_tokens and completion_tokens (standard OpenAI format):

{
  "usage": {
    "prompt_tokens": 11,
    "completion_tokens": 543,
    "total_tokens": 554
  }
}

The normalizeUsage function in OpenClaw correctly handles this fallback pattern:

const rawInput = asFiniteNumber(raw.input ?? raw.inputTokens ?? raw.input_tokens ?? raw.promptTokens ?? raw.prompt_tokens);

But the response parser in the code path for non-streaming responses doesn't use this normalization, causing input_tokens and output_tokens to be undefined, resulting in 0 values.

Additional Issue

For streaming, OpenClaw also forces supportsUsageInStreaming: false for non-native endpoints (CHANGELOG #8714), which may be overly conservative since Bailian supports stream_options: { include_usage: true }.

Steps to Reproduce

  1. Configure a non-native OpenAI-compatible endpoint (e.g., Bailian):
{
  "models": {
    "providers": {
      "bailian": {
        "baseUrl": "https://coding.dashscope.aliyuncs.com/v1",
        "api": "openai-completions",
        "models": [{ "id": "qwen3.5-plus", ... }]
      }
    }
  }
}
  1. Send messages and check /status - context tokens always show 0.

Actual Behavior

Token usage always shows 0 in /status and session context (e.g., "Context: 0/203k (0%)"), even though the Bailian API correctly returns usage data with prompt_tokens and completion_tokens fields.

Expected Behavior

Token usage should be correctly parsed from prompt_tokens/completion_tokens fallback fields, matching the behavior of the normalizeUsage function.

Environment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions