When batch-running tasks with Hy4 Flash, how do I verify charged requests from usage records?

Summary: When Hy4 Flash runs tasks in bulk, how do you reconcile each online request your application fires off concurrently against the vendor’s usage records and billed amounts, line by line?

Bottom line: Every business task, every network attempt, and every vendor record needs an identifier you can use to link them together. Your application decides whether to retry based on the task, and does reconciliation based on the attempt. On APIYI apiyi.com, you use the X-Shellapi-Request-Id response header to match the request_id in the consumption log, then check each charge against quota. On Tencent Cloud TokenHub International, you use the client-side receipt to explain usage, and confirm the amount against the resource bill in the Billing Center.

There are three separate things to judge: whether the request reached you, whether the server generated content, and whether the account was settled. These three outcomes are independent — none of them can stand in for the other two. This article only covers online invocations dispatched from your application’s queue. Within the scope of this article, Hy4 Flash does not use Tencent Cloud’s offline batch processing; when we say “batch,” we mean the many online requests your program fires off concurrently.

The information in this article was verified on 2026-11-30. Prices come from APIYI’s public price list and Tencent Cloud’s official pricing page. The worked examples and records are synthetic cases meant to illustrate the accounting method — this article did not run live tests.

hy4-flash-batch-usage-billing-reconciliation-en-image-0

Knowledge Map: The Six Stages of Hy4 Flash Batch Reconciliation

hy4-flash-batch-usage-billing-reconciliation-en-image-1

Figure caption (alt text): This is a vertical flow diagram. Section 1 pins down the price basis, then Section 2 registers an attempt number for every request. Next, the flow splits by entry point: APIYI takes the Section 3 path, matching usage logs exactly by request ID — when no ID is available, it narrows the range using conditions like the time window, and if the candidates aren’t unique, the amount is recorded as not uniquely attributable. TokenHub International takes the Section 4 path, aggregating usage by API key and pulling the amount from resource bills. The two paths merge in Section 5 for a two-way check, and Section 6 outputs a traceable batch report. Before retrying, you need to go back to the usage records to confirm whether the previous attempt was already billed.

Index: What Order to Read the Hy4 Flash Reconciliation Steps In

Section 1 decides “which price list to calculate with,” and it’s the prerequisite for every amount comparison that follows. Section 2 leaves evidence behind at the moment you send the request—without that layer, Sections 3 and 4 can only do fuzzy matching. Sections 3 and 4 are two parallel paths, so if you only use one of the entry points, you can just read the matching section. Section 5 combines all the earlier evidence into file-level verification, and Section 6 gives you the acceptance criteria for the batch report. Once you’ve read it all, you should be able to trace any aggregated amount back to a specific attempt, and trace the final output back to the request that was actually adopted.

To Know: Terminology Involved in Hy4 Flash Reconciliation

Term Plain Explanation
Business task The one thing you need to get done, like “write a summary for item #128″—it may take multiple requests
Attempt A single outbound network request made to complete the task; a retry creates a new attempt
X-Shellapi-Request-Id The request identifier APIYI returns in the response header, matching request_id in the usage log
quota The quota unit in the APIYI usage log; quota ÷ 500000 gives you back the dollar amount
Pre-deduction The quota check before execution—if the balance is too low, the request is blocked before it runs
Cached-read tokens The portion of the input that hits the cache, priced separately
Resource bill The actual charge breakdown in the Tencent Cloud Billing Center filtered by product, already including discounts, vouchers, and other offsets

1 Lock Down the Pricing Basis Before Running Hy4 Flash Batch Jobs

1.1 The Three Entry Points Use Different Definitions

They’re all called Hy4 Flash, but different entry points don’t share the same pricing, metering, or billing aggregation. Before reconciling anything, write down which entry point this batch of jobs goes through and which day’s price snapshot it’s based on.

Item APIYI (platform price list) Tencent Cloud TokenHub International (first-party) Tencent Cloud China site batch inference (first-party)
Model name hy4-flash, chat type hy4-flash Supported list includes hy4, hy4-preview, hy3; Flash is not listed
Endpoint /v1/chat/completions Singapore domain tokenhub-intl.tencentcloudmaas.com/v1/chat/completions; other regions have their own access domains POST /v1/batches offline service
Input/output/cache read (USD per million tokens) 0.04 / 0.14 / 0.0014 0.070 / 0.281 / 0.003 Out of scope for this article
Group or discount Groups Default and SVIP; the console consumption column includes the group multiplier Inference fee 50% off window through Nov 30, 12:00 Beijing time (04:00 UTC) —
Used in this article Yes Yes No, listed only to distinguish it

