Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

CLI: add show model stats (#21376)

Jin Haib73f030931a0
diff --git a/internal/cli/cli_http.go b/internal/cli/cli_http.go
index 53a9b052d0..c5db5d87ed 100644
--- a/internal/cli/cli_http.go
+++ b/internal/cli/cli_http.go
@@ -514,6 +514,8 @@ func (c *CLI) ExecuteUserCommand(commandCount int, cmd *Command) (ResponseIf, er
return c.APIShowConcurrencyCommand(commandCount, cmd)
case "api_show_quota":
return c.APIShowQuotaCommand(commandCount, cmd)
+ case "api_show_model_stats":
+ return c.APIShowModelStatsCommand(commandCount, cmd)
case "api_list_api_servers":
return c.CommonListAPIServersCommand(commandCount, cmd)
case "api_list_environments":
diff --git a/internal/cli/lexer.go b/internal/cli/lexer.go
index 423d244dcb..2882b3c446 100644
--- a/internal/cli/lexer.go
+++ b/internal/cli/lexer.go
@@ -569,6 +569,10 @@ func (l *Lexer) lookupIdent(ident string) Token {
return Token{Type: TokenFatal, Value: ident}
case "PANIC":
return Token{Type: TokenPanic, Value: ident}
+ case "BY":
+ return Token{Type: TokenBy, Value: ident}
+ case "DATE":
+ return Token{Type: TokenDate, Value: ident}
case "PARAM":
return Token{Type: TokenParam, Value: ident}
case "PLAY":
diff --git a/internal/cli/types.go b/internal/cli/types.go
index 93e450aed0..706b090f41 100644
--- a/internal/cli/types.go
+++ b/internal/cli/types.go
@@ -215,6 +215,8 @@ const (
TokenError
TokenFatal
TokenPanic
+ TokenBy
+ TokenDate
// Literals
TokenIdentifier
TokenQuotedString
diff --git a/internal/cli/user_command.go b/internal/cli/user_command.go
index f513f0229e..3c86e463f9 100644
--- a/internal/cli/user_command.go
+++ b/internal/cli/user_command.go
@@ -3944,3 +3944,47 @@ func (c *CLI) APIShowQuotaCommand(commandCount int, cmd *Command) (ResponseIf, e
return HandleCommonDataResponse(resp, "get quota")
}
+
+func (c *CLI) APIShowModelStatsCommand(commandCount int, cmd *Command) (ResponseIf, error) {
+ httpClient, err := c.apiModeClient()
+ if err != nil {
+ return nil, err
+ }
+
+ // Build the query with url.Values rather than Sprintf: filter values are
+ // caller-supplied and may contain characters that need percent-encoding.
+ query := netUrl.Values{}
+ if days, ok := cmd.Params["days"].(int); ok && days > 0 {
+ query.Set("days", fmt.Sprintf("%d", days))
+ }
+ if v, ok := cmd.Params["start"].(string); ok && v != "" {
+ query.Set("start", v)
+ }
+ if v, ok := cmd.Params["end"].(string); ok && v != "" {
+ query.Set("end", v)
+ }
+ if v, ok := cmd.Params["provider"].(string); ok && v != "" {
+ query.Set("provider", v)
+ }
+ if v, ok := cmd.Params["instance"].(string); ok && v != "" {
+ query.Set("instance", v)
+ }
+ if v, ok := cmd.Params["model"].(string); ok && v != "" {
+ query.Set("model", v)
+ }
+ if v, ok := cmd.Params["by"].(string); ok && v != "" {
+ query.Set("by", v)
+ }
+
+ url := "/system/stats/model"
+ if encoded := query.Encode(); encoded != "" {
+ url += "?" + encoded
+ }
+
+ resp, err := httpClient.Request(commandCount, "GET", url, httpClient.AuthKind(), nil, nil)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get model stats: %w", err)
+ }
+
+ return HandleCommonResponse(resp, "get model stats")
+}
diff --git a/internal/cli/user_parser.go b/internal/cli/user_parser.go
index d1a8633817..df9f5e9433 100644
--- a/internal/cli/user_parser.go
+++ b/internal/cli/user_parser.go
@@ -812,9 +812,15 @@ func (p *Parser) parseAPIShowProviderModel(providerName string) (*Command, error
}
// SHOW MODEL 'model_name';
+// SHOW MODEL STATS [<time range>] ['<provider>' ['<instance>' ['<model>']]] [BY <dimension>]
func (p *Parser) parseAPIShowModel() (*Command, error) {
p.nextToken() // consume MODEL
+ // SHOW MODEL STATS ...
+ if p.curToken.Type == TokenStats {
+ return p.parseAPIShowModelStats()
+ }
+
modelName, err := p.parseQuotedString()
if err != nil {
return nil, fmt.Errorf("expected model name: %w", err)
@@ -967,6 +973,122 @@ func (p *Parser) parseAPIShowQuota() (*Command, error) {
return cmd, nil
}
+// SHOW MODEL STATS [<time range>]
+//
+// ['<provider>' ['<instance>' ['<model>']]]
+// [BY <dimension>]
+//
+// Time range (optional, defaults to today when omitted):
+//
+// FROM '<start>' TO '<end>'
+// DAYS <n>
+//
+// Filters (optional, in order): provider, then instance, then model.
+// Dimension (optional): BY DATE | BY MODEL | BY INSTANCE | BY PROVIDER.
+//
+// Examples:
+//
+// SHOW MODEL STATS;
+// SHOW MODEL STATS DAYS 7;
+// SHOW MODEL STATS FROM '2024-01-01' TO '2024-01-31';
+// SHOW MODEL STATS DAYS 7 'openai';
+// SHOW MODEL STATS DAYS 7 'openai' 'prod-instance' 'gpt-4o';
+// SHOW MODEL STATS DAYS 7 BY DATE;
+// SHOW MODEL STATS DAYS 30 'openai' 'prod' BY MODEL;
+// SHOW MODEL STATS FROM '2024-01-01' TO '2024-01-31' 'azure' BY INSTANCE;
+func (p *Parser) parseAPIShowModelStats() (*Command, error) {
+ p.nextToken() // consume STATS
+ cmd := NewCommand("api_show_model_stats")
+
+ // Optional time range. Omitted => backend defaults to today.
+ switch p.curToken.Type {
+ case TokenDays:
+ p.nextToken() // consume DAYS
+ days, err := p.parseNumber()
+ if err != nil {
+ return nil, fmt.Errorf("expected number of days after DAYS: %w", err)
+ }
+ cmd.Params["days"] = days
+ p.nextToken() // consume the integer token
+ case TokenFrom:
+ p.nextToken() // consume FROM
+ start, err := p.parseQuotedString()
+ if err != nil {
+ return nil, fmt.Errorf("expected start date after FROM: %w", err)
+ }
+ p.nextToken() // consume start
+ if p.curToken.Type != TokenTo {
+ return nil, fmt.Errorf("expected TO after FROM start, got %s", p.curToken.Value)
+ }
+ p.nextToken() // consume TO
+ end, err := p.parseQuotedString()
+ if err != nil {
+ return nil, fmt.Errorf("expected end date after TO: %w", err)
+ }
+ p.nextToken() // consume end
+ cmd.Params["start"] = start
+ cmd.Params["end"] = end
+ case TokenSemicolon, TokenEOF:
+ // No time range; nothing to consume here.
+ }
+
+ // Optional filters: provider, then instance, then model (each a quoted string).
+ if p.curToken.Type == TokenQuotedString {
+ provider, err := p.parseQuotedString()
+ if err != nil {
+ return nil, err
+ }
+ p.nextToken() // consume provider
+ cmd.Params["provider"] = provider
+
+ if p.curToken.Type == TokenQuotedString {
+ var instance string
+ instance, err = p.parseQuotedString()
+ if err != nil {
+ return nil, err
+ }
+ p.nextToken() // consume instance
+ cmd.Params["instance"] = instance
+
+ if p.curToken.Type == TokenQuotedString {
+ var model string
+ model, err = p.parseQuotedString()
+ if err != nil {
+ return nil, err
+ }
+ p.nextToken() // consume model
+ cmd.Params["model"] = model
+ }
+ }
+ }
+
+ // Optional grouping dimension: BY DATE | BY MODEL | BY INSTANCE | BY PROVIDER.
+ // BY is not a reserved keyword, so it arrives as a bare identifier.
+ if p.curToken.Type == TokenBy {
+ p.nextToken() // consume BY
+ switch {
+ case p.curToken.Type == TokenModel:
+ cmd.Params["by"] = "model"
+ case p.curToken.Type == TokenInstance:
+ cmd.Params["by"] = "instance"
+ case p.curToken.Type == TokenProvider:
+ cmd.Params["by"] = "provider"
+ case p.curToken.Type == TokenDate:
+ cmd.Params["by"] = "date"
+ default:
+ return nil, fmt.Errorf("unknown MODEL STATS dimension: %s", p.curToken.Value)
+ }
+ p.nextToken() // consume the dimension token
+ }
+
+ // Semicolon is optional
+ if p.curToken.Type == TokenSemicolon {
+ p.nextToken()
+ }
+
+ return cmd, nil
+}
+
// endregion SHOW commands
// region CREATE commands
diff --git a/internal/cli/user_parser_test.go b/internal/cli/user_parser_test.go
index 8ce6bf3982..ae9c9459b5 100644
--- a/internal/cli/user_parser_test.go
+++ b/internal/cli/user_parser_test.go
@@ -300,3 +300,112 @@ func TestParseListSyncLogs(t *testing.T) {
})
}
}
+
+func TestParseAPIShowModelStats(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ expectedParams map[string]interface{}
+ wantErr bool
+ }{
+ {
+ name: "default to today",
+ input: "SHOW MODEL STATS;",
+ expectedParams: map[string]interface{}{},
+ },
+ {
+ name: "last 7 days",
+ input: "SHOW MODEL STATS DAYS 7;",
+ expectedParams: map[string]interface{}{"days": 7},
+ },
+ {
+ name: "absolute range",
+ input: "SHOW MODEL STATS FROM '2024-01-01' TO '2024-01-31';",
+ expectedParams: map[string]interface{}{"start": "2024-01-01", "end": "2024-01-31"},
+ },
+ {
+ name: "provider filter",
+ input: "SHOW MODEL STATS DAYS 7 'openai';",
+ expectedParams: map[string]interface{}{"days": 7, "provider": "openai"},
+ },
+ {
+ name: "provider + instance filter",
+ input: "SHOW MODEL STATS DAYS 7 'openai' 'prod';",
+ expectedParams: map[string]interface{}{"days": 7, "provider": "openai", "instance": "prod"},
+ },
+ {
+ name: "provider + instance + model filter",
+ input: "SHOW MODEL STATS DAYS 7 'openai' 'prod' 'gpt-4o';",
+ expectedParams: map[string]interface{}{"days": 7, "provider": "openai", "instance": "prod", "model": "gpt-4o"},
+ },
+ {
+ name: "group by date",
+ input: "SHOW MODEL STATS DAYS 7 BY DATE;",
+ expectedParams: map[string]interface{}{"days": 7, "by": "date"},
+ },
+ {
+ name: "group by model",
+ input: "SHOW MODEL STATS DAYS 7 BY MODEL;",
+ expectedParams: map[string]interface{}{"days": 7, "by": "model"},
+ },
+ {
+ name: "group by instance",
+ input: "SHOW MODEL STATS DAYS 7 BY INSTANCE;",
+ expectedParams: map[string]interface{}{"days": 7, "by": "instance"},
+ },
+ {
+ name: "group by provider",
+ input: "SHOW MODEL STATS DAYS 7 BY PROVIDER;",
+ expectedParams: map[string]interface{}{"days": 7, "by": "provider"},
+ },
+ {
+ name: "provider filter + group by date",
+ input: "SHOW MODEL STATS DAYS 30 'openai' BY DATE;",
+ expectedParams: map[string]interface{}{"days": 30, "provider": "openai", "by": "date"},
+ },
+ {
+ name: "provider + instance filter + group by model",
+ input: "SHOW MODEL STATS DAYS 30 'openai' 'prod' BY MODEL;",
+ expectedParams: map[string]interface{}{"days": 30, "provider": "openai", "instance": "prod", "by": "model"},
+ },
+ {
+ name: "provider + instance + model filter + group by date",
+ input: "SHOW MODEL STATS DAYS 30 'openai' 'prod' 'gpt-4o' BY DATE;",
+ expectedParams: map[string]interface{}{"days": 30, "provider": "openai", "instance": "prod", "model": "gpt-4o", "by": "date"},
+ },
+ {
+ name: "absolute range + provider filter + group by instance",
+ input: "SHOW MODEL STATS FROM '2024-01-01' TO '2024-01-31' 'azure' BY INSTANCE;",
+ expectedParams: map[string]interface{}{"start": "2024-01-01", "end": "2024-01-31", "provider": "azure", "by": "instance"},
+ },
+ {
+ name: "absolute range + group by provider",
+ input: "SHOW MODEL STATS FROM '2024-01-01' TO '2024-01-31' BY PROVIDER;",
+ expectedParams: map[string]interface{}{"start": "2024-01-01", "end": "2024-01-31", "by": "provider"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ p := NewParser(tt.input)
+ cmd, err := p.Parse(APIMode)
+ if tt.wantErr {
+ if err == nil {
+ t.Fatalf("Parse() error = nil, want error")
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("Parse() error = %v", err)
+ }
+
+ if cmd.Type != "api_show_model_stats" {
+ t.Fatalf("Command Type = %v, expected api_show_model_stats", cmd.Type)
+ }
+
+ if !reflect.DeepEqual(cmd.Params, tt.expectedParams) {
+ t.Errorf("Params = %#v, expected %#v", cmd.Params, tt.expectedParams)
+ }
+ })
+ }
+}
diff --git a/internal/handler/stats.go b/internal/handler/stats.go
index c90cd4dcdd..2d95705838 100644
--- a/internal/handler/stats.go
+++ b/internal/handler/stats.go
@@ -37,8 +37,8 @@ func NewStatsHandler(statsService *service.StatsService) *StatsHandler {
}
}
-// GetStats returns API conversation statistics for the current user's tenant.
-func (h *StatsHandler) GetStats(c *gin.Context) {
+// GetChatStats returns API conversation statistics for the current user's tenant.
+func (h *StatsHandler) GetChatStats(c *gin.Context) {
user, errorCode, errorMessage := GetUser(c)
if errorCode != common.CodeSuccess {
common.ErrorWithCode(c, errorCode, errorMessage)
@@ -60,7 +60,7 @@ func (h *StatsHandler) GetStats(c *gin.Context) {
ctx := c.Request.Context()
// Get stats
- stats, err := h.statsService.GetStats(ctx, user.ID, fromDate, toDate, source)
+ stats, err := h.statsService.GetChatStats(ctx, user.ID, fromDate, toDate, source)
if err != nil {
code := common.CodeExceptionError
if errors.Is(err, service.ErrTenantNotFound) {
diff --git a/internal/handler/stats_ee.go b/internal/handler/stats_ee.go
new file mode 100644
index 0000000000..f9f6401ae6
--- /dev/null
+++ b/internal/handler/stats_ee.go
@@ -0,0 +1,31 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package handler
+
+import (
+ "ragflow/internal/common"
+
+ "github.com/gin-gonic/gin"
+)
+
+func (h *StatsHandler) GetModelStats(c *gin.Context) {
+ common.ErrorWithCode(c, common.CodeNotImplemented, "GetModelStats not implemented")
+}
+
+func (h *StatsHandler) GetGroupStats(c *gin.Context) {
+ common.ErrorWithCode(c, common.CodeNotImplemented, "GetGroupStats not implemented")
+}
diff --git a/internal/router/router.go b/internal/router/router.go
index 05948a3e8e..9af3d5930c 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -643,7 +643,9 @@ func (r *Router) Setup(engine *gin.Engine) {
system := v1.Group("/system")
{
system.GET("/status", r.systemHandler.GetStatus)
- system.GET("/stats", r.statsHandler.GetStats) // TODO: need to reconsider this endpoint and function
+ system.GET("/stats/chat", r.statsHandler.GetChatStats)
+ system.GET("/stats/group", r.statsHandler.GetGroupStats)
+ system.GET("/stats/model", r.statsHandler.GetModelStats)
config := system.Group("/config")
{
diff --git a/internal/service/stats.go b/internal/service/stats.go
index 68385e2e01..918c435cdb 100644
--- a/internal/service/stats.go
+++ b/internal/service/stats.go
@@ -40,8 +40,8 @@ func NewStatsService() *StatsService {
}
}
-// StatsResponse matches Python GET /api/v1/system/stats response data.
-type StatsResponse struct {
+// ChatStatsResponse matches Python GET /api/v1/system/stats response data.
+type ChatStatsResponse struct {
PV []StatPoint `json:"pv"`
UV []StatPoint `json:"uv"`
Speed []StatPoint `json:"speed"`
@@ -50,8 +50,8 @@ type StatsResponse struct {
ThumbUp []StatPoint `json:"thumb_up"`
}
-// GetStats returns daily API conversation statistics for the first tenant of a user.
-func (s *StatsService) GetStats(ctx context.Context, userID, fromDate, toDate string, source *string) (*StatsResponse, error) {
+// GetChatStats returns daily API conversation statistics for the first tenant of a user.
+func (s *StatsService) GetChatStats(ctx context.Context, userID, fromDate, toDate string, source *string) (*ChatStatsResponse, error) {
tenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, userID)
if err != nil || len(tenants) == 0 {
return nil, ErrTenantNotFound
@@ -62,7 +62,7 @@ func (s *StatsService) GetStats(ctx context.Context, userID, fromDate, toDate st
return nil, err
}
- response := &StatsResponse{
+ response := &ChatStatsResponse{
PV: make([]StatPoint, 0, len(rows)),
UV: make([]StatPoint, 0, len(rows)),
Speed: make([]StatPoint, 0, len(rows)),
diff --git a/test/api/system_api_test.go b/test/api/system_api_test.go
index a2b64dcd14..9516cffbc9 100644
--- a/test/api/system_api_test.go
+++ b/test/api/system_api_test.go
@@ -43,7 +43,7 @@ func TestRESTSystemPublicContracts(t *testing.T) {
func TestRESTSystemProtectedContracts(t *testing.T) {
unauth := unauthenticatedConfig()
- for _, path := range []string{"/system/status", "/system/stats", "/system/tokens", "/system/config/log"} {
+ for _, path := range []string{"/system/status", "/system/stats/chat", "/system/tokens", "/system/config/log"} {
result := restCall(t, &unauth, http.MethodGet, path, nil, nil)
if result.Status != http.StatusUnauthorized || result.JSON["code"] != float64(401) {
t.Fatalf("%s auth contract: status=%d body=%v", path, result.Status, result.JSON)
@@ -55,7 +55,7 @@ func TestRESTSystemProtectedContracts(t *testing.T) {
t.Fatalf("status missing %q: %v", key, status)
}
}
- stats := object(t, restOK(t, restCall(t, TestConfig, http.MethodGet, "/system/stats", nil, nil))["data"])
+ stats := object(t, restOK(t, restCall(t, TestConfig, http.MethodGet, "/system/stats/chat", nil, nil))["data"])
for _, key := range []string{"pv", "uv", "speed", "tokens", "round", "thumb_up"} {
if _, ok := stats[key].([]any); !ok {
t.Fatalf("stats[%q] must be an array: %T", key, stats[key])