Skip to content

Go: implement Balance in DeepSeek driver - #14632

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

JinHai-CN merged 2 commits into
infiniflow:mainfrom
pandadev66:feat/go-deepseek-balance

Conversation

@pandadev66

@pandadev66 pandadev66 commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

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

  • `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": , "currency": }`, 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

  • 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.

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.
@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: 37aaa24a-ebbb-49d9-8ff6-7c6a5795f372

📥 Commits

Reviewing files that changed from the base of the PR and between 9309643 and f72b4e3.

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

📝 Walkthrough

Walkthrough

Adds 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.

Changes

DeepSeek Balance Query Implementation

Layer / File(s) Summary
Endpoint Configuration
conf/models/deepseek.json
URL suffix mapping extended with "models": "models" and "balance": "user/balance".
Response Data Shape
internal/entity/models/deepseek.go
deepseekBalanceResponse struct defined to match /user/balance response with balance_infos entries and string numeric fields.
Balance Method
internal/entity/models/deepseek.go
DeepSeekModel.Balance() implemented with API key validation, region-aware base URL selection, authenticated GET to /user/balance, JSON parsing, string-to-float64 conversion, and non-200/parse error handling.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

  • infiniflow/ragflow#14290: Also updates DeepSeek configuration URL suffix entries for models and balance.
  • infiniflow/ragflow#14262: Related prior PR that added a stub for DeepSeekModel.Balance; this PR implements the full HTTP-backed logic.

Suggested labels

size:L

Poem

🐰 A little hop to check the chest,
DeepSeek speaks, I fetch the rest,
Tokens bearer, numbers bright,
Currency found, all set right,
I nibble logs and dance tonight.

🚥 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 DeepSeek driver.
Description check ✅ Passed The description fully addresses the template requirements with clear problem statement, comprehensive implementation details, edge cases, and proper type classification.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

@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

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 0501134 and 9309643.

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

Comment thread internal/entity/models/deepseek.go Resolved
…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.
@Haruko386 Haruko386 added the ci Continue Integration label May 7, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft May 7, 2026 12:55
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 7, 2026 12:55
@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 (0501134) to head (f72b4e3).
⚠️ Report is 5 commits behind head on main.

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.
📢 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.

@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 , 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?

@JinHai-CN
JinHai-CN merged commit e729ece into infiniflow:main May 8, 2026
2 checks passed
pekar9781 pushed a commit to pekar9781/ragflow that referenced this pull request May 8, 2026
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.
@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
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.
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 DeepSeek Go driver

3 participants