APIYI’s price snapshot comes from the public master table dated 2026-11-30 11:14 (UTC+8). The console consumption column already includes the group multiplier. Top-up bonuses belong to a separate accounting layer, so don’t mix them with per-transaction charges. It’s a good idea to save the group, price snapshot, and currency on the day you launch the job.

1.2 Hy4 Flash Jobs That Span a Discount Window Must Be Split by Actual Time of Occurrence

The first-party 50% discount applies to usage that actually occurs inside the window, and the list price returns once the window closes. If a batch of jobs crosses the cutoff, you can’t apply the discount uniformly based on when the batch was created—that throws off the reconciliation. The right approach is to check billing attribution against the actual time of each attempt.

1.3 Don’t Treat Concurrent Online Requests as Offline Batch Processing

The China site’s /v1/batches is a separate service: each input line’s custom_id is unique within the file, and the outer id points to the whole job. In billing, online service and batch inference resources are also aggregated separately. No matter how many concurrent requests you open in the client, each request is still an independent online attempt, and it should be recorded as an attempt.

2 How to Record Every Attempt During Batch Calls to Hy4 Flash

2.1 Keep Business Records and Attempt Records in Separate Tables

Business records answer “did this get done?” Attempt records answer “how many requests did it take, and what was the result of each one?” Retries should get a new attempt ID and be linked through the same task ID.

Table Logged before sending the request Logged after receiving the response
Business record Batch, task ID, input summary hash Output validation result, attempt ID finally accepted
Attempt record Attempt ID, provider, region, actual domain, model, endpoint, group, key label, send time Request ID, response body result id, HTTP status, finish reason, response end time, summary of raw usage

If SDK automatic retries are enabled, you need to mark every attempt at the observable network layer. A more direct approach is to disable SDK retries and let the application control them. On a network failure, if response headers haven’t been read yet, leave the request ID column blank, but keep the exact time window and error source. Don’t write the raw key into logs—only record a redacted key label.

2.2 Handling Usage Fields and Streaming Disconnects

TokenHub Chat non-streaming responses return usage.prompt_tokens, completion_tokens, and total_tokens; the example also breaks these down into prompt_tokens_details.cached_tokens and completion_tokens_details.reasoning_tokens. For streaming calls, set stream: true and stream_options.include_usage: true; the full usage is returned in the final stats block.

When the client disconnects early, a missing final block only means the local side didn’t receive the metering data. The provider’s billing documentation states that whether the interruption is initiated by the client or happens on the server side, tokens that the server has already generated but hasn’t fully output are still billed. So you can’t treat “no usage received” as “no charge.” Save error.request_id from error responses and id from successful results in separate fields, and note where each came from.

3 Confirm Hy4 Flash Billed Requests with APIYI Consumption Records

3.1 Quick Start: Get the Request ID

For non-streaming calls, the OpenAI Python SDK lets you read the raw response headers with with_raw_response.create. The minimal example below turns off automatic SDK retries so that every attempt gets registered by your application.

import openai

client = openai.OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.apiyi.com/v1",  # Use the APIYI unified endpoint
    max_retries=0,  # Let the application register each attempt itself
)

raw = client.chat.completions.with_raw_response.create(
    model="hy4-flash",
    messages=[{"role": "user", "content": "用一句话总结这段商品描述"}],
)
request_id = raw.headers.get("X-Shellapi-Request-Id")  # Corresponds to request_id in the logs
completion = raw.parse()
print(request_id, completion.id, completion.usage)

When a request fails, you can also grab the same value from the end of the error message. The result id in the response body, the X-Request-Id returned upstream, and this string are different fields, each stored separately — don’t overwrite one with another.

🚀 Quick Start: Start by running a few hy4-flash requests on APIYI apiyi.com using your new-user free trial quota. Confirm you can read X-Shellapi-Request-Id and find the matching row in the console’s consumption logs before wiring it into a batch queue.

3.2 Pulling Consumption Records with the Log Query API

