Repository navigation
Go: implement Balance in SiliconFlow driver - #14643
Conversation
The SiliconFlow Go driver shipped with a stub Balance method.
SiliconFlow exposes GET /v1/user/info that returns the account
balance per currency, so the "Balance" panel in the model
provider UI can work the same way it works for Moonshot and
Gitee.
Changes:
- conf/models/siliconflow.json: add "balance": "user/info" under
url_suffix so the driver builds the URL from config.
- internal/entity/models/siliconflow.go: replace the Balance
stub with a real implementation. Adds a small local response
type that matches the upstream shape.
How it works:
- Validate apiConfig and the API key, resolve the region with a
default fallback, and build the URL from BaseURL[region] +
URLSuffix.Balance.
- GET the URL with Authorization: Bearer <api_key>.
- Parse the response. SiliconFlow returns balance fields as
strings, so the driver parses them with strconv.ParseFloat.
Prefer totalBalance over balance when both are present.
- Return {"balance": <float>, "currency": "CNY"}, the same
shape the Moonshot driver returns.
Edge cases:
- Missing or empty API key returns a clear local error before
any HTTP call.
- An unknown region falls back to the default base URL.
- Empty balance and totalBalance returns a clear "no balance
info in response" error rather than a zero-value silent
success.
- Non-numeric balance string returns a clear parse error.
- Non-200 responses propagate the upstream status line and body.
Closes infiniflow#14642
|
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds ChangesSiliconFlow Balance Feature
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related issues
Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Hi @Magicbook1108, gentle ping for review. Same pattern as the Moonshot and Gitee Balance implementations, scope is two files (one config, one driver), and it closes #14642. Thanks! |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/entity/models/siliconflow.go (1)
587-598: ⚡ Quick winAPI-level error response is not checked —
parsed.Messageis silently discarded.When SiliconFlow returns HTTP 200 with
"status": false(e.g. for an invalid/expired key that passes basic format validation), the code skips straight to readingTotalBalance/Balance. Those fields will be empty, so the caller receives"no balance info in response"rather than the actual API error string inparsed.Message.🛡️ Proposed fix — check API-level status after unmarshal
var parsed siliconflowBalanceResponse if err = json.Unmarshal(body, &parsed); err != nil { return nil, fmt.Errorf("failed to parse response: %w", err) } + + if !parsed.Status { + msg := parsed.Message + if msg == "" { + msg = "unknown API error" + } + return nil, fmt.Errorf("SiliconFlow API error (code %d): %s", parsed.Code, msg) + } raw := parsed.Data.TotalBalance🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/siliconflow.go` around lines 587 - 598, After unmarshalling into siliconflowBalanceResponse, check the API-level status/message before reading Data: if parsed.Status (or parsed.Message/parsed.Success flag used by the response struct) indicates failure, return an error containing parsed.Message (the API error) instead of falling through to empty TotalBalance/Balance; update the logic around parsed (the variable) so the call site returns fmt.Errorf("siliconflow API error: %s", parsed.Message) when the response signals failure, and only then proceed to read parsed.Data.TotalBalance / parsed.Data.Balance.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/entity/models/siliconflow.go`:
- Around line 532-541: The siliconflowBalanceResponse struct currently declares
Status as a bool which causes json.Unmarshal to fail because SiliconFlow returns
status as a string; update the siliconflowBalanceResponse definition to change
the field Status from bool to string (i.e., the Status field in the
siliconflowBalanceResponse struct) so the JSON (e.g., "normal") can be parsed
correctly and the API response error becomes visible.
---
Nitpick comments:
In `@internal/entity/models/siliconflow.go`:
- Around line 587-598: After unmarshalling into siliconflowBalanceResponse,
check the API-level status/message before reading Data: if parsed.Status (or
parsed.Message/parsed.Success flag used by the response struct) indicates
failure, return an error containing parsed.Message (the API error) instead of
falling through to empty TotalBalance/Balance; update the logic around parsed
(the variable) so the call site returns fmt.Errorf("siliconflow API error: %s",
parsed.Message) when the response signals failure, and only then proceed to read
parsed.Data.TotalBalance / parsed.Data.Balance.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 2ce38c22-d3c9-4a81-84cc-65aa36b98ffc
📒 Files selected for processing (2)
conf/models/siliconflow.jsoninternal/entity/models/siliconflow.go
CodeRabbit web-checked the SiliconFlow /v1/user/info schema and flagged that the top-level status field is a string, not a bool. Decoding into a bool field fails the whole unmarshal and the caller sees a generic "failed to parse response" error instead of the real API error. This commit changes Status from bool to string and adds an API-level check after the unmarshal: when code is not 20000 the driver returns a clear error built from parsed.Message instead of falling through to an empty TotalBalance/Balance.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14643 +/- ##
=======================================
Coverage 94.16% 94.16%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 662 662
Misses 25 25
Partials 16 16 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
| type siliconflowBalanceResponse struct { | ||
| Code int `json:"code"` | ||
| Status string `json:"status"` | ||
| Message string `json:"message"` | ||
| Data struct { | ||
| Balance string `json:"balance"` | ||
| TotalBalance string `json:"totalBalance"` | ||
| Status string `json:"status"` | ||
| } `json:"data"` | ||
| } | ||
|
|
There was a problem hiding this comment.
According to
{
"code": 20000,
"message": "OK",
"status": true,
"data": {
"balance": "0.88",
"chargeBalance": "88.00",
"totalBalance": "88.88"
}
}status is a bool
your code:
type siliconflowBalanceResponse struct {
Status string `json:"status"`
}There was a problem hiding this comment.
Hi @Haruko386, thanks so much for testing this against the live endpoint and catching it! Fixed in commit 5500eba, status is back to bool and the API-level check now uses !parsed.Status.
Haruko386
left a comment
There was a problem hiding this comment.
Hi @pandadev66 ,
I found an issue in the SiliconFlow balance response parsing logic.
The /v1/user/info endpoint is working correctly and returns a response like:
{
"code": 20000,
"message": "OK",
"status": true,
"data": {
"balance": "0.88"
}
}However, the current implementation defines the status field as a string, while the actual API response returns a boolean value.
This causes the following error during JSON unmarshalling:
json: cannot unmarshal bool into Go struct field siliconflowBalanceResponse.status of type string
The struct field should be updated from:
Status string `json:"status"`to:
Status bool `json:"status"`After this change, the balance endpoint should work correctly.
The earlier change made the top-level status field a string based on a docs lookup, but @Haruko386 tested against the live /v1/user/info endpoint and confirmed the API actually returns status as a boolean. Decoding into a string field now fails the whole unmarshal with: json: cannot unmarshal bool into Go struct field siliconflowBalanceResponse.status of type string Change Status back to bool. The API-level error check now uses !parsed.Status, which is the natural read of the boolean flag. The unused nested Status field on Data is removed since it is not needed by this code path.
### What problem does this PR solve?
The SiliconFlow Go driver shipped with a stub \`Balance\` method that
returned \`no such method\`, even though SiliconFlow exposes a public
\`GET /v1/user/info\` endpoint that returns the account balance per
currency.
So the "Balance" panel in the model provider UI always shows an error
for SiliconFlow tenants, while it already works for
Moonshot and Gitee. This PR fills the gap.
### What this PR includes
- \`conf/models/siliconflow.json\`: add \`\"balance\": \"user/info\"\`
under \`url_suffix\` so the driver builds the URL from config.
- \`internal/entity/models/siliconflow.go\`: replace the \`Balance\`
stub with a real implementation. Adds a small local response type that
matches the upstream shape.
No factory change. No interface change.
### How the driver works
- Validate \`apiConfig\` and the API key, resolve the region with a
default fallback, and build the URL from \`BaseURL[region] +
URLSuffix.Balance\`.
- GET the URL with \`Authorization: Bearer <api_key>\`.
- Parse the upstream response. SiliconFlow returns balance fields as
strings, so the driver parses them with \`strconv.ParseFloat\`. It
prefers \`totalBalance\` over \`balance\` when both are present.
- Return \`{\"balance\": <float>, \"currency\": \"CNY\"}\`, the same
shape the Moonshot driver returns. The UI can render it
with no provider-specific code.
### Edge cases
- Missing or empty API key returns a clear local error before any HTTP
call.
- An unknown region falls back to the default base URL.
- Empty \`balance\` and \`totalBalance\` returns a clear "no balance
info in response" error rather than a zero-value silent success.
- Non-numeric balance string returns a clear parse error.
- Non-200 responses propagate the upstream status line and body.
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
### How was this tested?
- \`go build ./internal/entity/models/...\` in a clean go 1.25 image
returns exit 0.
- The full method set on \`SiliconflowModel\` still matches the
\`ModelDriver\` interface.
- Pattern parity with the existing Moonshot and Gitee Balance
implementations.
Closes infiniflow#14642
Replace the "no such method" stub in OpenAIModel.Balance with a real
implementation against the Organization Costs endpoint
(GET /v1/organization/costs), authenticated by an admin API key
(sk-admin-...). The result follows the {balance, currency} contract
already used by DeepSeek (infiniflow#14632) and SiliconFlow (infiniflow#14643) so the CLI
surface from infiniflow#14262 can render it without provider-specific code.
The legacy /v1/dashboard/billing/* endpoints are intentionally not
used: they are deprecated and reject project API keys with 401. Admin
keys are required by OpenAI to call /v1/organization/*, so the driver
fails fast with a clear error when a non-admin key is supplied.
Semantic caveat documented in code: peer drivers' Balance() returns
*remaining* spendable amount, but this driver returns *already-spent*
costs because OpenAI exposes no remaining-balance endpoint to API
callers. /v1/dashboard/billing/credit_grants is browser-session-only
and rejects API keys with 403, confirmed in review by Haruko386. The
Balance() doc comment records this explicitly so future contributors
do not re-attempt that path; switch to a remaining-balance endpoint
when OpenAI ships one.
Fixes infiniflow#14874
Replace the "no such method" stub in OpenAIModel.Balance with a real
implementation against the Organization Costs endpoint
(GET /v1/organization/costs), authenticated by an admin API key
(sk-admin-...). The legacy /v1/dashboard/billing/* endpoints are
intentionally not used: the documented /organization/* surface
requires admin keys, and the legacy /dashboard/billing/credit_grants
path is browser-session-only and rejects API keys with 403
(reproduced in review by Haruko386).
Return shape: {spend, currency} — deliberately diverges from the
{balance, currency} shape used by the DeepSeek (infiniflow#14632) and
SiliconFlow (infiniflow#14643) drivers. OpenAI exposes no remaining-balance
API to API callers, so labeling month-to-date spend as "balance"
would conflate opposite quantities (remaining vs consumed) under one
field name and silently mislead users. Raised in review on infiniflow#14876
by coderabbitai; the doc comment on Balance() records the rationale
and a forward path: emit "balance" alongside or instead of "spend"
once OpenAI ships a documented remaining-balance endpoint.
Fixes infiniflow#14874
### What problem does this PR solve?
The SiliconFlow Go driver shipped with a stub \`Balance\` method that
returned \`no such method\`, even though SiliconFlow exposes a public
\`GET /v1/user/info\` endpoint that returns the account balance per
currency.
So the "Balance" panel in the model provider UI always shows an error
for SiliconFlow tenants, while it already works for
Moonshot and Gitee. This PR fills the gap.
### What this PR includes
- \`conf/models/siliconflow.json\`: add \`\"balance\": \"user/info\"\`
under \`url_suffix\` so the driver builds the URL from config.
- \`internal/entity/models/siliconflow.go\`: replace the \`Balance\`
stub with a real implementation. Adds a small local response type that
matches the upstream shape.
No factory change. No interface change.
### How the driver works
- Validate \`apiConfig\` and the API key, resolve the region with a
default fallback, and build the URL from \`BaseURL[region] +
URLSuffix.Balance\`.
- GET the URL with \`Authorization: Bearer <api_key>\`.
- Parse the upstream response. SiliconFlow returns balance fields as
strings, so the driver parses them with \`strconv.ParseFloat\`. It
prefers \`totalBalance\` over \`balance\` when both are present.
- Return \`{\"balance\": <float>, \"currency\": \"CNY\"}\`, the same
shape the Moonshot driver returns. The UI can render it
with no provider-specific code.
### Edge cases
- Missing or empty API key returns a clear local error before any HTTP
call.
- An unknown region falls back to the default base URL.
- Empty \`balance\` and \`totalBalance\` returns a clear "no balance
info in response" error rather than a zero-value silent success.
- Non-numeric balance string returns a clear parse error.
- Non-200 responses propagate the upstream status line and body.
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
### How was this tested?
- \`go build ./internal/entity/models/...\` in a clean go 1.25 image
returns exit 0.
- The full method set on \`SiliconflowModel\` still matches the
\`ModelDriver\` interface.
- Pattern parity with the existing Moonshot and Gitee Balance
implementations.
Closes infiniflow#14642
What problem does this PR solve?
The SiliconFlow Go driver shipped with a stub `Balance` method that returned `no such method`, even though SiliconFlow exposes a public `GET /v1/user/info` endpoint that returns the account balance per currency.
So the "Balance" panel in the model provider UI always shows an error for SiliconFlow tenants, while it already works for
Moonshot and Gitee. This PR fills the gap.
What this PR includes
No factory change. No interface change.
How the driver works
with no provider-specific code.
Edge cases
Type of change
How was this tested?
Closes #14642