
Huawei Cloud Maas Tokens Usage
- 72 installs
- 19 repo stars
- Updated July 31, 2026
- huaweicloud/huaweicloud-skills
Huawei Cloud MaaS Tokens Usage is an agent skill that runs the documented REST usage script with correct service types, credential patterns, and time ranges.
About
Huawei Cloud MaaS Tokens Usage is an agent skill that wraps the bundled Python CLI for pulling Model-as-a-Service token usage from Huawei Cloud over a defined interval. Solo builders and small teams shipping agents or APIs on Huawei MaaS install it when they need auditable usage pulls for billing reconciliation, capacity planning, or incident review—not ad-hoc guessing from the console. The skill encodes acceptance criteria that agents often get wrong: valid service_type values (1, 2, 4 only), credential sourcing from environment variables or a credentials file, and strict calendar semantics for phrases like last 7 days versus this month. It fits the Operate phase because it assumes live services and AK/SK access, and it reinforces safe handling by directing users to configure secrets locally rather than pasting keys into the conversation. Use it whenever you need deterministic REST statistics aligned with Huawei’s API rather than improvised curl or unsupported parameter combinations.
- REST script maas_rest_usage_stats.py with --from/--to date ranges
- service-type 1 (My Service), 2 (Preset Service), and 4 (Custom Endpoint)—not 3
- Credentials via HW_ACCESS_KEY/HW_SECRET_KEY env vars or --credentials-file (line, comma, or KEY=VALUE formats)
- Explicit distinction between “last 7 days” and “this month” when interpreting user requests
- Security pattern: never ask for AK/SK in chat and never hardcode secrets in code
Huawei Cloud Maas Tokens Usage by the numbers
- 72 all-time installs (skills.sh)
- +4 installs in the week ending Aug 2, 2026 (Skillselion tracking)
- Ranked #646 of 1,042 Cloud & Infrastructure skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/huaweicloud/huaweicloud-skills --skill huawei-cloud-maas-tokens-usageAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 72 |
|---|---|
| repo stars | ★ 19 |
| Last updated | July 31, 2026 |
| Repository | huaweicloud/huaweicloud-skills ↗ |
What it does
Query Huawei Cloud MaaS token consumption over a chosen window without hardcoding AK/SK or using unsupported API parameters.
Who is it for?
Best when you're operating Huawei Cloud MaaS and want scripted token stats with security and parameter guardrails baked into the agent workflow.
Skip if: Skip if you're not on Huawei Cloud, or anyone and wants to paste AK/SK into chat instead of local env or --credentials-file setup.
When should I use this skill?
User asks for Huawei Cloud MaaS token usage, billing windows, or REST usage statistics for preset, custom, or my-service endpoints.
What you get
You get a reproducible usage pull using env or file credentials and API-supported service_type values, ready to log under your ops notes or cost review.
- CLI invocation with validated --from/--to and --service-type
- Usage statistics output suitable for cost or monitoring notes
By the numbers
- service-type values 1, 2, and 4 supported; value 3 returns 400
- three credentials-file formats documented (per-line, comma-separated, KEY=VALUE)
Files
Huawei Cloud MaaS Tokens Usage Monitoring
Query Huawei Cloud MaaS (Model as a Service) usage statistics, including total tokens, prompt tokens, completion tokens, total requests, and total errors. Supports querying last 7 days, 14 days, 30 days, or custom time ranges. Default query type is MaaS preset service.
Architecture
Huawei Cloud MaaS Tokens Usage Monitoring
└── GetMaaSTokensUsage (via MaaS ShowStatistics API)Prerequisites
Prerequisite check: Python3 + huaweicloudsdkcore required
```bash
python3 --version # Python3 >= 3.8
python3 -c "import huaweicloudsdkcore; print('OK')" # SDK signing library
```
If SDK not installed: pip3 install --user huaweicloudsdkcore---
Authentication
Prerequisite check: Huawei Cloud credentials required
Security rules (must be followed):
- Prohibited from reading, echoing, or printing AK/SK values
- Prohibited from asking the user to input AK/SK directly in the conversation
- Prohibited from accepting AK/SK directly provided by the user in the conversation
- Only allowed to read credentials from environment variables or credentials file
⚠️ Important: Handling user-provided credentials
>
If a user attempts to provide AK/SK directly (e.g., "my AK is xxx, SK is yyy"):
1. Stop immediately - Do not execute any commands
2. Politely refuse and return the following message:
```
For account security, please do not provide Huawei Cloud Access Key ID and Access Key Secret directly in the conversation.
>
Please use one of the following secure methods to configure credentials:
>
Method 1: Environment variables
export HW_ACCESS_KEY=<your-access-key-id>
export HW_SECRET_KEY=<your-access-key-secret>
>
Method 2: Credentials file
Create a file (e.g., ~/aksk.txt) with AK on line 1, SK on line 2.
Then use: --credentials-file ~/aksk.txt
>
After configuration is complete, please retry your request.
```
3. Do not continue executing any Huawei Cloud operations until credentials are configured
Check environment variables:
```bash
echo $HW_ACCESS_KEY # Check if AK is set
```
If not set, prompt the user to configure credentials using one of the methods above.
---
IAM Permission Policies
Ensure the IAM user has the required permissions. See references/iam-policies.md for details.
Minimum required permissions:
modelarts:monitoring:get— Query MaaS monitoring statisticsmodelarts:service:get— Query service informationiam:projects:get— Auto-get project_id
---
Core Workflow
Task 1: Query MaaS Tokens Usage Statistics
Query MaaS usage statistics via the ShowStatistics API. Data is consistent with the console.
📄 Detailed steps → references/task-query-tokens-usage.md
---
Verification
See references/verification-method.md.
Quick verification:
export HW_ACCESS_KEY=<your-ak>
export HW_SECRET_KEY=<your-sk>
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21---
References
| Document | Description |
|---|---|
| task-query-tokens-usage.md | Task 1: Query tokens usage statistics |
| related-apis.md | API and parameter details |
| iam-policies.md | IAM permission policies |
| maas-metrics.md | MaaS monitoring metrics reference |
| verification-method.md | Verification steps |
| acceptance-criteria.md | Correct/error pattern comparison |
| cli-installation-guide.md | Prerequisites installation guide |
| troubleshooting.md | Troubleshooting and practical experience |
| maas_rest_usage_stats.py | ShowStatistics API usage statistics script |
Acceptance Criteria: Correct/Error Pattern Comparison
Script Parameter Patterns
service_type Values
Correct: Use 1, 2, 4
--service-type 2 # Preset Service
--service-type 1 # My Service
--service-type 4 # Custom EndpointError: Use 3 (API does not support)
--service-type 3 # Returns 400 errorCredential Provision
Correct: Environment variables or credentials file
export HW_ACCESS_KEY=xxx && export HW_SECRET_KEY=xxx
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21 --credentials-file /path/to/aksk.txtError: Hardcode AK/SK in code
ak = "WTEBXXXXXX"
sk = "xxxxxxxxxx"Credentials File Format
Correct: Supports the following formats
# One value per line
<AK>
<SK>
# Comma-separated
<AK>,<SK>
# KEY=VALUE format
HW_ACCESS_KEY=<AK>
HW_SECRET_KEY=<SK>Security Standards
Credential Handling
Correct: Guide users to configure credentials themselves
Please set environment variables HW_ACCESS_KEY and HW_SECRET_KEY
Or use --credentials-file to specify a credentials fileError: Ask users for AK/SK in conversation
Please tell me your AK and SKTime Range Standards
Correct: Strictly distinguish "last 7 days" and "this month"
- "last 7 days": now-7d ~ now
- "this month": 1st of month ~ now
Error: Confuse time ranges
- User says "last 7 days" but calculate as "this month"
Timezone Standards
Correct: Follow OS local timezone, auto-detect
Error: Hardcode CST/Asia/Shanghai
Prerequisites Installation Guide
Python3 + huaweicloudsdkcore
# Check Python3 version
python3 --version # Requires >= 3.8
# Install SDK signing library
pip3 install --user huaweicloudsdkcore
# Verify
python3 -c "import huaweicloudsdkcore; print('SDK OK')"Credentials Configuration
Method 1: Environment variables (recommended)
export HW_ACCESS_KEY=<your-access-key-id>
export HW_SECRET_KEY=<your-access-key-secret>Method 2: Credentials file
Create a file supporting three formats:
# One value per line
<AK>
<SK>
# Comma-separated
<AK>,<SK>
# KEY=VALUE format
HW_ACCESS_KEY=<AK>
HW_SECRET_KEY=<SK>Usage: --credentials-file /path/to/aksk.txt
Security reminder:
- Never provide AK/SK directly in conversation
- Never hardcode AK/SK in scripts
MaaS Service Regions
| Region | Region ID |
|---|---|
| Southwest-Guiyang-1 | cn-southwest-2 |
MaaS ShowStatistics API currently only supports Southwest-Guiyang-1 region.
IAM Permission Policy
Required Permissions
| Operation | Permission | Description |
|---|---|---|
| Query MaaS monitoring statistics | modelarts:monitoring:get | Call ShowStatistics API |
| Query service information | modelarts:service:get | Get service list etc. |
| Get project ID | iam:projects:get | Auto-get project_id |
Minimum Permission Policy
{
"Version": "1.1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"modelarts:monitoring:get",
"modelarts:service:get",
"iam:projects:get"
]
}
]
}Predefined Permission Policies
- ModelArts CommonOperations — ModelArts common operations (includes
modelarts:service:get,modelarts:monitoring:get) - IAM ReadOnlyAccess — IAM read-only access (includes
iam:projects:get)
MaaS Monitoring Metrics Reference
MaaS ShowStatistics API
API
POST /v1/{project_id}/maas/monitoring/show-statistics
Response Metrics
| Field | Type | Description | Unit | Conversion |
|---|---|---|---|---|
total_request_count | Integer | Total request count | count | Use directly |
total_error_count | Integer | Total error count | count | Use directly |
total_token | Double | Total tokens (prompt + completion) | thousand | Actual = value × 1000 |
total_prompt_token | Double | Total prompt tokens | thousand | Actual = value × 1000 |
total_completion_token | Double | Total completion tokens | thousand | Actual = value × 1000 |
total_completion_tasks | Integer | Completed batch inference tasks | count | Batch inference only |
total_infer_count | Integer | Total inference count | count | Batch inference only |
service_type Values
| service_type | Description |
|---|---|
| 1 | My Service (model service deployed on "My Service" page) |
| 2 | Preset Service (model service enabled on "Preset Service" tab) |
| 4 | Custom Endpoint (endpoint service created on "Custom Endpoint" tab) |
Note: API doc says 3=Custom Endpoint, but the actual API only supports [1, 2, 4].
infer_type Values
| infer_type | Description |
|---|---|
real_time | Online inference |
batch | Batch inference (restricted use phase) |
Limitations
- Only retains 30 days of statistics data
- API rate limit: total requests ≤ 1000/min, per-user ≤ 200/min
References
| Document | Description |
|---|---|
| related-apis.md | API and parameter details |
Related APIs
MaaS ShowStatistics API
API Information
- API:
POST /v1/{project_id}/maas/monitoring/show-statistics - Endpoint:
modelarts.{region}.myhuaweicloud.com(dynamically assembled) - Auth: AK/SK signing (SDK-HMAC-SHA256)
- API Doc: https://support.huaweicloud.com/api-maas/ShowStatistics.html
- Rate limit: Total requests ≤ 1000/min, per-user ≤ 200/min
Request Parameters
| Parameter | Required | Type | Description |
|---|---|---|---|
service_type | Yes | Integer | 1=My Service, 2=Preset Service, 4=Custom Endpoint |
start_time | Yes | Long | Start time, millisecond timestamp |
end_time | Yes | Long | End time, millisecond timestamp (≤ 30 days from start_time) |
infer_type | Yes | String | "real_time"=online inference, "batch"=batch inference |
timezone | No | String | IANA format, defaults to OS local timezone |
api_keys | No | Array of strings | Filter by API Key list, pass empty string "" for online experience calls |
ips | No | Array of strings | Filter by IP address |
Response Parameters
| Parameter | Type | Description | Unit |
|---|---|---|---|
total_request_count | Integer | Total request count | count |
total_error_count | Integer | Total error count | count |
total_token | Double | Total tokens | thousand |
total_prompt_token | Double | Total prompt tokens | thousand |
total_completion_token | Double | Total completion tokens | thousand |
total_completion_tasks | Integer | Completed batch inference tasks | count |
total_infer_count | Integer | Total inference count | count |
Request Example
{
"service_type": 2,
"start_time": 1778169600000,
"end_time": 1779292800000,
"timezone": "Asia/Shanghai",
"infer_type": "real_time"
}Response Example
{
"total_request_count": 67188,
"total_error_count": 8002,
"total_token": 2482084.98,
"total_prompt_token": 2456504.362,
"total_completion_token": 24872.928,
"total_completion_tasks": 0,
"total_infer_count": 0
}Python Script Invocation
export HW_ACCESS_KEY=<your-ak>
export HW_SECRET_KEY=<your-sk>
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21References
| Document | Description |
|---|---|
| MaaS ShowStatistics API | Official API documentation |
Task 1: Query MaaS Tokens Usage Statistics
Query MaaS usage statistics via the ShowStatistics API. Data is consistent with the Huawei Cloud console.
API Information
- API:
POST /v1/{project_id}/maas/monitoring/show-statistics - Endpoint:
modelarts.{region}.myhuaweicloud.com(dynamically assembled) - Region limitation: Only supports Southwest-Guiyang-1 (cn-southwest-2)
- Auth: AK/SK signing (SDK-HMAC-SHA256), via huaweicloudsdkcore
Signer - API Doc: https://support.huaweicloud.com/api-maas/ShowStatistics.html
- Rate limit: Total requests ≤ 1000/min, per-user ≤ 200/min
Important: Default region is cn-southwest-2
MaaS ShowStatistics API only supports Southwest-Guiyang-1 region (cn-southwest-2).
---
Script: maas_rest_usage_stats.py
Query via MaaS ShowStatistics API. The script automatically handles:
- AK/SK signing via huaweicloudsdkcore (no manual signing needed)
- Auto-segmentation for time ranges exceeding 30 days
- Auto-detection of OS local timezone
Required Parameters
| Parameter | Description |
|---|---|
--from | Start date in YYYY-MM-DD format |
--to | End date in YYYY-MM-DD format |
| Credentials | Environment variables (HW_ACCESS_KEY, HW_SECRET_KEY) or --credentials-file |
Optional Parameters
| Parameter | Default | Description |
|---|---|---|
--region | cn-southwest-2 | Huawei Cloud region |
--service-type | 2 | 1=My Service, 2=Preset Service, 4=Custom Endpoint |
--infer-type | real_time | real_time=Online inference, batch=Batch inference |
--api-keys | All keys | Filter by API Key list |
--raw | off | Show raw API response |
--credentials-file | - | Credentials file path |
Usage Examples
# Environment variables
export HW_ACCESS_KEY=<your-ak>
export HW_SECRET_KEY=<your-sk>
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21
# Credentials file (supports: one-per-line, comma-separated, KEY=VALUE)
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21 --credentials-file /path/to/aksk.txt
# My Service
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21 --service-type 1
# Custom Endpoint
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21 --service-type 4
# Batch inference
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21 --infer-type batch
# Filter by API Key
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21 --api-keys key1 key2
# Show raw API response
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21 --raw---
Time Range Handling
Key: Time range must match user expression exactly
| User expression | Time range | Description |
|---|---|---|
| "last 7 days" | now-7d ~ now | Rolling 7-day window |
| "last 14 days" | now-14d ~ now | Rolling 14-day window |
| "last 30 days" / "last month" | now-30d ~ now | Rolling 30-day window |
| "this month" | 1st of month 00:00:00 ~ now | Calendar month |
| Specific date range | User-specified start and end | e.g. "May 1 to May 19" |
Default time range: If not specified, default to last 7 days.
30-day data retention: API only retains 30 days of statistics. The script automatically segments queries exceeding 30 days and aggregates results.
---
service_type Values
| service_type | Description |
|---|---|
| 1 | My Service (model service deployed on "My Service" page) |
| 2 | Preset Service (model service enabled on "Preset Service" tab) [Default] |
| 4 | Custom Endpoint (endpoint service created on "Custom Endpoint" tab) |
Note: API doc says 3=Custom Endpoint, but the actual API only supports [1, 2, 4]. Using 3 returns a 400 error.
---
Execution Steps
Step 1: Run the script
export HW_ACCESS_KEY=<your-ak>
export HW_SECRET_KEY=<your-sk>
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21Step 2: View output
MaaS Preset Service Usage Statistics - Region: cn-southwest-2
+────────────────────+──────────────────────+
| Metric | Value |
+════════════════════+══════════════════════+
| Total Tokens | 2,482.08 M tokens |
| Prompt Tokens | 2,456.50 M tokens |
| Completion Tokens | 24.87 M tokens |
| Total Requests | 67,188 |
| Total Errors | 8,002 |
| Error Rate | 11.91% |
+────────────────────+──────────────────────+
Period: 2026-05-08 00:00:00 ~ 2026-05-21 00:00:00 (CST)---
Response Fields
| Field | Type | Description | Unit | Conversion |
|---|---|---|---|---|
total_request_count | Integer | Total request count | count | Use directly |
total_error_count | Integer | Total error count | count | Use directly |
total_token | Double | Total tokens (prompt + completion) | thousand | Actual = value × 1000 |
total_prompt_token | Double | Total prompt tokens | thousand | Actual = value × 1000 |
total_completion_token | Double | Total completion tokens | thousand | Actual = value × 1000 |
Token unit conversion: API returns values in thousands. For example, total_token: 2482084.98 → actual = 2,482,084,980 tokens ≈ 2,482.08 M tokens.---
Error Rate Calculation
Error rate = Total errors / Total requests × 100%---
References
| Document | Description |
|---|---|
| maas_rest_usage_stats.py | ShowStatistics API usage statistics script |
| related-apis.md | API and parameter details |
| maas-metrics.md | MaaS monitoring metrics reference |
| troubleshooting.md | Troubleshooting and practical experience |
Troubleshooting and Practical Experience
1. MaaS ShowStatistics API Issues
Issue: DNS cannot resolve maas.{region}.myhuaweicloud.com
Symptom: socket.gaierror: [Errno -2] Name or service not known
Root cause: MaaS API has no independent maas.* domain. It reuses the ModelArts endpoint.
Solution: Use modelarts.{region}.myhuaweicloud.com as the endpoint (dynamically assembled).
Issue: AK/SK signing returns 401
Symptom: verify ak sk signature failed
Root cause: Manually implementing HWS-HMAC-SHA256 signing algorithm is error-prone.
Solution: Use huaweicloudsdkcore Signer class. Do not implement signing manually.
Issue: service_type=3 returns 400
Symptom: "service_type must be one of [1 2 4]"
Root cause: API doc says 3=Custom Endpoint, but the actual API only supports [1, 2, 4].
Solution: Use service_type=4 for Custom Endpoint.
Issue: ShowStatistics returns all zeros
Possible causes: 1. Incorrect timestamp calculation (missing timezone) 2. Time range exceeds 30 days 3. Wrong service_type (no calls for that type)
Troubleshooting: 1. Verify timestamp is correct 2. Ensure time range ≤ 30 days (script auto-segments longer ranges) 3. Try different service_type
Issue: Small discrepancy between API and console
Symptom: API returns 67,188, console shows 67,118.
Possible cause: Minor time boundary differences.
Conclusion: Discrepancy is within reasonable range (< 0.1%). Data is reliable.
2. AK/SK Signing Implementation
Recommended: Use huaweicloudsdkcore Signer
from huaweicloudsdkcore.signer.signer import Signer
from huaweicloudsdkcore.sdk_request import SdkRequest
class _Creds:
def __init__(self, ak, sk):
self.ak = ak
self.sk = sk
signer = Signer(_Creds(ak, sk))
req = SdkRequest(
method="POST", schema="https", host=host,
resource_path=path, uri=path, query_params=[],
header_params={"Content-Type": "application/json"}, body=body_bytes
)
signed_req = signer.sign(req)
headers = {k: v for k, v in signed_req.header_params.items()}Sending the signed request
Important: The body sent must exactly match the body used during signing, otherwise 401 error.
url = f"https://{host}{signed_req.uri}"
resp = requests.post(url, headers=headers, data=body_bytes, verify=False)3. Timestamp Issues
Issue: Naive datetime timestamp is incorrect
Solution: Use timezone-aware datetime. The script auto-detects the OS local timezone.
4. Permission Issues
Issue: Returns 403 error
Solution: Ensure the IAM user has modelarts:service:get and modelarts:monitoring:get permissions. See iam-policies.md.
Verification Steps and Methods
Prerequisite Verification
1. Verify Python3 and SDK
python3 --version # Python3 >= 3.8
python3 -c "import huaweicloudsdkcore; print('SDK OK')"2. Verify Credentials
# Environment variables
echo "AK set: $([ -n \"$HW_ACCESS_KEY\" ] && echo 'YES' || echo 'NO')"
# Or credentials file
cat /path/to/aksk.txtFunctional Verification
# Environment variables
export HW_ACCESS_KEY=<your-ak>
export HW_SECRET_KEY=<your-sk>
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21
# Credentials file
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21 --credentials-file /path/to/aksk.txt
# Different service_type
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21 --service-type 1
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21 --service-type 4
# Raw response
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21 --rawEnd-to-End Verification Script
#!/bin/bash
set -e
echo "=== 1. Verify Python3 and SDK ==="
python3 --version
python3 -c "import huaweicloudsdkcore; print('SDK OK')"
echo "=== 2. Verify ShowStatistics API ==="
python3 scripts/maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21 --credentials-file /home/lj/aksk.txt
echo "=== All verifications passed ==="Verification Checklist
| Check | Expected Result |
|---|---|
| Python3 version | >= 3.8 |
| huaweicloudsdkcore | Import successful |
| Credentials | Environment variables or credentials file provided |
| ShowStatistics API | Returns 200, total_request_count > 0 |
| Script output format | Table + Period |
| Token unit conversion | M tokens (thousand × 1000 = actual tokens) |
| service_type | Supports 1/2/4 |
#!/usr/bin/env python3
"""
MaaS monitoring data query via Huawei Cloud SDK signing + MaaS ShowStatistics API
API doc: https://support.huaweicloud.com/api-maas/ShowStatistics.html
POST /v1/{project_id}/maas/monitoring/show-statistics
Endpoint: modelarts.{region}.myhuaweicloud.com
Auth: AK/SK signing (SDK-HMAC-SHA256)
Token unit: response values are in thousands, actual = value x 1000
Environment variables:
HW_ACCESS_KEY: Huawei Cloud AK
HW_SECRET_KEY: Huawei Cloud SK
Usage:
export HW_ACCESS_KEY=your_ak
export HW_SECRET_KEY=your_sk
python3 maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21
python3 maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21 --service-type 1
python3 maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21 --service-type 4
python3 maas_rest_usage_stats.py --from 2026-05-08 --to 2026-05-21 --infer-type batch
"""
import argparse
import json
import os
import sys
from datetime import datetime, timezone, timedelta
import requests
import urllib3
from huaweicloudsdkcore.signer.signer import Signer
from huaweicloudsdkcore.sdk_request import SdkRequest
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
SERVICE_TYPE_MAP = {
1: "My Service",
2: "Preset Service",
4: "Custom Endpoint",
}
def _local_iana_tz():
try:
tz_key = datetime.now().astimezone().tzname()
mapping = {"CST": "Asia/Shanghai", "EST": "America/New_York", "PST": "America/Los_Angeles"}
return mapping.get(tz_key, tz_key)
except Exception:
return "Asia/Shanghai"
class _Creds:
def __init__(self, ak, sk):
self.ak = ak
self.sk = sk
def _sign_and_request(method, host, resource_path, query_params, headers, body, ak, sk):
signer = Signer(_Creds(ak, sk))
if isinstance(body, str):
body = body.encode("utf-8")
elif body is None:
body = b""
req = SdkRequest(
method=method,
schema="https",
host=host,
resource_path=resource_path,
uri=resource_path,
query_params=query_params or [],
header_params=headers,
body=body,
)
signed_req = signer.sign(req)
req_headers = {}
for k, v in signed_req.header_params.items():
req_headers[k] = v
url = f"https://{host}{signed_req.uri}"
return requests.request(method, url, headers=req_headers, data=body, verify=False, timeout=30)
def get_project_id(ak, sk, region):
iam_host = f"iam.{region}.myhuaweicloud.com"
resp = _sign_and_request(
"GET", iam_host, "/v3/projects", [("name", region)],
{"Content-Type": "application/json"}, None, ak, sk,
)
if resp.status_code == 200:
projects = resp.json().get("projects", [])
if projects:
return projects[0]["id"]
raise RuntimeError(f"Failed to get project_id: {resp.status_code} {resp.text[:300]}")
def show_statistics(endpoint, project_id, ak, sk, body):
resource_path = f"/v1/{project_id}/maas/monitoring/show-statistics"
body_bytes = json.dumps(body).encode("utf-8")
resp = _sign_and_request(
"POST", endpoint, resource_path, [],
{"Content-Type": "application/json"}, body_bytes, ak, sk,
)
if resp.status_code == 200:
return resp.json()
raise RuntimeError(f"ShowStatistics failed: {resp.status_code} {resp.text[:500]}")
def fmt_tokens(val_k):
val_m = val_k / 1000
if val_m >= 1:
return f"{val_m:,.2f} M tokens"
return f"{val_k:,.2f} K tokens"
def main():
parser = argparse.ArgumentParser(description="MaaS usage statistics via ShowStatistics API")
parser.add_argument("--region", default="cn-southwest-2", help="Region (default: cn-southwest-2)")
parser.add_argument("--from", dest="from_date", required=True, help="Start date YYYY-MM-DD")
parser.add_argument("--to", dest="to_date", required=True, help="End date YYYY-MM-DD")
parser.add_argument("--service-type", type=int, default=2,
help="Service type: 1=My Service, 2=Preset Service(default), 4=Custom Endpoint")
parser.add_argument("--infer-type", default="real_time", help="Infer type: real_time(default), batch")
parser.add_argument("--api-keys", nargs="*", help="Filter by API Key list")
parser.add_argument("--raw", action="store_true", help="Show raw API response")
parser.add_argument("--credentials-file", help="Credentials file path (KEY=VALUE, CSV, or one-per-line)")
args = parser.parse_args()
ak = os.environ.get("HW_ACCESS_KEY", "")
sk = os.environ.get("HW_SECRET_KEY", "")
if (not ak or not sk) and args.credentials_file:
try:
with open(args.credentials_file, "r") as f:
lines = [l.strip() for l in f if l.strip() and not l.strip().startswith("#")]
for line in lines:
if "=" in line:
key, val = line.split("=", 1)
key, val = key.strip(), val.strip()
if key == "HW_ACCESS_KEY" and not ak:
ak = val
elif key == "HW_SECRET_KEY" and not sk:
sk = val
elif "," in line:
parts = [p.strip() for p in line.split(",")]
if not ak and len(parts) >= 1:
ak = parts[0]
if not sk and len(parts) >= 2:
sk = parts[1]
if not ak and len(lines) >= 1:
ak = lines[0]
if not sk and len(lines) >= 2:
sk = lines[1]
except FileNotFoundError:
print(f"Error: Credentials file not found: {args.credentials_file}", file=sys.stderr)
sys.exit(1)
if not ak or not sk:
print("Error: Credentials not found. Provide AK/SK via:", file=sys.stderr)
print(" 1. Environment variables: export HW_ACCESS_KEY=xxx && export HW_SECRET_KEY=xxx", file=sys.stderr)
print(" 2. Credentials file: --credentials-file <path>", file=sys.stderr)
sys.exit(1)
region = args.region
endpoint = f"modelarts.{region}.myhuaweicloud.com"
local_tz = datetime.now().astimezone().tzinfo
from_dt = datetime.strptime(args.from_date, "%Y-%m-%d").replace(tzinfo=local_tz)
to_dt = datetime.strptime(args.to_date, "%Y-%m-%d").replace(tzinfo=local_tz)
project_id = get_project_id(ak, sk, region)
svc_name = SERVICE_TYPE_MAP.get(args.service_type, str(args.service_type))
base_body = {
"service_type": args.service_type,
"timezone": _local_iana_tz(),
"infer_type": args.infer_type,
}
if args.api_keys is not None:
base_body["api_keys"] = args.api_keys
max_days = 29
delta_days = (to_dt - from_dt).days
segments = []
if delta_days <= max_days:
segments.append((from_dt, to_dt))
else:
cur = from_dt
while cur < to_dt:
seg_end = min(cur + timedelta(days=max_days), to_dt)
segments.append((cur, seg_end))
cur = seg_end
total_req = 0
total_err = 0
total_token = 0.0
prompt_token = 0.0
completion_token = 0.0
raw_responses = []
for seg_from, seg_to in segments:
body = dict(base_body)
body["start_time"] = int(seg_from.timestamp() * 1000)
body["end_time"] = int(seg_to.timestamp() * 1000)
data = show_statistics(endpoint, project_id, ak, sk, body)
total_req += data.get("total_request_count", 0)
total_err += data.get("total_error_count", 0)
total_token += data.get("total_token", 0)
prompt_token += data.get("total_prompt_token", 0)
completion_token += data.get("total_completion_token", 0)
if args.raw:
raw_responses.append({"segment": f"{seg_from.strftime('%Y-%m-%d')}~{seg_to.strftime('%Y-%m-%d')}", "data": data})
fail_rate = total_err / total_req * 100 if total_req > 0 else 0
tz_label = datetime.now().astimezone().strftime("%Z")
time_range = f"{from_dt.strftime('%Y-%m-%d 00:00:00')} ~ {to_dt.strftime('%Y-%m-%d 00:00:00')} ({tz_label})"
col1_w = 20
col2_w = 22
sep = f"+{'─'*col1_w}+{'─'*col2_w}+"
row_fmt = f"| {{:<{col1_w}}} | {{:<{col2_w}}} |"
print()
print(f"MaaS {svc_name} Usage Statistics - Region: {region}")
print(sep)
print(row_fmt.format("Metric", "Value"))
print(sep.replace("─", "═"))
print(row_fmt.format("Total Tokens", fmt_tokens(total_token)))
print(row_fmt.format("Prompt Tokens", fmt_tokens(prompt_token)))
print(row_fmt.format("Completion Tokens", fmt_tokens(completion_token)))
print(row_fmt.format("Total Requests", f"{total_req:,}"))
print(row_fmt.format("Total Errors", f"{total_err:,}"))
print(row_fmt.format("Error Rate", f"{fail_rate:.2f}%"))
print(sep)
print(f"Period: {time_range}")
if args.raw:
print(f"\nRaw API Response:")
print(json.dumps(raw_responses, indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()
Related skills
How it compares
Use instead of hand-rolled curl against MaaS usage APIs without the documented service_type and credential acceptance rules.
FAQ
Who is huawei-cloud-maas-tokens-usage for?
Developers running inference on Huawei Cloud MaaS who need agent-guided REST usage reporting with correct auth and date windows.
When should I use huawei-cloud-maas-tokens-usage?
In Operate when monitoring spend or usage trends; also when reconciling monthly bills or answering “how many tokens did we burn last 7 days?” before scaling or throttling.
Is huawei-cloud-maas-tokens-usage safe to install?
The skill explicitly forbids collecting AK/SK in conversation and hardcoding secrets; review the Security Audits panel on this page before trusting any third-party skill in production.