Repository navigation
Go: implement Balance in DeepSeek driver - #14632
Conversation
The DeepSeek Go driver shipped with a stub Balance method that
returned "no such method", even though DeepSeek exposes a public
GET /user/balance endpoint that works with the same Bearer
token used for chat. So the "Balance" panel in the model
provider UI always showed an error for DeepSeek tenants, while
it works for Moonshot and Gitee.
This commit adds the real implementation.
Changes:
- conf/models/deepseek.json: add "balance": "user/balance" under
url_suffix so the driver can build the URL from config the
same way the other endpoints do.
- internal/entity/models/deepseek.go: replace the Balance stub
with a real implementation. Adds a small local response type
deepseekBalanceResponse 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. DeepSeek returns the shape:
{
"is_available": true,
"balance_infos": [
{"currency": "USD", "total_balance": "10.00", ...},
{"currency": "CNY", "total_balance": "70.00", ...}
]
}
total_balance is a string in the upstream API, so the driver
parses it with strconv.ParseFloat.
- Return the first balance entry as
{"balance": <float>, "currency": <string>}, 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.
- Empty balance_infos returns a clear "no balance info in
response" error rather than a zero-value silent success.
- Non-numeric total_balance returns a clear parse error.
- Non-200 responses propagate the upstream status line and body
so the user can see why the call failed.
|
ℹ️ 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 DeepSeek balance support: extends config with endpoints, defines a typed balance response, and implements DeepSeekModel.Balance to call /user/balance, parse the response, and return numeric balance and currency. ChangesDeepSeek Balance Query Implementation
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. This follows the Moonshot Balance pattern, scope is two files (one config, one driver), and it makes the existing Balance button work for DeepSeek the same way it already works for Moonshot and Gitee. Thanks! |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/deepseek.go`:
- Around line 509-517: The code currently sets region from apiConfig.Region and
immediately errors if z.BaseURL doesn't contain it; instead change the lookup so
that if apiConfig.Region is provided but not present (or empty) in z.BaseURL,
the code falls back to the "default" region rather than returning an error.
Update the region resolution logic around apiConfig.Region, z.BaseURL and the
local region variable in deepseek.go: check for a configured baseURL for the
requested region and only use it if found and non-empty, otherwise set region =
"default" and then validate that z.BaseURL["default"] exists before returning an
error.
🪄 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: 1e5e6927-e934-4d1c-b0f8-69716c19446e
📒 Files selected for processing (2)
conf/models/deepseek.jsoninternal/entity/models/deepseek.go
…s unknown Address CodeRabbit review note. The previous Balance code took apiConfig.Region as-is and returned a hard error when that region key was not present in z.BaseURL. That contradicts the intended default-fallback behavior and breaks valid requests when a stray or unrecognized region value is set. The fix mirrors the pattern used by other drivers: pre-load the default base URL, override it only if a non-empty regional URL is configured, and only error out when the default itself is missing.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14632 +/- ##
=======================================
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:
|
Haruko386
left a comment
There was a problem hiding this comment.
Hi @pandadev66 , LGTM
I have reviewed the code changes, and there are no apparent issues with the code, thank you for you contribution.
However, to ensure everything works flawlessly in practice, could you please provide a snippet of your local test results in your future PR description or comments?
Closes infiniflow#14631 ### What problem does this PR solve? The DeepSeek Go driver shipped with a stub \`Balance\` method that returned \`no such method\`, even though DeepSeek exposes a public \`GET /user/balance\` endpoint that works with the same Bearer token used for chat. So the "Balance" panel in the model provider UI always shows an error for DeepSeek tenants, while it already works for Moonshot and Gitee. This PR fills the gap. ### What this PR includes - \`conf/models/deepseek.json\`: add \`\"balance\": \"user/balance\"\` under \`url_suffix\` so the driver can build the URL from config the same way the other endpoints do. - \`internal/entity/models/deepseek.go\`: replace the \`Balance\` stub with a real implementation. Adds a small local response type \`deepseekBalanceResponse\` 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: \`\`\`json { \"is_available\": true, \"balance_infos\": [ {\"currency\": \"USD\", \"total_balance\": \"10.00\", ...}, {\"currency\": \"CNY\", \"total_balance\": \"70.00\", ...} ] } \`\`\` \`total_balance\` is a string in the upstream API, so the driver parses it with \`strconv.ParseFloat\`. - Return the first balance entry as \`{\"balance\": <float>, \"currency\": <string>}\`, 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. - Empty \`balance_infos\` returns a clear \"no balance info in response\" error rather than a zero-value silent success. - Non-numeric \`total_balance\` returns a clear parse error. - Non-200 responses propagate the upstream status line and body so the user can see why the call failed. ### 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 (the go.mod minimum) returns exit 0. - The full method set on \`DeepSeekModel\` still matches the \`ModelDriver\` interface. - Pattern parity with the existing Moonshot and Gitee Balance implementations.
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
Closes infiniflow#14631 ### What problem does this PR solve? The DeepSeek Go driver shipped with a stub \`Balance\` method that returned \`no such method\`, even though DeepSeek exposes a public \`GET /user/balance\` endpoint that works with the same Bearer token used for chat. So the "Balance" panel in the model provider UI always shows an error for DeepSeek tenants, while it already works for Moonshot and Gitee. This PR fills the gap. ### What this PR includes - \`conf/models/deepseek.json\`: add \`\"balance\": \"user/balance\"\` under \`url_suffix\` so the driver can build the URL from config the same way the other endpoints do. - \`internal/entity/models/deepseek.go\`: replace the \`Balance\` stub with a real implementation. Adds a small local response type \`deepseekBalanceResponse\` 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: \`\`\`json { \"is_available\": true, \"balance_infos\": [ {\"currency\": \"USD\", \"total_balance\": \"10.00\", ...}, {\"currency\": \"CNY\", \"total_balance\": \"70.00\", ...} ] } \`\`\` \`total_balance\` is a string in the upstream API, so the driver parses it with \`strconv.ParseFloat\`. - Return the first balance entry as \`{\"balance\": <float>, \"currency\": <string>}\`, 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. - Empty \`balance_infos\` returns a clear \"no balance info in response\" error rather than a zero-value silent success. - Non-numeric \`total_balance\` returns a clear parse error. - Non-200 responses propagate the upstream status line and body so the user can see why the call failed. ### 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 (the go.mod minimum) returns exit 0. - The full method set on \`DeepSeekModel\` still matches the \`ModelDriver\` interface. - Pattern parity with the existing Moonshot and Gitee Balance implementations.
Closes #14631
What problem does this PR solve?
The DeepSeek Go driver shipped with a stub `Balance` method that returned `no such method`, even though DeepSeek exposes a public `GET /user/balance` endpoint that works with the same Bearer token used for chat.
So the "Balance" panel in the model provider UI always shows an error for DeepSeek 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
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:
```json
{
"is_available": true,
"balance_infos": [
{"currency": "USD", "total_balance": "10.00", ...},
{"currency": "CNY", "total_balance": "70.00", ...}
]
}
```
`total_balance` is a string in the upstream API, so the driver parses it with `strconv.ParseFloat`.
Return the first balance entry as `{"balance": , "currency": }`, the same shape the Moonshot driver returns. The UI can render it with no provider-specific code.
Edge cases
Type of change
How was this tested?