@@ -4,17 +4,22 @@ import (
44 "chat/channel"
55 "database/sql"
66 "fmt"
7+
8+ "chat/globals"
9+ "chat/utils"
10+
711 "github.com/go-redis/redis/v8"
812)
913
1014const (
1115 ErrNotAuthenticated = "not authenticated error (model: %s)"
1216 ErrNotSetPrice = "the price of the model is not set (model: %s)"
1317 ErrNotEnoughQuota = "user quota is not enough error (model: %s, minimum quota: %0.2f, your quota: %0.2f)"
18+ ErrEstimatedCost = "estimated cost exceeds user quota (model: %s, estimated cost: %0.2f, your quota: %0.2f)"
1419)
1520
1621// CanEnableModel returns whether the model can be enabled (without subscription)
17- func CanEnableModel (db * sql.DB , user * User , model string ) error {
22+ func CanEnableModel (db * sql.DB , user * User , model string , messages []globals. Message ) error {
1823 isAuth := user != nil
1924 isAdmin := isAuth && user .IsAdmin (db )
2025
@@ -37,21 +42,23 @@ func CanEnableModel(db *sql.DB, user *User, model string) error {
3742 return fmt .Errorf (ErrNotAuthenticated , model )
3843 }
3944
40- // return if the user is authenticated and has enough quota
41- limit := charge .GetLimit ()
45+ // Calculate estimated input cost
46+ inputTokens := utils .NumTokensFromMessages (messages , model , false )
47+ estimatedInputCost := float32 (inputTokens ) / 1000 * charge .GetInput ()
4248
49+ // Get user's current quota
4350 quota := user .GetQuota (db )
44- if quota < limit {
45- return fmt .Errorf (ErrNotEnoughQuota , model , limit , quota )
51+ if quota < estimatedInputCost {
52+ return fmt .Errorf (ErrEstimatedCost , model , estimatedInputCost , quota )
4653 }
4754
4855 return nil
4956}
5057
51- func CanEnableModelWithSubscription (db * sql.DB , cache * redis.Client , user * User , model string ) (canEnable error , usePlan bool ) {
58+ func CanEnableModelWithSubscription (db * sql.DB , cache * redis.Client , user * User , model string , messages []globals. Message ) (canEnable error , usePlan bool ) {
5259 // use subscription quota first
5360 if user != nil && HandleSubscriptionUsage (db , cache , user , model ) {
5461 return nil , true
5562 }
56- return CanEnableModel (db , user , model ), false
63+ return CanEnableModel (db , user , model , messages ), false
5764}
0 commit comments