The public endpoint for fetching invocation records is GET /api/log/self on the APIYI main site, and the credential is a personal access token with the “Usage & Personal Records · Read” permission. The query parameters set type=2, model_name=hy4-flash, start_timestamp, and end_timestamp; add request_id as well when you’re investigating a single failure.

Time windows are sliced in Unix seconds, pagination starts at p=0, and pageSize caps out at 5000. I’d recommend paging serially by hour or by day, keeping a reasonable overlap with the previous window. Deduplicate by account and request ID, and only advance the watermark once the entire window has been written to the database successfully.

View the complete fetch and matching code
import json
import time
from decimal import Decimal
import requests

BASE = "https://api.apiyi.com"
LOG_URL = f"{BASE}/api/log/self"
PAT = "YOUR_PERSONAL_ACCESS_TOKEN"  # must have the "Usage & Personal Records · Read" permission
PAGE_SIZE = 5000                    # documented maximum
OVERLAP = 300                       # overlap the previous window by 5 minutes

def fetch_window(start_ts: int, end_ts: int, account: str) -> dict:
    """Serially page through one time window, returning records deduplicated by (account, request_id)"""
    rows, page = {}, 0
    while True:
        resp = requests.get(
            LOG_URL,
            # the exact auth header format follows the APIYI log-query docs
            headers={"Authorization": f"Bearer {PAT}"},
            params={
                "type": 2,
                "model_name": "hy4-flash",
                "start_timestamp": start_ts,
                "end_timestamp": end_ts,
                "p": page,
                "pageSize": PAGE_SIZE,
            },
            timeout=60,
        )
        resp.raise_for_status()
        # where the list sits in the response body follows the docs; here we assume the data field
        items = resp.json().get("data") or []
        for it in items:
            other = it.get("other")
            if isinstance(other, str) and other:
                other = json.loads(other)  # decode first, then pull request_path, usage, multipliers, and so on
            key = (account, it.get("request_id"))
            rows[key] = {
                "request_id": it.get("request_id"),
                "model_name": it.get("model_name"),
                "token_name": it.get("token_name"),
                "token_group": it.get("token_group"),
                "created_at": it.get("created_at"),
                "prompt_tokens": it.get("prompt_tokens"),
                "completion_tokens": it.get("completion_tokens"),
                "error_code": it.get("error_code"),
                "quota": int(it.get("quota") or 0),
                "other": other,
            }
        if len(items) < PAGE_SIZE:
            return rows
        page += 1

def quota_to_usd(quota: int) -> Decimal:
    """Convert integer quota back to a USD amount; round consistently by finance rules after aggregation"""
    return Decimal(quota) / Decimal(500000)

def match_attempts(attempts: list, logs: dict, account: str):
    """Left-join the attempt list onto the consumption list: exact match when an ID exists, otherwise leave it for manual narrowing"""
    matched, pending = [], []
    for a in attempts:
        rid = a.get("request_id")
        row = logs.get((account, rid)) if rid else None
        if row:
            matched.append((a["attempt_id"], rid, quota_to_usd(row["quota"])))
        else:
            pending.append(a)  # narrow further by key label, time window, model, endpoint, usage
    return matched, pending

if __name__ == "__main__":
    end = int(time.time())
    start = end - 3600 - OVERLAP
    logs = fetch_window(start, end, account="acct-main")
    print(len(logs), "条消费记录已去重")

3.3 Reading Consumption Records and Attempts Without IDs

Convert amounts back to USD with quota ÷ 500000. The details store model_name, token_name, token_group, created_at, prompt_tokens, completion_tokens, and error_code. The other field gets decoded into JSON first, and then you pull the actual request_path, usage, multiplier, and billing type that were provided. Compare the client send time, log timestamp, and account-export timezone on the same basis—get the timezone off by one notch and the whole batch shifts.

For attempts without a request ID, narrow things down first using the key label, the same time window, the model, the endpoint, and usage. If multiple candidates still remain inside that window, keep it as an “amount that couldn’t be uniquely attributed”—don’t force-assign it to some attempt just to make the report look good.

3.4 Check Consumption Records Before Retrying

The console consumption log records requests that were successfully billed. A pre-authorization hold is just a quota check before execution; returning insufficient_user_quota means the request was blocked before it ever ran. APIYI’s documentation confirms that non-streaming long responses can hit a “server finished billing but the client never received the result” situation, so after a timeout, verify the consumption record first before deciding whether to retry. HTTP status codes and balance snapshots are only part of the evidence—you have to look at them together with the time window, timezone, and account filters.

