Skip to content

Go: add balance command - #14262

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
JinHai-CN:fix394
Apr 21, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
JinHai-CN:fix394

Conversation

@JinHai-CN

@JinHai-CN JinHai-CN commented Apr 21, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

RAGFlow(user)> list supported models from 'moonshot' 'test';
+---------------------------------+
| model_name                      |
+---------------------------------+
| moonshot-v1-32k-vision-preview  |
| kimi-k2.6                       |
| moonshot-v1-8k                  |
| moonshot-v1-auto                |
| moonshot-v1-128k                |
| moonshot-v1-32k                 |
| kimi-k2.5                       |
| moonshot-v1-8k-vision-preview   |
| moonshot-v1-128k-vision-preview |
+---------------------------------+
RAGFlow(user)> show balance from 'moonshot' 'test';
+---------+----------+
| balance | currency |
+---------+----------+
| 0       | CNY      |
+---------+----------+

Type of change

  • New Feature (non-breaking change which adds functionality)

@JinHai-CN JinHai-CN added the ci Continue Integration label Apr 21, 2026
@coderabbitai

coderabbitai Bot commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This pull request introduces a new "SHOW BALANCE" CLI command and corresponding HTTP API endpoint that enables users to query the balance of their provider instances. The implementation spans the CLI lexer, parser, command dispatcher, HTTP handler, service layer, and model driver interface, with balance method implementations added to multiple provider drivers.

Changes

Cohort / File(s) Summary
CLI Lexer & Parser
internal/cli/types.go, internal/cli/lexer.go, internal/cli/user_parser.go
Added TokenBalance token type, extended lexer to recognize "BALANCE" identifier, and implemented parser logic for SHOW BALANCE FROM <provider_name> <instance_name> syntax.
CLI Command Handler
internal/cli/client.go, internal/cli/user_command.go
Routed show_instance_balance command dispatch and implemented HTTP GET handler that validates parameters, calls /providers/{providerName}/instances/{instanceName}/balance, and returns balance response.
HTTP API Layer
internal/router/router.go, internal/handler/providers.go
Added GET route and Gin handler for balance endpoint; handler extracts URL params, validates input, retrieves user context, and delegates to service layer.
Service Layer
internal/service/model_service.go
Implemented ShowInstanceBalance() method that resolves tenant, loads provider and instance data, constructs APIConfig with credentials, and delegates balance retrieval to model driver.
Model Driver Interface & Implementations
internal/entity/models/types.go, internal/entity/models/factory.go
Extended ModelDriver interface with Name() and Balance() methods; fixed Moonshot constructor typo (MooshotModel → MoonshotModel), updated ListModels() to use GET, and added functional Balance() implementation.
Model Provider Stubs
internal/entity/models/dummy.go, internal/entity/models/deepseek.go, internal/entity/models/zhipu-ai.go
Added Name() and Balance() stub methods; Zhipu-AI also updated error messages to use Name() method.

Sequence Diagram(s)

sequenceDiagram
    participant User as User (CLI)
    participant Parser as Parser
    participant Client as HTTP Client
    participant Handler as Handler
    participant Service as Service
    participant DAO as DAO Layer
    participant Driver as Model Driver
    participant API as Provider API

    User->>Parser: SHOW BALANCE FROM provider instance
    Parser->>Parser: Tokenize & parse
    Parser->>Client: ExecuteUserCommand(show_instance_balance)
    Client->>Client: Prepare HTTP GET request
    Client->>Handler: GET /providers/{provider}/instances/{instance}/balance
    
    Handler->>Handler: Extract & validate params
    Handler->>Service: ShowInstanceBalance(provider, instance, userID)
    
    Service->>DAO: GetByUserIDAndRole(userID, owner)
    DAO-->>Service: tenant
    Service->>DAO: GetByTenantIDAndProviderName(tenant, provider)
    DAO-->>Service: provider instance
    Service->>DAO: GetModelProviderManager().FindProvider(provider)
    DAO-->>Service: provider driver info
    
    Service->>Driver: Balance(apiConfig with region & key)
    Driver->>API: GET /balance endpoint
    API-->>Driver: balance amount
    Driver-->>Service: {balance: amount, currency: ...}
    
    Service-->>Handler: balance map, success code
    Handler-->>Client: HTTP 200 {code: 0, data: balance}
    Client-->>User: Display balance
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

