From a86e0ca0ca2037ec97b6585b47b7ee92f1259519 Mon Sep 17 00:00:00 2001 From: Panda Dev <56657208+pandadev66@users.noreply.github.com> Date: Fri, 8 May 2026 06:01:10 +0200 Subject: [PATCH] Go: implement Balance in SiliconFlow driver (#14643) ### 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 \`. - 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 - [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 #14642 --- conf/models/siliconflow.json | 3 +- internal/entity/models/siliconflow.go | 85 ++++++++++++++++++++++++++- 2 files changed, 86 insertions(+), 2 deletions(-) diff --git a/conf/models/siliconflow.json b/conf/models/siliconflow.json index d9340365d0..4da3e0dcab 100644 --- a/conf/models/siliconflow.json +++ b/conf/models/siliconflow.json @@ -7,7 +7,8 @@ "chat": "chat/completions", "models": "models", "embedding": "embeddings", - "rerank": "rerank" + "rerank": "rerank", + "balance": "user/info" }, "models": [ { diff --git a/internal/entity/models/siliconflow.go b/internal/entity/models/siliconflow.go index c1a1db07ef..6c9e9ce4af 100644 --- a/internal/entity/models/siliconflow.go +++ b/internal/entity/models/siliconflow.go @@ -24,6 +24,7 @@ import ( "io" "net/http" "ragflow/internal/common" + "strconv" "strings" "time" ) @@ -528,8 +529,90 @@ func (z *SiliconflowModel) ListModels(apiConfig *APIConfig) ([]string, error) { return models, nil } +type siliconflowBalanceResponse struct { + Code int `json:"code"` + Status bool `json:"status"` + Message string `json:"message"` + Data struct { + Balance string `json:"balance"` + TotalBalance string `json:"totalBalance"` + } `json:"data"` +} + func (z *SiliconflowModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) { - return nil, fmt.Errorf("%s, no such method", z.Name()) + if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" { + return nil, fmt.Errorf("api key is required") + } + + region := "default" + if apiConfig.Region != nil && *apiConfig.Region != "" { + region = *apiConfig.Region + } + + baseURL := z.BaseURL["default"] + if region != "default" { + if regional, ok := z.BaseURL[region]; ok && regional != "" { + baseURL = regional + } + } + if baseURL == "" { + return nil, fmt.Errorf("siliconflow: no base URL configured for default region") + } + + url := fmt.Sprintf("%s/%s", strings.TrimSuffix(baseURL, "/"), z.URLSuffix.Balance) + + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return nil, fmt.Errorf("failed to create request: %w", err) + } + + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) + + resp, err := z.httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("failed to send request: %w", err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response: %w", err) + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("SiliconFlow balance API error: %s, body: %s", resp.Status, string(body)) + } + + 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 + if raw == "" { + raw = parsed.Data.Balance + } + if raw == "" { + return nil, fmt.Errorf("no balance info in response") + } + + total, err := strconv.ParseFloat(raw, 64) + if err != nil { + return nil, fmt.Errorf("invalid balance %q: %w", raw, err) + } + + return map[string]interface{}{ + "balance": total, + "currency": "CNY", + }, nil } func (z *SiliconflowModel) CheckConnection(apiConfig *APIConfig) error {