Reconcile NewAPI and Sub2API bills
English | 简体中文 · Documentation
Platform administrators open Platform management → Reconciliation (/reconciliation) to compare XHub accounting with a supplier's NewAPI or Sub2API usage logs. A run preserves the selected account, connections, period, recorded amounts and evidence. Reconciliation does not change charges, provider balances or deployment prices.
The result separates request matching, recorded-amount comparison, and usage/price-rule verification. Amounts equal does not certify all pricing dimensions or make a usage log a financial receipt.
Configure a billing source
First configure the XHub provider and model deployment using the customer guide. Select Add source in Reconciliation.
| Field | What to enter |
|---|---|
| Name | A recognizable label, such as Supplier A production |
| Platform | NewAPI or Sub2API |
| Billing backend URL | The backend origin, for example https://billing.example.invalid; this is separate from an inference URL ending in /v1 |
| Upstream account ID | The numeric ID of the account whose logs you are authorized to read |
| Upstream key IDs | Identifiers such as 8,9, not secret values. Empty means no key filter inside this account. |
| XHub suppliers | Existing connections that use this billing account |
| Billing timezone | An IANA timezone, such as Asia/Shanghai or UTC |
| Usage contract | A tested field version, only after confirming the deployment uses those semantics; otherwise keep Unknown / not verified |
Use one source for a billing account shared by several XHub connections, selecting all relevant connections. Separate accounts or installations need separate sources. Do not add totals from overlapping sources: the same charge can appear in both. Narrow key IDs when other applications share the account; an unmatched supplier record may belong to another application.
A run freezes its source mapping. Renaming a source or rotating its token preserves the scope. Changing the platform, address, account, key filters, supplier mapping, timezone or usage contract changes the scope: review it and save the daily plan again. An old-scope job cannot publish under the new scope. Deleting a source cancels its pending jobs and removes its schedule; saved runs remain historical evidence.
Authorize NewAPI or Sub2API
| Platform | Credential and interfaces |
|---|---|
| NewAPI | Use the same account's personal access token (PAT) with usage:read. The connector reads /api/status, /api/log/self and /api/log/self/export. An inference key is not a billing PAT. |
| Sub2API | Use the account's access JWT, optionally with its corresponding refresh token. The connector reads /api/v1/auth/me and /api/v1/usage; authorized renewal uses /api/v1/auth/refresh. An inference key is not an access JWT. |
Select Verify connection to check identity and interface capability. Stored tokens are encrypted and not returned by source lists or exports; XHub needs a configured master key. File-only sources may omit credentials but cannot synchronize until authorization is provided.
On a Sub2API 401, XHub can refresh once, save the rotated pair, then retry. Refreshing authorization is temporary; Reauthorization required needs new administrator-supplied authorization. Do not reuse a consumed refresh token. Leaving both fields blank preserves existing authorization when address/account are unchanged. Entering a new access token without a new refresh token clears the previous refresh token. Changing the backend or account also prevents reuse of old authorization.
Choose the usage contract conservatively
| Contract | Meaning and boundary |
|---|---|
unknown |
No field-semantics assertion. Amounts can still be compared when their unit is known; normalized usage remains unknown. |
newapi_04dfcbb7 |
Tested against NewAPI 04dfcbb7128982d78b63a2ecb15f6d20c7305f44. Claude requires explicit usage_semantic evidence; expression billing_tokens are not automatically disjoint raw usage. |
sub2api_f53641e5 |
Tested against Sub2API f53641e53c8da5efd959595c1eac696bdc0a3a57. Self-log input_tokens already excludes cache buckets; subtracting cache again undercounts input. |
A contract describes log fields, not every model supported by a gateway. Missing cache TTL, an unknown alias or absent semantic evidence remains unknown.
NewAPI other must be a valid JSON object (including an empty object). Missing, malformed or null evidence cannot mean “zero cache”; normalized usage and reference cost remain unknown. Under a confirmed OpenAI usage contract, total cache creation plus one explicit 30m or 12h bucket can determine the other bucket by conservation. Missing both buckets or inconsistent totals do not establish a TTL. This derivation applies only to the OpenAI two-bucket contract above; provided Anthropic 5m/1h buckets must still sum to total creation. Sub2API cache counters follow that version’s optional-zero semantics and are not required on every row.
Collect or import a period
Dates include both selected days in the source timezone. For example, 2026-12-01 to 2026-12-01 means that local calendar day. API callers may use RFC3339 timestamps with a half-open interval: start included, end excluded. The limit is 31 source-calendar days and 10,000 supplier records; exceeding it fails instead of silently truncating a successful result.
Sync and reconcile queues an asynchronous job. The page shows queued, running, retry-wait, succeeded, failed, needs-authorization or canceled status. Closing the page does not cancel it. Transient failures are attempted at most three times. A canceled or unsuccessful job does not publish a successful run. Resolve the cause, then use Retry this window.
Daily collection is disabled by default. Enable it explicitly, choose an hour from 0–23 and a lookback of 1–31 days, then save. It uses the source timezone and reviews complete days before the scheduled day, excluding that day. A lookback helps revisit late usage but does not prove all refunds or financial adjustments are exposed. Task metadata is retained for 90 days; this does not delete saved billing evidence. Editing a schedule while it remains enabled preserves already registered jobs, including in-flight collection. Explicitly disabling it cancels unfinished scheduled jobs; manual jobs and saved runs remain. Temporary queue conflicts retry after a persistent delay (1 minute, doubling up to 1 hour) without changing the original billing window. An invalid source scope or damaged schedule pauses collection; review the audit record, enable daily collection again, and save. Corrupt rows are retained and audited once by content digest while healthy sources continue.
Import a file
Select a JSON array, NDJSON or CSV file, inspect its fields, then Confirm import and reconcile. The limit is 10 MB / 10,000 records. Export XLSX to CSV first. Preserve account/key/request IDs, timestamps, models and original amount precision. Keep the source file separately: a run stores selected evidence and hashes, not a complete archival copy of the spreadsheet. File completeness is explicitly unverified.
For NewAPI, API collection reads current quota_per_unit; a historical import needs an explicit Quota per USD and verification that it applied then. This fictional CSV assumes 500000 quota per USD:
user_id,token_id,type,request_id,created_at,model_name,quota
42,8,2,example-request-001,2026-12-01T09:00:00+08:00,example-model,500The configured source must actually select account 42, key 8, the matching supplier and period. Missing amount or unit evidence is unknown, never zero. The workflow does not perform foreign-exchange conversion; do not relabel a non-USD amount as USD.
Management API example
Use a platform administrator's session token, not an inference key. These values are placeholders:
export XHUB_BASE="http://localhost:4000"
export XHUB_SESSION_TOKEN="YOUR_ADMIN_SESSION_TOKEN"
export SOURCE_ID="YOUR_SAVED_SOURCE_ID"
curl --fail-with-body "$XHUB_BASE/reconciliation/sources/$SOURCE_ID/jobs" \
-H "Authorization: Bearer $XHUB_SESSION_TOKEN" \
-H "Content-Type: application/json" \
-d '{"from":"2026-12-01","to":"2026-12-01"}'The response is 202 with a job ID. Read GET /reconciliation/jobs/{id} to terminal status, then GET /reconciliation/runs/{run_id} or its /export endpoint. File ingestion uses POST /reconciliation/sources/{id}/runs with from, to, records and, when needed, quota_per_unit. Source, job, run, export and resolution management require platform-administrator permission.
Browse historical runs
Run history loads 50 summaries at a time, newest first. Select Load more runs to see older batches. Opening a run or exporting it still returns its complete evidence. Switching sources starts a new history page; a cursor from another source is rejected.
GET /reconciliation/runs?source_id=SOURCE_ID&limit=50 returns data and, when more rows exist, next_cursor. Pass that cursor with the same source_id in the next request. The maximum limit is 100. Summaries omit findings and credentials; they preserve the run's frozen scope and totals without recalculation.
An upgrade creates a separate summary index in the same database. New runs and their summaries commit together. Existing evidence is projected in resumable batches without loading full historical findings into application memory. If initialization fails or its startup time budget expires, run lists and new reconciliation batches report a storage error, while inference and existing run details remain available. Check the server's reconciliation_storage log, resolve the database issue if present, and restart to resume from the saved position. Original evidence is retained.
Read amounts and evidence
| Value | Meaning |
|---|---|
| XHub booked amount | Actual local accounting and its historical price snapshot where available; reference calculations do not overwrite it |
| Supplier bill | NewAPI quota converted using the recorded unit, or Sub2API actual_cost. Sub2API total_cost is a separate base-cost reference and may differ due to a multiplier. |
| Difference | Supplier amount minus XHub amount; positive means the supplier amount is greater |
| Official reference | A separate versioned, conditional calculation, not a third paid invoice or a replacement for recorded amounts |
Totals include known in-scope amounts, including one-sided records; out-of-scope records are excluded. An unknown-amount count means the total is partial. Supplier amounts explicitly labeled with a non-USD currency remain in their original evidence and are excluded from the supplier USD total and paired difference. The corresponding known XHub USD charge remains visible and included. When the page reports incomparable currencies, do not subtract the two totals to derive the difference total. Equal totals can conceal offsetting row differences: inspect findings.
- Amounts equal (rules require verification): linked amounts agree; usage, pricing and completeness still need evidence.
- Difference: inspect the exact delta. NewAPI integer-quota rounding or an older floating-point ledger can explain tiny differences; no implicit tolerance hides them.
- Supplier record without a match / XHub record without a match: check key scope, IDs, timing and other applications before alleging missing accounting. Request start and provider completion can cross a period boundary; retry with an appropriate overlapping period.
- Ambiguous: duplicate or conflicting identities prevent safe one-to-one matching.
- Insufficient evidence / unknown: a missing amount or unsupported billing dimension is not free. An XHub snapshot marked unpriced is explained separately, even when its recorded amount is zero or the model has no official price profile.
Pricing analysis shows disjoint usage, cache TTLs, reasoning as part of output, reference components, local applied rates and difference decomposition. Reference sources, check dates and rule versions remain visible. reference_only is a conditional snapshot calculation; billed_reference_only uses quantities XHub charged, not independently measured provider usage. Missing historical effective dates, execution tier, region, holiday evidence and unsupported dimensions remain limitations. This is not certification of current official prices for every model.
Each side uses its own evidence: supplier estimates use its log timestamp and execution conditions; XHub estimates use the local pricing plan’s frozen timestamp and billing snapshot, falling back to the local ledger timestamp only for older records without a frozen clock. Matching the same request does not turn the supplier's settlement timestamp, service tier or holiday assertion into XHub execution evidence. Crossing a peak/off-peak boundary can produce different reference results. Conditions not independently recorded by XHub remain unknown.
A tariff contains text, batch or audio prices
Regular dialogue uses real-time token prices, even when the same tariff lists batch discounts. Soft billing may exclude an unused a_input quote only when the final outgoing Chat, Responses or Messages request is recognized as standard non-audio dialogue and measured usage contains no audio or video dimension. Image input is billed as a reported subset of input tokens; no separate image rate is invented. Unknown extensions, audio requests, measured audio and missing required dimensions remain unpriced. A zero recorded amount does not mean free usage.
ex_cache is charged once with ordinary cache only when their per-token USD rates are exactly equal and there are no time-window cache overrides or higher-priority input/cached prices. The frozen snapshot retains the original tariff and request facts. Strict budgets separately support verified equivalent aliases in raw catalog tiers. This fix extends manual rates only for soft billing; strict flat rates still conservatively reject that variant, and earlier bills remain unchanged.
An explicit zero audio/video count differs from null: zero establishes no usage in that dimension; null does not. Soft token billing leaves nonzero, null or malformed audio/video measurements unpriced instead of substituting a text rate.
Retries, caches and multiple suppliers
One client call can create multiple XHub outbound attempts, possibly switching connections or models. Match each attempt with its supplier and provider request ID. A dispatch marker proves entry into the send boundary, not provider acceptance or payment. An unconfirmed attempt keeps an unknown result.
An XHub local response-cache hit creates no outbound attempt or new supplier bill. A provider prompt-cache hit still calls upstream and may charge cache reads, writes and output. NewAPI or Sub2API may also retry internally: XHub records XHub → gateway attempts while self logs may expose only the final charge. A match cannot prove complete internal-attempt disclosure. Older XHub records may lack attempt evidence too.
Record decisions without rewriting history
For a finding, append a reason with Accept explained difference, Wait for supplier or Reopen review. History records the administrator, time and revision. A concurrent edit requires a refresh before resubmission. Original amounts, matching and evidence remain unchanged; accepting a difference does not make it equal or adjust a balance.
Export evidence and retain original supplier files where applicable. Exports contain selected billing evidence, not provider secrets or request/response bodies. Free-text decision reasons are review history: never paste credentials or private prompts. Changed facts create a new collection snapshot; an old decision is not automatic proof that a new revision is resolved.
Keep Modelink price maintenance separate
AI Model Marketplace → Deployment price updates uses Qiniu Modelink data and its own policy. Reconciliation sources read NewAPI or Sub2API billing evidence. Adding a source does not change the Modelink feed, enable price following or rewrite charges.
If a price or cache rule is wrong, preserve evidence, confirm the actual model and intended rate, then use deployment price management for future requests. Official execution conditions, supplier multipliers and quota rounding are separate explanations. See pricing behavior and usage and logs.