-
-
Notifications
You must be signed in to change notification settings - Fork 646
feat: add token usage tracking and Prometheus metrics endpoint #416
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
zangxin75
wants to merge
2
commits into
tbphp:main
Choose a base branch
from
zangxin75:feat/token-usage-tracking
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| package db | ||
|
|
||
| import ( | ||
| "gpt-load/internal/models" | ||
|
|
||
| "github.com/sirupsen/logrus" | ||
| "gorm.io/gorm" | ||
| ) | ||
|
|
||
| // V1_2_0_AddTokenColumns adds token usage columns to request_logs table | ||
| func V1_2_0_AddTokenColumns(db *gorm.DB) error { | ||
| if !db.Migrator().HasColumn(&models.RequestLog{}, "prompt_tokens") { | ||
| if err := db.Migrator().AddColumn(&models.RequestLog{}, "prompt_tokens"); err != nil { | ||
| return err | ||
| } | ||
| logrus.Info("Added column prompt_tokens to request_logs") | ||
| } | ||
| if !db.Migrator().HasColumn(&models.RequestLog{}, "completion_tokens") { | ||
| if err := db.Migrator().AddColumn(&models.RequestLog{}, "completion_tokens"); err != nil { | ||
| return err | ||
| } | ||
| logrus.Info("Added column completion_tokens to request_logs") | ||
| } | ||
| if !db.Migrator().HasColumn(&models.RequestLog{}, "total_tokens") { | ||
| if err := db.Migrator().AddColumn(&models.RequestLog{}, "total_tokens"); err != nil { | ||
| return err | ||
| } | ||
| logrus.Info("Added column total_tokens to request_logs") | ||
| } | ||
| if !db.Migrator().HasColumn(&models.RequestLog{}, "token_cost_usd") { | ||
| if err := db.Migrator().AddColumn(&models.RequestLog{}, "token_cost_usd"); err != nil { | ||
| return err | ||
| } | ||
| logrus.Info("Added column token_cost_usd to request_logs") | ||
| } | ||
| return nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| package handler | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "strings" | ||
|
|
||
| "gpt-load/internal/models" | ||
|
|
||
| "github.com/gin-gonic/gin" | ||
| "github.com/sirupsen/logrus" | ||
| ) | ||
|
|
||
| // Metrics returns a Prometheus-text /metrics endpoint exposing token usage | ||
| // and request counts aggregated from request_logs. | ||
| // | ||
| // This is deliberately kept minimal — a full Prometheus client library is not | ||
| // introduced. The output format follows the Prometheus exposition format so | ||
| // operators can scrape it with any standard Prometheus server and build | ||
| // dashboards (e.g. Grafana) on top. | ||
| func (s *Server) Metrics(c *gin.Context) { | ||
| var results []struct { | ||
| GroupName string | ||
| Model string | ||
| TotalRequests int64 | ||
| TotalTokens int64 | ||
| TotalCost float64 | ||
| TotalPrompt int64 | ||
| TotalCompletion int64 | ||
| } | ||
|
|
||
| // Aggregate token usage and request count from successful non-streaming | ||
| // requests (those are the ones where we can extract usage data). | ||
| if err := s.DB.Model(&models.RequestLog{}). | ||
| Select(`COALESCE(group_name, '') as group_name, | ||
| COALESCE(model, 'unknown') as model, | ||
| COUNT(*) as total_requests, | ||
| COALESCE(SUM(total_tokens), 0) as total_tokens, | ||
| COALESCE(SUM(token_cost_usd), 0) as total_cost, | ||
| COALESCE(SUM(prompt_tokens), 0) as total_prompt, | ||
| COALESCE(SUM(completion_tokens), 0) as total_completion`). | ||
| Where("is_success = ? AND is_stream = ?", true, false). | ||
| Group("group_name, model"). | ||
| Scan(&results).Error; err != nil { | ||
| logrus.WithError(err).Error("Failed to query metrics") | ||
| c.String(500, "internal error\n") | ||
| return | ||
| } | ||
|
|
||
| var sb strings.Builder | ||
| sb.WriteString("# HELP gpt_load_requests_total Total number of successful proxy requests by group and model\n") | ||
| sb.WriteString("# TYPE gpt_load_requests_total counter\n") | ||
| for _, r := range results { | ||
| sb.WriteString(fmt.Sprintf( | ||
| `gpt_load_requests_total{group=%q,model=%q} %d`+"\n", | ||
| r.GroupName, r.Model, r.TotalRequests, | ||
| )) | ||
| } | ||
|
|
||
| sb.WriteString("\n# HELP gpt_load_tokens_total Total token count by type, group, and model\n") | ||
| sb.WriteString("# TYPE gpt_load_tokens_total counter\n") | ||
| for _, r := range results { | ||
| if r.TotalPrompt > 0 { | ||
| sb.WriteString(fmt.Sprintf( | ||
| `gpt_load_tokens_total{type="prompt",group=%q,model=%q} %d`+"\n", | ||
| r.GroupName, r.Model, r.TotalPrompt, | ||
| )) | ||
| } | ||
| if r.TotalCompletion > 0 { | ||
| sb.WriteString(fmt.Sprintf( | ||
| `gpt_load_tokens_total{type="completion",group=%q,model=%q} %d`+"\n", | ||
| r.GroupName, r.Model, r.TotalCompletion, | ||
| )) | ||
| } | ||
| if r.TotalTokens > 0 { | ||
| sb.WriteString(fmt.Sprintf( | ||
| `gpt_load_tokens_total{type="total",group=%q,model=%q} %d`+"\n", | ||
| r.GroupName, r.Model, r.TotalTokens, | ||
| )) | ||
| } | ||
| } | ||
|
|
||
| sb.WriteString("\n# HELP gpt_load_cost_total Total cost in USD by group and model\n") | ||
| sb.WriteString("# TYPE gpt_load_cost_total counter\n") | ||
| for _, r := range results { | ||
| if r.TotalCost > 0 { | ||
| sb.WriteString(fmt.Sprintf( | ||
| `gpt_load_cost_total{group=%q,model=%q} %.6f`+"\n", | ||
| r.GroupName, r.Model, r.TotalCost, | ||
| )) | ||
| } | ||
| } | ||
|
|
||
| c.Header("Content-Type", "text/plain; charset=utf-8") | ||
| c.String(200, sb.String()) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.