Skip to content

Go: implement Balance in SiliconFlow driver - #14643

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
pandadev66:feat/go-siliconflow-balance
May 8, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
pandadev66:feat/go-siliconflow-balance

Conversation

@pandadev66

@pandadev66 pandadev66 commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

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": , "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

  • 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 #14642

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
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label May 7, 2026
@coderabbitai

coderabbitai Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack
No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c7da1ce3-8c55-4fdd-b256-0687e2167ee5

📥 Commits

Reviewing files that changed from the base of the PR and between 3a5005d and 5500eba.

📒 Files selected for processing (1)
  • internal/entity/models/siliconflow.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/entity/models/siliconflow.go

📝 Walkthrough

Walkthrough

Adds balance and rerank URL suffixes to SiliconFlow config and implements SiliconflowModel.Balance to call the configured /user/info endpoint, parse the JSON response, convert the balance to float64, and return {"balance": , "currency":"CNY"}.

Changes

SiliconFlow Balance Feature

Layer / File(s) Summary
Configuration and Endpoint URLs
conf/models/siliconflow.json
Adds url_suffix entries for rerank (→ rerank) and balance (→ user/info).
Imports for Parsing
internal/entity/models/siliconflow.go
Adds strconv import to parse balance strings to float64.
Balance Response Schema
internal/entity/models/siliconflow.go
Adds siliconflowBalanceResponse struct describing top-level code/status/message and data.totalBalance/data.balance fields.
Balance Method Implementation
internal/entity/models/siliconflow.go
Implements (*SiliconflowModel).Balance(apiConfig *APIConfig) to validate apiConfig, resolve base URL, GET the endpoint built from URLSuffix.Balance, unmarshal JSON, verify success, extract totalBalance (fallback balance), parse to float64, and return {"balance": <float>, "currency":"CNY"}.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

  • #14642: Feature Request to implement Balance in the SiliconFlow Go driver — the PR implements that requested behavior.

Possibly related PRs

Suggested labels

size:L

Poem

🐰 I hopped from config to code with care,
A bearer token led me there,
JSON twitched—strconv took a bite,
Now balances gleam in morning light,
SiliconFlow's credits shown just right.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: implementing the Balance method in the SiliconFlow Go driver.
Description check ✅ Passed The description covers the problem being solved, the specific changes made, implementation details, edge cases, and includes the required type-of-change checkbox selection.
Linked Issues check ✅ Passed All requirements from issue #14642 are met: Balance method implemented with proper parsing, url_suffix config updated, proper authentication and response handling, and correct return type.
Out of Scope Changes check ✅ Passed Changes are limited to implementing Balance in siliconflow.go and adding balance config in siliconflow.json, directly addressing the linked issue with no extraneous modifications.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pandadev66

Copy link
Copy Markdown
Contributor Author

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!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
internal/entity/models/siliconflow.go (1)

587-598: ⚡ Quick win

API-level error response is not checked — parsed.Message is 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 reading TotalBalance/Balance. Those fields will be empty, so the caller receives "no balance info in response" rather than the actual API error string in parsed.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

📥 Commits

Reviewing files that changed from the base of the PR and between bb10b83 and 013da5d.

📒 Files selected for processing (2)
  • conf/models/siliconflow.json
  • internal/entity/models/siliconflow.go

Comment thread internal/entity/models/siliconflow.go Resolved
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.
@JinHai-CN JinHai-CN added the ci Continue Integration label May 7, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft May 7, 2026 12:56
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 7, 2026 12:57
@codecov

codecov Bot commented May 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (bb10b83) to head (5500eba).
⚠️ Report is 5 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment on lines +532 to +542
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"`
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"`
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JinHai-CN
JinHai-CN merged commit a86e0ca into infiniflow:main May 8, 2026
1 check passed
pekar9781 pushed a commit to pekar9781/ragflow that referenced this pull request May 8, 2026
### 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
@pandadev66 pandadev66 mentioned this pull request May 11, 2026
1 task done
hunnyboy1217 added a commit to hunnyboy1217/ragflow that referenced this pull request May 14, 2026
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
hunnyboy1217 added a commit to hunnyboy1217/ragflow that referenced this pull request May 14, 2026
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
@whitepicker whitepicker mentioned this pull request May 20, 2026
4 tasks done
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
### 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Implement Balance in the SiliconFlow Go driver

3 participants