AI 大模型推理

  • AI 大模型推理 > API 文档 > 用量与账单 >大模型Token预估账单查询

    大模型Token预估账单查询

    最近更新时间: 2026-07-29 17:32:47

    接口概述

    本组接口用于查询 API Key 的大模型消耗费用,包含两个接口:

    • 接口 1:查询 API Key 当天、本周、本月的消耗汇总。
    • 接口 2:查询 API Key 指定时间范围、按天或按月的消耗明细。

    主要能力:

    • 灵活鉴权:支持 API Key(sk-)与 AK/SK 两种鉴权方式。
      • API Key 鉴权:返回当前 Key 的账单。
      • AK/SK 鉴权:返回当前账号下所有 Key 的账单,按 API Key 分组,并返回每个 Key 的名称。
    • 时区支持:通过 timezone 参数指定账单输出时区,按所选时区确定周期起止与明细日期。
    • 多粒度明细:明细查询支持按天(day)或按月(month)聚合。

    接口信息

    • 接入端点: https://api.qnaigc.com
    • 说明: 接口中展示的花费均为原始标准价格,未经资源包等优惠换算
    • 费用单位: 人民币元,保留 2 位小数

    认证方式

    支持两种鉴权方式:

    1. AK/SK 签名认证:使用七牛云标准的 AK/SK 签名认证,返回当前账号下所有 API Key 的账单。
      Authorization: Qiniu <AccessKey>:<EncodedSign>
      
    2. API Key 认证:使用正式 API Key(sk- 开头)认证,返回该 Key 的账单。
      Authorization: Bearer sk-xxxxxxxxxxxxxxxxx
      

    临时 Key(tk- 开头)不允许调用本组接口,会返回 temporary key is not allowed(401)。签名实现请参考 AK/SK 签名实现参考

    接口 1:天/周/月消耗汇总

    查询 API Key 当天、本周、本月的消耗汇总。

    • 接口路径: GET /v3/stat/usage/apikey/cost

    请求参数

    参数名 类型 必填 描述 示例值
    type string 统计周期:day(当天)、week(本周)、month(本月) month
    timezone string 账单输出时区,IANA 时区名称,默认 Asia/Shanghai UTC

    周期口径按 timezone 计算:

    • day:当天 0 点至当前时刻
    • week:本周一 0 点至当前时刻(周一为一周的第一天)
    • month:本月 1 号 0 点至当前时刻

    响应示例

    {
      "status": true,
      "data": {
        "timezone": "Asia/Shanghai",
        "api_keys": [
          {
            "api_key": "sk-7c***fbe19",
            "name": "我的测试 Key",
            "models": [
              {
                "model_id": "deepseek-v3",
                "items": [
                  {
                    "name": "deepseek-v3输入",
                    "key": "input",
                    "usage": { "count": 100.00, "unit": "k/tokens" },
                    "fee": 1.00
                  },
                  {
                    "name": "deepseek-v3输出",
                    "key": "output",
                    "usage": { "count": 100.00, "unit": "k/tokens" },
                    "fee": 1.00
                  }
                ],
                "total_fee": 2.00
              }
            ],
            "total_fee": 2.00
          }
        ]
      }
    }
    
    字段 类型 描述
    data.timezone string 账单输出时区
    data.api_keys array 按 API Key 分组的账单列表
    data.api_keys[].api_key string API Key(脱敏,格式 前缀+前2位+***+后5位,如 sk-7c***fbe19
    data.api_keys[].name string 该 API Key 的名称
    data.api_keys[].models array 按模型分组的账单
    data.api_keys[].models[].model_id string 模型 ID
    data.api_keys[].models[].items array 计费项列表(结构见 响应字段说明
    data.api_keys[].models[].total_fee number 该模型的总费用
    data.api_keys[].total_fee number 该 API Key 的总费用

    接口 2:消耗明细查询

    查询 API Key 指定时间范围、按天或按月聚合的消耗明细。

    • 接口路径: GET /v3/stat/usage/apikey/cost-detail

    请求参数

    参数名 类型 必填 描述 示例值
    start_date string 开始日期,格式 YYYY-MM-DD 2026-01-01
    end_date string 结束日期,格式 YYYY-MM-DD 2026-01-31
    grain string 聚合粒度:day(按天,默认)或 month(按月) day
    timezone string 账单输出时区,IANA 时区名称,默认 Asia/Shanghai UTC

    参数校验

    • start_date / end_date 必填,格式须为 YYYY-MM-DD
    • start_date 不能晚于 end_date
    • 查询范围不能超过 100 天
    • grain 仅支持 daymonth

    响应示例

    响应结构随鉴权方式不同而不同。

    AK/SK 鉴权(返回账号下所有 API Key 的明细)

    {
      "status": true,
      "data": {
        "period": "2025-01-01 ~ 2025-01-31",
        "grain": "day",
        "timezone": "Asia/Shanghai",
        "total_fee": 150.00,
        "api_keys": [
          {
            "api_key": "sk-7c***fbe19",
            "name": "我的测试 Key",
            "total_fee": 100.00,
            "bills": [
              {
                "date": "2025-01-01",
                "total_fee": 50.00,
                "models": [
                  {
                    "model_id": "deepseek-v3",
                    "items": [
                      {
                        "name": "deepseek-v3输入",
                        "key": "input",
                        "usage": { "count": 100.00, "unit": "k/tokens" },
                        "fee": 1.00
                      }
                    ],
                    "total_fee": 1.00
                  }
                ]
              }
            ]
          },
          {
            "api_key": "sk-3a***9b12",
            "name": "生产环境 Key",
            "total_fee": 50.00,
            "bills": [ ... ]
          }
        ]
      }
    }
    

    API Key 鉴权(返回单个 API Key 的明细)

    {
      "status": true,
      "data": {
        "api_key": "sk-7c***fbe19",
        "name": "我的测试 Key",
        "period": "2025-01-01 ~ 2025-01-31",
        "grain": "day",
        "timezone": "Asia/Shanghai",
        "total_fee": 100.00,
        "bills": [
          {
            "date": "2025-01-01",
            "total_fee": 50.00,
            "models": [
              {
                "model_id": "deepseek-v3",
                "items": [
                  {
                    "name": "deepseek-v3输入",
                    "key": "input",
                    "usage": { "count": 100.00, "unit": "k/tokens" },
                    "fee": 1.00
                  }
                ],
                "total_fee": 1.00
              }
            ]
          },
          {
            "date": "2025-01-02",
            "total_fee": 50.00,
            "models": [ ... ]
          }
        ]
      }
    }
    

    响应字段说明

    接口 1 与接口 2 共用以下计费项结构。

    计费项 items[]

    字段 类型 描述
    name string 计费项名称(中文描述)
    key string 计费项标识(如 inputoutput
    usage object 用量信息
    usage.count number 用量数值(保留 2 位小数)
    usage.unit string 用量单位(如 k/tokens百字符分钟tokens
    fee number 该计费项费用(人民币元)

    明细账单 bills[](接口 2)

    字段 类型 描述
    date string 日期(grain=day 时为 YYYY-MM-DDgrain=month 时为 YYYY-MM
    total_fee number 该时间点的总费用
    models array 按模型分组的账单(model_id / items / total_fee

    其他公共字段

    字段 类型 描述
    api_key string API Key(脱敏,格式 前缀+前2位+***+后5位
    name string 该 API Key 的名称
    period string 时间范围,格式 YYYY-MM-DD ~ YYYY-MM-DD
    grain string 聚合粒度:daymonth
    timezone string 账单输出时区
    total_fee number 总费用(人民币元)

    错误响应

    { "status": false, "error": "错误信息描述" }
    

    错误码说明

    HTTP 状态码 错误类型 描述
    400 Bad Request 请求参数错误(type / 日期格式 / 时间范围 / 粒度 / 时区等)
    401 Unauthorized 鉴权失败(含临时 Key 被拒绝)
    500 Internal Server Error 服务器内部错误

    常见错误信息

    接口 1:

    • "invalid type, must be day/week/month": type 取值非法
    • "无效的 timezone,需使用 IANA 时区名称,例如 UTC": timezone 取值为 Local 或无法识别

    接口 2:

    • "start_date and end_date are required": 缺少日期参数
    • "invalid start_date format, expected 2006-01-02" / "invalid end_date format, expected 2006-01-02": 日期格式错误
    • "start_date cannot be after end_date": 开始日期晚于结束日期
    • "date range cannot exceed 100 days": 查询范围超过 100 天
    • "invalid grain, must be day or month": grain 取值非法
    • "无效的 timezone,需使用 IANA 时区名称,例如 UTC": timezone 取值为 Local 或无法识别

    鉴权类(两接口通用):

    • "temporary key is not allowed": 使用了临时 Key(tk-
    • "invalid api key or aksk": API Key 或 AK/SK 无效
    • "missing authorization header": 缺少鉴权信息

    使用示例

    示例 1:查询本月消耗汇总(API Key)

    curl --location "https://api.qnaigc.com/v3/stat/usage/apikey/cost?type=month" \
      --header "Authorization: Bearer sk-xxxxxxxxxxxxxxxxx"
    

    示例 2:查询本周消耗汇总(AK/SK,指定 UTC 时区)

    curl --location "https://api.qnaigc.com/v3/stat/usage/apikey/cost?type=week&timezone=UTC" \
      --header "Authorization: Qiniu <AccessKey>:<EncodedSign>"
    

    示例 3:按天查询消耗明细(API Key)

    curl --location "https://api.qnaigc.com/v3/stat/usage/apikey/cost-detail?start_date=2026-01-01&end_date=2026-01-31&grain=day" \
      --header "Authorization: Bearer sk-xxxxxxxxxxxxxxxxx"
    

    示例 4:按月查询消耗明细(AK/SK)

    curl --location "https://api.qnaigc.com/v3/stat/usage/apikey/cost-detail?start_date=2026-01-01&end_date=2026-03-31&grain=month" \
      --header "Authorization: Qiniu <AccessKey>:<EncodedSign>"
    

    注意事项

    1. 价格口径: 返回费用为原始标准价格,不含资源包等优惠。
    2. 时区处理: 周期起止与明细日期均按 timezone 计算,建议按实际业务所在时区传入;不传时默认 Asia/Shanghai
    3. 数据时效: 当天数据可能存在延迟,建议查询昨天及之前的数据。
    4. Key 类型: 仅正式 Key(sk-)可调用,临时 Key(tk-)会被拒绝。
    5. 范围限制: 明细查询最大跨度为 100 天。

    AK/SK 签名实现参考

    const crypto = require('crypto')
    
    /**
     * URL 安全的 Base64 编码
     * @param {Buffer} buffer - 要编码的数据
     * @returns {string} - URL 安全的 Base64 字符串
     */
    function urlSafeBase64Encode(buffer) {
      return buffer.toString('base64')
        .replace(/\+/g, '-')
        .replace(/\//g, '_');
    }
    
    /**
     * 生成待签名的原始字符串
     * @param {Object} options - 请求参数
     * @param {string} options.method - HTTP 方法(大小写敏感)
     * @param {string} options.path - 请求路径
     * @param {string} [options.query] - 查询参数(不包含 ?)
     * @param {string} options.host - 主机名
     * @param {string} [options.contentType] - Content-Type
     * @param {Object} [options.headers] - X-Qiniu-* 开头的自定义头(可选)
     * @param {string} [options.body] - 请求体(可选)
     * @returns {string} - 待签名的字符串
     */
    function generateSigningString(options) {
      const { method, path, query, host, contentType, headers, body } = options
    
      // 1. Method + 空格 + Path
      let signingStr = method.toUpperCase()
    
      // 2. 添加 Path 和 Query
      signingStr += ' ' + path
      if (query) {
        signingStr += '?' + query
      }
    
      // 3. 添加 Host
      signingStr += '\nHost: ' + host
    
      // 4. 添加 Content-Type(如果有)
      if (contentType) {
        signingStr += '\nContent-Type: ' + contentType
      }
    
      // 5. 添加 X-Qiniu-* 头部(如果有)
      if (headers) {
        // 按 key 的 ASCII 排序
        const sortedKeys = Object.keys(headers).sort()
        sortedKeys.forEach(key => {
          if (key.toLowerCase().startsWith('x-qiniu-')) {
            // 格式化 key:每个单词首字母大写,其余小写
            const formattedKey = key.split('-')
              .map((part) => {
                return part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()
              })
              .join('-')
            signingStr += '\n' + formattedKey + ': ' + headers[key]
          }
        })
      }
    
      // 6. 添加两个连续换行符
      signingStr += '\n\n'
    
      // 7. 添加 Body(如果有且 Content-Type 不是 application/octet-stream)
      if (body && contentType && contentType !== 'application/octet-stream') {
        signingStr += body
      }
    
      return signingStr
    }
    
    /**
     * 生成七牛云管理凭证(Access Token)
     * @param {string} accessKey - 七牛云 AccessKey
     * @param {string} secretKey - 七牛云 SecretKey
     * @param {Object} requestOptions - 请求参数(同 generateSigningString)
     * @returns {string} - 管理凭证字符串
     */
    function generateAccessToken(accessKey, secretKey, requestOptions) {
      // 1. 生成待签名的原始字符串
      const signingStr = generateSigningString(requestOptions);
    
      // 2. 使用 HMAC-SHA1 计算签名
      const hmac = crypto.createHmac('sha1', secretKey);
      hmac.update(signingStr);
      const sign = hmac.digest();
    
      // 3. 对签名进行 URL 安全的 Base64 编码
      const encodedSign = urlSafeBase64Encode(sign);
    
      // 4. 将 AccessKey 和 encodedSign 用冒号连接
      return accessKey + ':' + encodedSign;
    }
    
    // 示例:调用消耗汇总接口
    const accessKey = '你的 AccessKey'
    const secretKey = '你的 SecretKey'
    const requestOptions = {
      method: 'GET',
      path: '/v3/stat/usage/apikey/cost',
      query: 'type=month',
      // 调用明细接口:
      // path: '/v3/stat/usage/apikey/cost-detail',
      // query: 'start_date=2026-01-01&end_date=2026-01-31&grain=day',
      host: 'api.qnaigc.com'
    }
    const accessToken = generateAccessToken(accessKey, secretKey, requestOptions)
    console.log('Access Token:', accessToken)
    
    // 实际请求
    fetch('https://api.qnaigc.com/v3/stat/usage/apikey/cost?type=month', {
      headers: { 'Authorization': 'Qiniu ' + accessToken }
    }).then(res => res.json()).then(console.log)
    
    以上内容是否对您有帮助?