size:M

Poem

🐰 A balance query hops along the way,
Through parsers, handlers—ledgers on display,
From CLI dreams to provider API calls,
Where Moonshot shines (no typo walls!)
The drivers now report their wealth,
A feature blooming, full and stealth!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The PR description includes practical examples of the new balance command functionality but omits the required 'What problem does this PR solve?' narrative context explaining the motivation. Add a brief explanation of the problem/use case that this balance command feature addresses to complete the description context.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: add balance command' accurately describes the main feature addition: a new balance command for displaying account balances.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.

@JinHai-CN
JinHai-CN marked this pull request as ready for review April 21, 2026 12:43
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 21, 2026

@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: 2

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

60-62: Inconsistent error message vs. other drivers.

DeepSeekModel.Balance and ZhipuAIModel.Balance return fmt.Errorf("%s, no such method", z.Name()), while this one returns a bare "no such method". Since Name() is now implemented, prefer the same format for consistent diagnostics.

Proposed change
 func (z *DummyModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) {
-	return nil, fmt.Errorf("no such method")
+	return nil, fmt.Errorf("%s, no such method", z.Name())
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/dummy.go` around lines 60 - 62, The DummyModel.Balance
method returns a bare error string; update it to match DeepSeekModel.Balance and
ZhipuAIModel.Balance by including the model name via z.Name(), e.g. return
fmt.Errorf("%s, no such method", z.Name()), so diagnostics are consistent across
drivers and leverage the implemented Name() method.
internal/entity/models/types.go (1)

4-17: Interface extension looks reasonable; consider documenting the Balance contract.

Adding Name() and Balance(apiConfig *APIConfig) (map[string]interface{}, error) to ModelDriver is cleanly implemented across all existing drivers (deepseek.go, dummy.go, moonshot.go, zhipu-ai.go), so no build breakage. Two optional refinements:

  1. The Balance return type map[string]interface{} is untyped — a small struct (e.g., BalanceInfo { Balance float64; Currency string; ... }) would make the contract explicit for service/handler consumers and avoid ad‑hoc key lookups.
  2. A brief doc comment on Balance indicating the expected keys (e.g., balance, currency) and that unsupported providers should return a "no such method"-style error would help future driver implementers stay consistent.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/types.go` around lines 4 - 17, The new
ModelDriver.Balance method lacks a contract; add a doc comment on the Balance
method in the ModelDriver interface describing the expected fields (e.g.,
"balance" as float64, "currency" as string) and that drivers which don't support
balance should return a consistent "unsupported" error string; optionally
replace the untyped map[string]interface{} with a concrete BalanceInfo struct
(e.g., BalanceInfo with Balance float64, Currency string, etc.) and update the
ModelDriver.Balance signature and all implementations (deepseek.go, dummy.go,
moonshot.go, zhipu-ai.go) to return BalanceInfo (or the documented map) and the
standardized unsupported error where appropriate.
internal/service/model_service.go (1)

478-493: Remove the unreachable commented block.

This code sits after the return path and is no longer part of the balance implementation.

Proposed cleanup
-	// convert instance.Extra (json string) to map
-	//var extra map[string]string
-	//err = json.Unmarshal([]byte(instance.Extra), &extra)
-	//if err != nil {
-	//	return nil, common.CodeServerError, err
-	//}
-	//
-	//result := map[string]interface{}{
-	//	"id":           instance.ID,
-	//	"instanceName": instance.InstanceName,
-	//	"providerID":   instance.ProviderID,
-	//	"status":       instance.Status,
-	//	"region":       extra["region"],
-	//}
-	//
-	//return result, common.CodeSuccess, nil
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/model_service.go` around lines 478 - 493, Remove the
unreachable commented block in model_service.go: delete the commented-out
json.Unmarshal of instance.Extra and the subsequent construction of result (the
block referencing instance.Extra, extra map, and the result map with keys
"id","instanceName","providerID","status","region") that appears after the
return path in the function containing instance and result; keep the function
logic compact by removing these dead comments and any unused commented variables
like extra and err to avoid confusion.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/cli/user_parser.go`:
- Around line 1331-1340: The parser is advancing past the parsed instance name
twice causing it to swallow trailing input; in the block that builds the
"show_instance_balance" command (around NewCommand("show_instance_balance"),
p.Params["instance_name"], p.Params["provider_name"]) remove the extra
p.nextToken() call that occurs before the semicolon check so the optional
semicolon is examined against the current token (p.curToken) rather than
advancing past it; keep the semicolon-handling logic that calls p.nextToken()
only when p.curToken.Type == TokenSemicolon.

In `@internal/entity/models/moonshot.go`:
- Around line 116-121: The parsing currently directly type-asserts
result["data"] and modelMap["id"] which will panic on unexpected JSON; change
result handling in the function that builds models (the code using result,
models, modelMap and modelName) to first check that result["data"] exists and is
a []interface{} (use a safe type assertion and return an error if not), iterate
safely casting each element to map[string]interface{} only after verifying the
type, check that modelMap["id"] is a string before appending to models (return a
descriptive error if missing/invalid), and apply the same defensive checks to
the other occurrence that also asserts result["data"] and modelMap["id"] (the
block around lines 173-174) so the function returns an error instead of
panicking when the external API response shape is unexpected.

---

Nitpick comments:
In `@internal/entity/models/dummy.go`:
- Around line 60-62: The DummyModel.Balance method returns a bare error string;
update it to match DeepSeekModel.Balance and ZhipuAIModel.Balance by including
the model name via z.Name(), e.g. return fmt.Errorf("%s, no such method",
z.Name()), so diagnostics are consistent across drivers and leverage the
implemented Name() method.

In `@internal/entity/models/types.go`:
- Around line 4-17: The new ModelDriver.Balance method lacks a contract; add a
doc comment on the Balance method in the ModelDriver interface describing the
expected fields (e.g., "balance" as float64, "currency" as string) and that
drivers which don't support balance should return a consistent "unsupported"
error string; optionally replace the untyped map[string]interface{} with a
concrete BalanceInfo struct (e.g., BalanceInfo with Balance float64, Currency
string, etc.) and update the ModelDriver.Balance signature and all
implementations (deepseek.go, dummy.go, moonshot.go, zhipu-ai.go) to return
BalanceInfo (or the documented map) and the standardized unsupported error where
appropriate.

In `@internal/service/model_service.go`:
- Around line 478-493: Remove the unreachable commented block in
model_service.go: delete the commented-out json.Unmarshal of instance.Extra and
the subsequent construction of result (the block referencing instance.Extra,
extra map, and the result map with keys
"id","instanceName","providerID","status","region") that appears after the
return path in the function containing instance and result; keep the function
logic compact by removing these dead comments and any unused commented variables
like extra and err to avoid confusion.
🪄 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: 764ae551-9712-4882-899c-3c4f2e3e894b

📥 Commits

Reviewing files that changed from the base of the PR and between 2d05475 and 640fe8d.

⛔ Files ignored due to path filters (1)
  • uv.lock is excluded by !**/*.lock
📒 Files selected for processing (14)
  • internal/cli/client.go
  • internal/cli/lexer.go
  • internal/cli/types.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/dummy.go
  • internal/entity/models/factory.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/types.go
  • internal/entity/models/zhipu-ai.go
  • internal/handler/providers.go
  • internal/router/router.go
  • internal/service/model_service.go

Comment on lines +1331 to +1340
p.nextToken()

cmd := NewCommand("show_instance_balance")
cmd.Params["instance_name"] = instanceName
cmd.Params["provider_name"] = providerName

p.nextToken()
// Semicolon is optional
if p.curToken.Type == TokenSemicolon {
p.nextToken()

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.

⚠️ Potential issue | 🟡 Minor

Avoid advancing past the parsed instance name twice.

Line 1337 consumes one extra token before the semicolon check. That can silently swallow unexpected trailing input after SHOW BALANCE FROM 'provider' 'instance' and makes this parser differ from the surrounding command parsers.

Proposed fix
 	cmd.Params["instance_name"] = instanceName
 	cmd.Params["provider_name"] = providerName
 
-	p.nextToken()
 	// Semicolon is optional
 	if p.curToken.Type == TokenSemicolon {
 		p.nextToken()
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
p.nextToken()
cmd := NewCommand("show_instance_balance")
cmd.Params["instance_name"] = instanceName
cmd.Params["provider_name"] = providerName
p.nextToken()
// Semicolon is optional
if p.curToken.Type == TokenSemicolon {
p.nextToken()
p.nextToken()
cmd := NewCommand("show_instance_balance")
cmd.Params["instance_name"] = instanceName
cmd.Params["provider_name"] = providerName
// Semicolon is optional
if p.curToken.Type == TokenSemicolon {
p.nextToken()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/cli/user_parser.go` around lines 1331 - 1340, The parser is
advancing past the parsed instance name twice causing it to swallow trailing
input; in the block that builds the "show_instance_balance" command (around
NewCommand("show_instance_balance"), p.Params["instance_name"],
p.Params["provider_name"]) remove the extra p.nextToken() call that occurs
before the semicolon check so the optional semicolon is examined against the
current token (p.curToken) rather than advancing past it; keep the
semicolon-handling logic that calls p.nextToken() only when p.curToken.Type ==
TokenSemicolon.

Comment on lines +116 to +121
// convert result["data"] to []map[string]interface{}
models := make([]string, 0)
for _, model := range result["data"].([]interface{}) {
modelMap := model.(map[string]interface{})
modelName := modelMap["id"].(string)
models = append(models, modelName)

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.

⚠️ Potential issue | 🟠 Major

Guard Moonshot response parsing instead of panicking on unexpected JSON.

Lines 118-120 and 173-174 assert external API response shapes directly. A 200 response with an error payload, missing data, or a changed field type will panic the server path instead of returning a normal error.

Proposed fix
-	// convert result["data"] to []map[string]interface{}
-	models := make([]string, 0)
-	for _, model := range result["data"].([]interface{}) {
-		modelMap := model.(map[string]interface{})
-		modelName := modelMap["id"].(string)
+	data, ok := result["data"].([]interface{})
+	if !ok {
+		return nil, fmt.Errorf("unexpected models response: data is %T", result["data"])
+	}
+
+	models := make([]string, 0, len(data))
+	for _, model := range data {
+		modelMap, ok := model.(map[string]interface{})
+		if !ok {
+			return nil, fmt.Errorf("unexpected model entry type: %T", model)
+		}
+		modelName, ok := modelMap["id"].(string)
+		if !ok || modelName == "" {
+			return nil, fmt.Errorf("unexpected model entry: missing string id")
+		}
 		models = append(models, modelName)
 	}
-	data := result["data"].(map[string]interface{})
-	balance := data["available_balance"].(float64)
+	data, ok := result["data"].(map[string]interface{})
+	if !ok {
+		return nil, fmt.Errorf("unexpected balance response: data is %T", result["data"])
+	}
+	balance, ok := data["available_balance"].(float64)
+	if !ok {
+		return nil, fmt.Errorf("unexpected balance response: available_balance is %T", data["available_balance"])
+	}

Also applies to: 173-174

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/moonshot.go` around lines 116 - 121, The parsing
currently directly type-asserts result["data"] and modelMap["id"] which will
panic on unexpected JSON; change result handling in the function that builds
models (the code using result, models, modelMap and modelName) to first check
that result["data"] exists and is a []interface{} (use a safe type assertion and
return an error if not), iterate safely casting each element to
map[string]interface{} only after verifying the type, check that modelMap["id"]
is a string before appending to models (return a descriptive error if
missing/invalid), and apply the same defensive checks to the other occurrence
that also asserts result["data"] and modelMap["id"] (the block around lines
173-174) so the function returns an error instead of panicking when the external
API response shape is unexpected.

@codecov

codecov Bot commented Apr 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.97%. Comparing base (009e538) to head (640fe8d).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14262      +/-   ##
==========================================
- Coverage   96.66%   95.97%   -0.70%     
==========================================
  Files          10       10              
  Lines         690      695       +5     
  Branches      108      111       +3     
==========================================
  Hits          667      667              
- Misses          8       11       +3     
- Partials       15       17       +2     

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

@JinHai-CN
JinHai-CN merged commit 74b44e1 into infiniflow:main Apr 21, 2026
2 checks passed
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant