Repository navigation
Go: add balance command - #14262
Go: add balance command#14262
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughThis 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (4 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 |
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
internal/entity/models/dummy.go (1)
60-62: Inconsistent error message vs. other drivers.
DeepSeekModel.BalanceandZhipuAIModel.Balancereturnfmt.Errorf("%s, no such method", z.Name()), while this one returns a bare"no such method". SinceName()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 theBalancecontract.Adding
Name()andBalance(apiConfig *APIConfig) (map[string]interface{}, error)toModelDriveris cleanly implemented across all existing drivers (deepseek.go,dummy.go,moonshot.go,zhipu-ai.go), so no build breakage. Two optional refinements:
- The
Balancereturn typemap[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.- A brief doc comment on
Balanceindicating 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
⛔ Files ignored due to path filters (1)
uv.lockis excluded by!**/*.lock
📒 Files selected for processing (14)
internal/cli/client.gointernal/cli/lexer.gointernal/cli/types.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/entity/models/deepseek.gointernal/entity/models/dummy.gointernal/entity/models/factory.gointernal/entity/models/moonshot.gointernal/entity/models/types.gointernal/entity/models/zhipu-ai.gointernal/handler/providers.gointernal/router/router.gointernal/service/model_service.go
| 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() |
There was a problem hiding this comment.
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.
| 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.
| // 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) |
There was a problem hiding this comment.
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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
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
What problem does this PR solve?
Type of change