🎯 Technical tip: In batch queues, it’s best to change “auto-retry on timeout” to “timeout → check logs → then decide.” In the APIYI apiyi.com console, browsing by model and time, or ticking the request ID field when exporting, both let you quickly confirm whether the last attempt was already charged.

4 Verifying Hy4 Flash charges on TokenHub International

4.1 Usage stats and resource bills each cover one piece

TokenHub’s Usage Statistics can aggregate by online service, model, and API key. The total input volume includes cache hits. To get the actual amount, go to the Billing Center → Bill Details → Resource Bills and filter by TokenHub. Discounts, vouchers, and plan credits are already factored in there. Postpaid cost allocation supports daily and monthly views by API key ID, and bill allocation data is T+1.

hy4-flash-batch-usage-billing-reconciliation-en-image-2

The figure above compares the granularity of the two reconciliation paths. If you want to check Hy4 Flash and other models request by request in a single console, you can connect through APIYI apiyi.com and compare afterward.

4.2 Isolate batches with separate keys

Because the provider’s amounts are only itemized down to API key and time dimension, the best way to control batches is to use a separate key or an attributable resource, then compare client-side aggregate usage with platform aggregate in the same time bucket. Resource bills handle amount aggregation; individual receipts handle usage estimation. Their precision differs, so the precision of your conclusions should match the granularity of the bill you’re using. Once you have enough evidence, you can hand the abnormal requests and their identifiers to the provider for investigation.

Evidence APIYI TokenHub International
Per-request identifier X-Shellapi-Request-Id ↔ log request_id result id, error error.request_id
Usage source log prompt_tokens, completion_tokens, other.usage receipt usage, usage statistics
Amount source quota ÷ 500000 (group multiplier already included) resource bill (including discounts, vouchers, plan credits)
Finest amount granularity per request by API key daily/monthly, T+1

5 File-Level Reconciliation for Hy4 Flash Batch Jobs

5.1 A Two-Way Left Join Between the Two Lists

Collection files and accounting results are stored separately. The first list records the tasks in a dispatch batch plus every attempt made on them; the second list holds the platform’s raw consumption records and the price validity intervals. Start by left-joining the attempt list to find receipts — that surfaces attempts for which no receipt ever arrived. Then reverse the direction and look up the owning task for each consumption record — that surfaces client retries that were never logged, other tasks sharing the same key, or duplicate imports.

If the platform rolls several attempts into a single day, also check whether that resource carried any traffic outside the batch queue on that day. For shared resources, estimate the batch’s share from its usage; report the resource’s actual amount and the allocated result in separate columns rather than merging them into a single number.

5.2 Which Metadata to Record When Freezing a Batch

When freezing the batch summary, spell out the metering time bucket, the account and region scope, the price version, the time the reconciliation data was read, and the fingerprint of the original export file. When exports overlap, merge them on the platform row key before computing; if late entries or adjustments turn up, append the corrective basis under the same batch. Do the arithmetic in integer units or decimal amounts, sum in stages, then round once at the end following finance convention. Dispute tickets should carry only the fields needed to locate the record: request identifier, masked key label, model, endpoint, send time with time zone, client-side terminal status, and billing row.

5.3 A Synthetic Reconciliation Example (Theoretical, Not Measured)

The records below are synthetic data constructed to illustrate the method. They are not a real bill, and nothing was actually executed.

Task Attempt Client result Consumption log Delivered
A A-1 Timeout 347 units No
A A-2 Completed and passed validation 140 units Yes (adopted)
B B-1 Blocked by pre-authorization check No consumption row No
C C-1 Completed 50 units Yes
D Not sent Cancelled — No

The dispatch table has four business tasks and four submission attempts, with B rejected at the vendor’s entry point. Three charges were billed, totaling (347+140+50)/500000 = 0.001074 USD in credits, with two deliverables. A’s first attempt timed out but still counts toward the billed total, while only A’s second, validated output is adopted.

Now let’s verify how 347 units derives from usage. Assume that attempt had 20,000 total input tokens, of which 10,000 were cache reads, and 2,000 total output tokens, at APIYI’s published base price with a multiplier of one: (10000×0.04 + 10000×0.0014 + 2000×0.14) / 1000000 = 0.000694 USD, which multiplied by 500000 gives exactly 347 units. Note that cache reads must be subtracted from the input total and billed separately, and reasoning tokens are already included in the output total, so count them only once. Actual amounts always follow the settlement records.

6 Acceptance Method for Hy4 Flash Batch Reconciliation

The batch report must show at least the following numbers, and each number must be traceable back to individual evidence items:

  • Planned count, attempted-send count, delivered count
  • Matched billing entries, matched quota and amount
  • Count and amount that cannot be uniquely attributed

When discrepancies arise, investigate in this order: unmatched attempts, rate basis, account grouping, caching, and cross-billing windows. There’s only one acceptance standard: you can trace from the summary back to every piece of reconciliation evidence, from the final artifact back to the adopted attempts, and every retry row with confirmed billing stays in the report.

💰 Cost optimization: When batch tasks are cost-sensitive, you can call hy4-flash on a pay-as-you-go basis through APIYI apiyi.com, and pair it with the per-item log verification described in this article to keep “duplicate charges caused by retries” within a visible range.

FAQ

Q1: Why distinguish between tasks and attempts when running Hy4 Flash batch jobs?

Because billing happens at the attempt layer, while delivery judgment happens at the task layer. A task retried three times may be billed three times but delivered only once. If you only record tasks, you can’t explain the extra consumption rows.

Q2: The client timed out — is this Hy4 Flash request still billed?

You can’t judge based on timeout alone. APIYI documentation confirms that non-streaming long responses may already be billed without being delivered, and the original vendor also states that tokens already generated at interruption time are billed. First go to APIYI apiyi.com consumption logs to query by request ID or time window, then decide whether to retry.

Q3: Can Hy4 Flash use Tencent Cloud /v1/batches offline batch processing?

According to the materials, the batch inference support table for the China site lists `hy4`, `hy4-preview`, and `hy3` — Flash is not listed. This article’s scope is online `hy4-flash`, and client-side concurrency is still reconciled as independent online requests.

Q4: Do requests that fail pre-authorization show up in the consumption logs?

They won’t form consumption rows. `insufficient_user_quota` means pre-authorization validation blocked the request before execution. Task B in the synthetic example is exactly this case — it counts as an attempted send, but not as a billing entry.

Q5: How do I quickly start per-item reconciliation for Hy4 Flash?

Register at APIYI apiyi.com and get an API key and free test quota. Use the code in Section 3.1 to read `X-Shellapi-Request-Id`, then create a personal access token with read permissions, and pull logs page by page as described in Section 3.2.

Q6: What are the limitations of this method?

Attempts without a request ID can only be narrowed down by time window; with multiple candidates, they can only be recorded as unattributed amounts. TokenHub amounts are granular at most by key/day/month and have a T+1 delay, so they can’t be precise to the cent per item. Traffic sharing a key can only be estimated and apportioned by usage.

📚 References

  1. APIYI Documentation Center: complete price list, log billing explanations, request ID troubleshooting, log timezones and exports, log query API, pre-deduction mechanism, billed but no response received

    • Link: docs.apiyi.com
    • Note: The source for APIYI-side fields, interfaces, and billing conventions in this article, verified on 2026-11-30
  2. Tencent Cloud TokenHub access domains and pricing: official international site domains and Hy4 Flash prices

    • Link: tencentcloud.com/document/product/1300/78941, tencentcloud.com/document/product/1300/78937
    • Note: Includes the 50%-off window deadline; page updated on 2026-11-27
  3. Tencent Cloud Hy API Guide and billing methods: usage fields, streaming statistics blocks, interruption billing

    • Link: tencentcloud.com/document/product/1300/80695, tencentcloud.com/document/product/1300/78936
    • Note: Explains the usage breakdown and the billing rules after a connection drops
  4. Tencent Cloud usage statistics and bill allocation: aggregation by Key and T+1 allocation

    • Link: tencentcloud.com/document/product/1300/78947, tencentcloud.com/document/product/1300/81194
    • Note: The basis for reconciling amounts on the international site
  5. Tencent Cloud China site batch inference: the offline /v1/batches service

    • Link: cloud.tencent.com/document/product/1823/130849
    • Note: Used to distinguish offline batch processing from the online concurrent calls discussed in this article

Author: APIYI Technical Team
Technical Inquiries: Feel free to reach out to us via the APIYI website homepage. For more log and billing resources, visit the docs.apiyi.com documentation center.

Leave a Comment