fix(openai): preserve cache-write TTLs in usage and billing

This commit is contained in:
r266-tech committed 2026-11-08 22:00:15 +08:00
1 parent 6b4b37db43
commit fe093d76bd
62 files changed
+1472 -205

No files matched your search

+16 -14
View File
@@ -1655,6 +1655,8 @@ var (
{Name: "cache_read_tokens", Type: field.TypeInt, Default: 0},
{Name: "cache_creation_5m_tokens", Type: field.TypeInt, Default: 0},
{Name: "cache_creation_1h_tokens", Type: field.TypeInt, Default: 0},
{Name: "cache_creation_30m_tokens", Type: field.TypeInt, Default: 0},
{Name: "cache_creation_12h_tokens", Type: field.TypeInt, Default: 0},
{Name: "input_cost", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,10)"}},
{Name: "output_cost", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,10)"}},
{Name: "cache_creation_cost", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,10)"}},
@@ -1695,31 +1697,31 @@ var (
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "usage_logs_api_keys_usage_logs",
Columns: []*schema.Column{UsageLogsColumns[43]},
Columns: []*schema.Column{UsageLogsColumns[45]},
RefColumns: []*schema.Column{APIKeysColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "usage_logs_accounts_usage_logs",
Columns: []*schema.Column{UsageLogsColumns[44]},
Columns: []*schema.Column{UsageLogsColumns[46]},
RefColumns: []*schema.Column{AccountsColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "usage_logs_groups_usage_logs",
Columns: []*schema.Column{UsageLogsColumns[45]},
Columns: []*schema.Column{UsageLogsColumns[47]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.SetNull,
},
{
Symbol: "usage_logs_users_usage_logs",
Columns: []*schema.Column{UsageLogsColumns[46]},
Columns: []*schema.Column{UsageLogsColumns[48]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "usage_logs_user_subscriptions_usage_logs",
Columns: []*schema.Column{UsageLogsColumns[47]},
Columns: []*schema.Column{UsageLogsColumns[49]},
RefColumns: []*schema.Column{UserSubscriptionsColumns[0]},
OnDelete: schema.SetNull,
},
@@ -1728,32 +1730,32 @@ var (
{
Name: "usagelog_user_id",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[46]},
Columns: []*schema.Column{UsageLogsColumns[48]},
},
{
Name: "usagelog_api_key_id",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[43]},
Columns: []*schema.Column{UsageLogsColumns[45]},
},
{
Name: "usagelog_account_id",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[44]},
Columns: []*schema.Column{UsageLogsColumns[46]},
},
{
Name: "usagelog_group_id",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[45]},
Columns: []*schema.Column{UsageLogsColumns[47]},
},
{
Name: "usagelog_subscription_id",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[47]},
Columns: []*schema.Column{UsageLogsColumns[49]},
},
{
Name: "usagelog_created_at",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[42]},
Columns: []*schema.Column{UsageLogsColumns[44]},
},
{
Name: "usagelog_model",
@@ -1773,17 +1775,17 @@ var (
{
Name: "usagelog_user_id_created_at",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[46], UsageLogsColumns[42]},
Columns: []*schema.Column{UsageLogsColumns[48], UsageLogsColumns[44]},
},
{
Name: "usagelog_api_key_id_created_at",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[43], UsageLogsColumns[42]},
Columns: []*schema.Column{UsageLogsColumns[45], UsageLogsColumns[44]},
},
{
Name: "usagelog_group_id_created_at",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[45], UsageLogsColumns[42]},
Columns: []*schema.Column{UsageLogsColumns[47], UsageLogsColumns[44]},
},
},
}
+175 -1
View File
@@ -44748,6 +44748,10 @@ type UsageLogMutation struct {
addcache_creation_5m_tokens *int
cache_creation_1h_tokens *int
addcache_creation_1h_tokens *int
cache_creation_30m_tokens *int
addcache_creation_30m_tokens *int
cache_creation_12h_tokens *int
addcache_creation_12h_tokens *int
input_cost *float64
addinput_cost *float64
output_cost *float64
@@ -45929,6 +45933,118 @@ func (m *UsageLogMutation) ResetCacheCreation1hTokens() {
m.addcache_creation_1h_tokens = nil
}
// SetCacheCreation30mTokens sets the "cache_creation_30m_tokens" field.
func (m *UsageLogMutation) SetCacheCreation30mTokens(i int) {
m.cache_creation_30m_tokens = &i
m.addcache_creation_30m_tokens = nil
}
// CacheCreation30mTokens returns the value of the "cache_creation_30m_tokens" field in the mutation.
func (m *UsageLogMutation) CacheCreation30mTokens() (r int, exists bool) {
v := m.cache_creation_30m_tokens
if v == nil {
return
}
return *v, true
}
// OldCacheCreation30mTokens returns the old "cache_creation_30m_tokens" field's value of the UsageLog entity.
// If the UsageLog object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UsageLogMutation) OldCacheCreation30mTokens(ctx context.Context) (v int, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCacheCreation30mTokens is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCacheCreation30mTokens requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCacheCreation30mTokens: %w", err)
}
return oldValue.CacheCreation30mTokens, nil
}
// AddCacheCreation30mTokens adds i to the "cache_creation_30m_tokens" field.
func (m *UsageLogMutation) AddCacheCreation30mTokens(i int) {
if m.addcache_creation_30m_tokens != nil {
*m.addcache_creation_30m_tokens += i
} else {
m.addcache_creation_30m_tokens = &i
}
}
// AddedCacheCreation30mTokens returns the value that was added to the "cache_creation_30m_tokens" field in this mutation.
func (m *UsageLogMutation) AddedCacheCreation30mTokens() (r int, exists bool) {
v := m.addcache_creation_30m_tokens
if v == nil {
return
}
return *v, true
}
// ResetCacheCreation30mTokens resets all changes to the "cache_creation_30m_tokens" field.
func (m *UsageLogMutation) ResetCacheCreation30mTokens() {
m.cache_creation_30m_tokens = nil
m.addcache_creation_30m_tokens = nil
}
// SetCacheCreation12hTokens sets the "cache_creation_12h_tokens" field.
func (m *UsageLogMutation) SetCacheCreation12hTokens(i int) {
m.cache_creation_12h_tokens = &i
m.addcache_creation_12h_tokens = nil
}
// CacheCreation12hTokens returns the value of the "cache_creation_12h_tokens" field in the mutation.
func (m *UsageLogMutation) CacheCreation12hTokens() (r int, exists bool) {
v := m.cache_creation_12h_tokens
if v == nil {
return
}
return *v, true
}
// OldCacheCreation12hTokens returns the old "cache_creation_12h_tokens" field's value of the UsageLog entity.
// If the UsageLog object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UsageLogMutation) OldCacheCreation12hTokens(ctx context.Context) (v int, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCacheCreation12hTokens is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCacheCreation12hTokens requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCacheCreation12hTokens: %w", err)
}
return oldValue.CacheCreation12hTokens, nil
}
// AddCacheCreation12hTokens adds i to the "cache_creation_12h_tokens" field.
func (m *UsageLogMutation) AddCacheCreation12hTokens(i int) {
if m.addcache_creation_12h_tokens != nil {
*m.addcache_creation_12h_tokens += i
} else {
m.addcache_creation_12h_tokens = &i
}
}
// AddedCacheCreation12hTokens returns the value that was added to the "cache_creation_12h_tokens" field in this mutation.
func (m *UsageLogMutation) AddedCacheCreation12hTokens() (r int, exists bool) {
v := m.addcache_creation_12h_tokens
if v == nil {
return
}
return *v, true
}
// ResetCacheCreation12hTokens resets all changes to the "cache_creation_12h_tokens" field.
func (m *UsageLogMutation) ResetCacheCreation12hTokens() {
m.cache_creation_12h_tokens = nil
m.addcache_creation_12h_tokens = nil
}
// SetInputCost sets the "input_cost" field.
func (m *UsageLogMutation) SetInputCost(f float64) {
m.input_cost = &f
@@ -47474,7 +47590,7 @@ func (m *UsageLogMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *UsageLogMutation) Fields() []string {
fields := make([]string, 0, 47)
fields := make([]string, 0, 49)
if m.user != nil {
fields = append(fields, usagelog.FieldUserID)
}
@@ -47538,6 +47654,12 @@ func (m *UsageLogMutation) Fields() []string {
if m.cache_creation_1h_tokens != nil {
fields = append(fields, usagelog.FieldCacheCreation1hTokens)
}
if m.cache_creation_30m_tokens != nil {
fields = append(fields, usagelog.FieldCacheCreation30mTokens)
}
if m.cache_creation_12h_tokens != nil {
fields = append(fields, usagelog.FieldCacheCreation12hTokens)
}
if m.input_cost != nil {
fields = append(fields, usagelog.FieldInputCost)
}
@@ -47666,6 +47788,10 @@ func (m *UsageLogMutation) Field(name string) (ent.Value, bool) {
return m.CacheCreation5mTokens()
case usagelog.FieldCacheCreation1hTokens:
return m.CacheCreation1hTokens()
case usagelog.FieldCacheCreation30mTokens:
return m.CacheCreation30mTokens()
case usagelog.FieldCacheCreation12hTokens:
return m.CacheCreation12hTokens()
case usagelog.FieldInputCost:
return m.InputCost()
case usagelog.FieldOutputCost:
@@ -47769,6 +47895,10 @@ func (m *UsageLogMutation) OldField(ctx context.Context, name string) (ent.Value
return m.OldCacheCreation5mTokens(ctx)
case usagelog.FieldCacheCreation1hTokens:
return m.OldCacheCreation1hTokens(ctx)
case usagelog.FieldCacheCreation30mTokens:
return m.OldCacheCreation30mTokens(ctx)
case usagelog.FieldCacheCreation12hTokens:
return m.OldCacheCreation12hTokens(ctx)
case usagelog.FieldInputCost:
return m.OldInputCost(ctx)
case usagelog.FieldOutputCost:
@@ -47977,6 +48107,20 @@ func (m *UsageLogMutation) SetField(name string, value ent.Value) error {
}
m.SetCacheCreation1hTokens(v)
return nil
case usagelog.FieldCacheCreation30mTokens:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCacheCreation30mTokens(v)
return nil
case usagelog.FieldCacheCreation12hTokens:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCacheCreation12hTokens(v)
return nil
case usagelog.FieldInputCost:
v, ok := value.(float64)
if !ok {
@@ -48188,6 +48332,12 @@ func (m *UsageLogMutation) AddedFields() []string {
if m.addcache_creation_1h_tokens != nil {
fields = append(fields, usagelog.FieldCacheCreation1hTokens)
}
if m.addcache_creation_30m_tokens != nil {
fields = append(fields, usagelog.FieldCacheCreation30mTokens)
}
if m.addcache_creation_12h_tokens != nil {
fields = append(fields, usagelog.FieldCacheCreation12hTokens)
}
if m.addinput_cost != nil {
fields = append(fields, usagelog.FieldInputCost)
}
@@ -48252,6 +48402,10 @@ func (m *UsageLogMutation) AddedField(name string) (ent.Value, bool) {
return m.AddedCacheCreation5mTokens()
case usagelog.FieldCacheCreation1hTokens:
return m.AddedCacheCreation1hTokens()
case usagelog.FieldCacheCreation30mTokens:
return m.AddedCacheCreation30mTokens()
case usagelog.FieldCacheCreation12hTokens:
return m.AddedCacheCreation12hTokens()
case usagelog.FieldInputCost:
return m.AddedInputCost()
case usagelog.FieldOutputCost:
@@ -48338,6 +48492,20 @@ func (m *UsageLogMutation) AddField(name string, value ent.Value) error {
}
m.AddCacheCreation1hTokens(v)
return nil
case usagelog.FieldCacheCreation30mTokens:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddCacheCreation30mTokens(v)
return nil
case usagelog.FieldCacheCreation12hTokens:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddCacheCreation12hTokens(v)
return nil
case usagelog.FieldInputCost:
v, ok := value.(float64)
if !ok {
@@ -48661,6 +48829,12 @@ func (m *UsageLogMutation) ResetField(name string) error {
case usagelog.FieldCacheCreation1hTokens:
m.ResetCacheCreation1hTokens()
return nil
case usagelog.FieldCacheCreation30mTokens:
m.ResetCacheCreation30mTokens()
return nil
case usagelog.FieldCacheCreation12hTokens:
m.ResetCacheCreation12hTokens()
return nil
case usagelog.FieldInputCost:
m.ResetInputCost()
return nil
+29 -21
View File
@@ -2078,88 +2078,96 @@ func init() {
usagelogDescCacheCreation1hTokens := usagelogFields[20].Descriptor()
// usagelog.DefaultCacheCreation1hTokens holds the default value on creation for the cache_creation_1h_tokens field.
usagelog.DefaultCacheCreation1hTokens = usagelogDescCacheCreation1hTokens.Default.(int)
// usagelogDescCacheCreation30mTokens is the schema descriptor for cache_creation_30m_tokens field.
usagelogDescCacheCreation30mTokens := usagelogFields[21].Descriptor()
// usagelog.DefaultCacheCreation30mTokens holds the default value on creation for the cache_creation_30m_tokens field.
usagelog.DefaultCacheCreation30mTokens = usagelogDescCacheCreation30mTokens.Default.(int)
// usagelogDescCacheCreation12hTokens is the schema descriptor for cache_creation_12h_tokens field.
usagelogDescCacheCreation12hTokens := usagelogFields[22].Descriptor()
// usagelog.DefaultCacheCreation12hTokens holds the default value on creation for the cache_creation_12h_tokens field.
usagelog.DefaultCacheCreation12hTokens = usagelogDescCacheCreation12hTokens.Default.(int)
// usagelogDescInputCost is the schema descriptor for input_cost field.
usagelogDescInputCost := usagelogFields[21].Descriptor()
usagelogDescInputCost := usagelogFields[23].Descriptor()
// usagelog.DefaultInputCost holds the default value on creation for the input_cost field.
usagelog.DefaultInputCost = usagelogDescInputCost.Default.(float64)
// usagelogDescOutputCost is the schema descriptor for output_cost field.
usagelogDescOutputCost := usagelogFields[22].Descriptor()
usagelogDescOutputCost := usagelogFields[24].Descriptor()
// usagelog.DefaultOutputCost holds the default value on creation for the output_cost field.
usagelog.DefaultOutputCost = usagelogDescOutputCost.Default.(float64)
// usagelogDescCacheCreationCost is the schema descriptor for cache_creation_cost field.
usagelogDescCacheCreationCost := usagelogFields[23].Descriptor()
usagelogDescCacheCreationCost := usagelogFields[25].Descriptor()
// usagelog.DefaultCacheCreationCost holds the default value on creation for the cache_creation_cost field.
usagelog.DefaultCacheCreationCost = usagelogDescCacheCreationCost.Default.(float64)
// usagelogDescCacheReadCost is the schema descriptor for cache_read_cost field.
usagelogDescCacheReadCost := usagelogFields[24].Descriptor()
usagelogDescCacheReadCost := usagelogFields[26].Descriptor()
// usagelog.DefaultCacheReadCost holds the default value on creation for the cache_read_cost field.
usagelog.DefaultCacheReadCost = usagelogDescCacheReadCost.Default.(float64)
// usagelogDescTotalCost is the schema descriptor for total_cost field.
usagelogDescTotalCost := usagelogFields[25].Descriptor()
usagelogDescTotalCost := usagelogFields[27].Descriptor()
// usagelog.DefaultTotalCost holds the default value on creation for the total_cost field.
usagelog.DefaultTotalCost = usagelogDescTotalCost.Default.(float64)
// usagelogDescActualCost is the schema descriptor for actual_cost field.
usagelogDescActualCost := usagelogFields[26].Descriptor()
usagelogDescActualCost := usagelogFields[28].Descriptor()
// usagelog.DefaultActualCost holds the default value on creation for the actual_cost field.
usagelog.DefaultActualCost = usagelogDescActualCost.Default.(float64)
// usagelogDescRateMultiplier is the schema descriptor for rate_multiplier field.
usagelogDescRateMultiplier := usagelogFields[27].Descriptor()
usagelogDescRateMultiplier := usagelogFields[29].Descriptor()
// usagelog.DefaultRateMultiplier holds the default value on creation for the rate_multiplier field.
usagelog.DefaultRateMultiplier = usagelogDescRateMultiplier.Default.(float64)
// usagelogDescLongContextBillingApplied is the schema descriptor for long_context_billing_applied field.
usagelogDescLongContextBillingApplied := usagelogFields[28].Descriptor()
usagelogDescLongContextBillingApplied := usagelogFields[30].Descriptor()
// usagelog.DefaultLongContextBillingApplied holds the default value on creation for the long_context_billing_applied field.
usagelog.DefaultLongContextBillingApplied = usagelogDescLongContextBillingApplied.Default.(bool)
// usagelogDescBillingType is the schema descriptor for billing_type field.
usagelogDescBillingType := usagelogFields[30].Descriptor()
usagelogDescBillingType := usagelogFields[32].Descriptor()
// usagelog.DefaultBillingType holds the default value on creation for the billing_type field.
usagelog.DefaultBillingType = usagelogDescBillingType.Default.(int8)
// usagelogDescStream is the schema descriptor for stream field.
usagelogDescStream := usagelogFields[31].Descriptor()
usagelogDescStream := usagelogFields[33].Descriptor()
// usagelog.DefaultStream holds the default value on creation for the stream field.
usagelog.DefaultStream = usagelogDescStream.Default.(bool)
// usagelogDescUserAgent is the schema descriptor for user_agent field.
usagelogDescUserAgent := usagelogFields[34].Descriptor()
usagelogDescUserAgent := usagelogFields[36].Descriptor()
// usagelog.UserAgentValidator is a validator for the "user_agent" field. It is called by the builders before save.
usagelog.UserAgentValidator = usagelogDescUserAgent.Validators[0].(func(string) error)
// usagelogDescIPAddress is the schema descriptor for ip_address field.
usagelogDescIPAddress := usagelogFields[35].Descriptor()
usagelogDescIPAddress := usagelogFields[37].Descriptor()
// usagelog.IPAddressValidator is a validator for the "ip_address" field. It is called by the builders before save.
usagelog.IPAddressValidator = usagelogDescIPAddress.Validators[0].(func(string) error)
// usagelogDescImageCount is the schema descriptor for image_count field.
usagelogDescImageCount := usagelogFields[36].Descriptor()
usagelogDescImageCount := usagelogFields[38].Descriptor()
// usagelog.DefaultImageCount holds the default value on creation for the image_count field.
usagelog.DefaultImageCount = usagelogDescImageCount.Default.(int)
// usagelogDescImageSize is the schema descriptor for image_size field.
usagelogDescImageSize := usagelogFields[37].Descriptor()
usagelogDescImageSize := usagelogFields[39].Descriptor()
// usagelog.ImageSizeValidator is a validator for the "image_size" field. It is called by the builders before save.
usagelog.ImageSizeValidator = usagelogDescImageSize.Validators[0].(func(string) error)
// usagelogDescImageInputSize is the schema descriptor for image_input_size field.
usagelogDescImageInputSize := usagelogFields[38].Descriptor()
usagelogDescImageInputSize := usagelogFields[40].Descriptor()
// usagelog.ImageInputSizeValidator is a validator for the "image_input_size" field. It is called by the builders before save.
usagelog.ImageInputSizeValidator = usagelogDescImageInputSize.Validators[0].(func(string) error)
// usagelogDescImageOutputSize is the schema descriptor for image_output_size field.
usagelogDescImageOutputSize := usagelogFields[39].Descriptor()
usagelogDescImageOutputSize := usagelogFields[41].Descriptor()
// usagelog.ImageOutputSizeValidator is a validator for the "image_output_size" field. It is called by the builders before save.
usagelog.ImageOutputSizeValidator = usagelogDescImageOutputSize.Validators[0].(func(string) error)
// usagelogDescImageSizeSource is the schema descriptor for image_size_source field.
usagelogDescImageSizeSource := usagelogFields[40].Descriptor()
usagelogDescImageSizeSource := usagelogFields[42].Descriptor()
// usagelog.ImageSizeSourceValidator is a validator for the "image_size_source" field. It is called by the builders before save.
usagelog.ImageSizeSourceValidator = usagelogDescImageSizeSource.Validators[0].(func(string) error)
// usagelogDescVideoCount is the schema descriptor for video_count field.
usagelogDescVideoCount := usagelogFields[42].Descriptor()
usagelogDescVideoCount := usagelogFields[44].Descriptor()
// usagelog.DefaultVideoCount holds the default value on creation for the video_count field.
usagelog.DefaultVideoCount = usagelogDescVideoCount.Default.(int)
// usagelogDescVideoResolution is the schema descriptor for video_resolution field.
usagelogDescVideoResolution := usagelogFields[43].Descriptor()
usagelogDescVideoResolution := usagelogFields[45].Descriptor()
// usagelog.VideoResolutionValidator is a validator for the "video_resolution" field. It is called by the builders before save.
usagelog.VideoResolutionValidator = usagelogDescVideoResolution.Validators[0].(func(string) error)
// usagelogDescCacheTTLOverridden is the schema descriptor for cache_ttl_overridden field.
usagelogDescCacheTTLOverridden := usagelogFields[45].Descriptor()
usagelogDescCacheTTLOverridden := usagelogFields[47].Descriptor()
// usagelog.DefaultCacheTTLOverridden holds the default value on creation for the cache_ttl_overridden field.
usagelog.DefaultCacheTTLOverridden = usagelogDescCacheTTLOverridden.Default.(bool)
// usagelogDescCreatedAt is the schema descriptor for created_at field.
usagelogDescCreatedAt := usagelogFields[46].Descriptor()
usagelogDescCreatedAt := usagelogFields[48].Descriptor()
// usagelog.DefaultCreatedAt holds the default value on creation for the created_at field.
usagelog.DefaultCreatedAt = usagelogDescCreatedAt.Default.(func() time.Time)
userMixin := schema.User{}.Mixin()
+4
View File
@@ -88,6 +88,10 @@ func (UsageLog) Fields() []ent.Field {
Default(0),
field.Int("cache_creation_1h_tokens").
Default(0),
field.Int("cache_creation_30m_tokens").
Default(0),
field.Int("cache_creation_12h_tokens").
Default(0),
// 成本字段
field.Float("input_cost").
+23 -1
View File
@@ -65,6 +65,10 @@ type UsageLog struct {
CacheCreation5mTokens int `json:"cache_creation_5m_tokens,omitempty"`
// CacheCreation1hTokens holds the value of the "cache_creation_1h_tokens" field.
CacheCreation1hTokens int `json:"cache_creation_1h_tokens,omitempty"`
// CacheCreation30mTokens holds the value of the "cache_creation_30m_tokens" field.
CacheCreation30mTokens int `json:"cache_creation_30m_tokens,omitempty"`
// CacheCreation12hTokens holds the value of the "cache_creation_12h_tokens" field.
CacheCreation12hTokens int `json:"cache_creation_12h_tokens,omitempty"`
// InputCost holds the value of the "input_cost" field.
InputCost float64 `json:"input_cost,omitempty"`
// OutputCost holds the value of the "output_cost" field.
@@ -206,7 +210,7 @@ func (*UsageLog) scanValues(columns []string) ([]any, error) {
values[i] = new(sql.NullBool)
case usagelog.FieldInputCost, usagelog.FieldOutputCost, usagelog.FieldCacheCreationCost, usagelog.FieldCacheReadCost, usagelog.FieldTotalCost, usagelog.FieldActualCost, usagelog.FieldRateMultiplier, usagelog.FieldAccountRateMultiplier:
values[i] = new(sql.NullFloat64)
case usagelog.FieldID, usagelog.FieldUserID, usagelog.FieldAPIKeyID, usagelog.FieldAccountID, usagelog.FieldChannelID, usagelog.FieldGroupID, usagelog.FieldSubscriptionID, usagelog.FieldInputTokens, usagelog.FieldOutputTokens, usagelog.FieldCacheCreationTokens, usagelog.FieldCacheReadTokens, usagelog.FieldCacheCreation5mTokens, usagelog.FieldCacheCreation1hTokens, usagelog.FieldBillingType, usagelog.FieldDurationMs, usagelog.FieldFirstTokenMs, usagelog.FieldImageCount, usagelog.FieldVideoCount, usagelog.FieldVideoDurationSeconds:
case usagelog.FieldID, usagelog.FieldUserID, usagelog.FieldAPIKeyID, usagelog.FieldAccountID, usagelog.FieldChannelID, usagelog.FieldGroupID, usagelog.FieldSubscriptionID, usagelog.FieldInputTokens, usagelog.FieldOutputTokens, usagelog.FieldCacheCreationTokens, usagelog.FieldCacheReadTokens, usagelog.FieldCacheCreation5mTokens, usagelog.FieldCacheCreation1hTokens, usagelog.FieldCacheCreation30mTokens, usagelog.FieldCacheCreation12hTokens, usagelog.FieldBillingType, usagelog.FieldDurationMs, usagelog.FieldFirstTokenMs, usagelog.FieldImageCount, usagelog.FieldVideoCount, usagelog.FieldVideoDurationSeconds:
values[i] = new(sql.NullInt64)
case usagelog.FieldRequestID, usagelog.FieldModel, usagelog.FieldRequestedModel, usagelog.FieldUpstreamModel, usagelog.FieldUpstreamResponseModel, usagelog.FieldModelMappingChain, usagelog.FieldBillingTier, usagelog.FieldBillingMode, usagelog.FieldUserAgent, usagelog.FieldIPAddress, usagelog.FieldImageSize, usagelog.FieldImageInputSize, usagelog.FieldImageOutputSize, usagelog.FieldImageSizeSource, usagelog.FieldVideoResolution:
values[i] = new(sql.NullString)
@@ -369,6 +373,18 @@ func (_m *UsageLog) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.CacheCreation1hTokens = int(value.Int64)
}
case usagelog.FieldCacheCreation30mTokens:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field cache_creation_30m_tokens", values[i])
} else if value.Valid {
_m.CacheCreation30mTokens = int(value.Int64)
}
case usagelog.FieldCacheCreation12hTokens:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field cache_creation_12h_tokens", values[i])
} else if value.Valid {
_m.CacheCreation12hTokens = int(value.Int64)
}
case usagelog.FieldInputCost:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field input_cost", values[i])
@@ -682,6 +698,12 @@ func (_m *UsageLog) String() string {
builder.WriteString("cache_creation_1h_tokens=")
builder.WriteString(fmt.Sprintf("%v", _m.CacheCreation1hTokens))
builder.WriteString(", ")
builder.WriteString("cache_creation_30m_tokens=")
builder.WriteString(fmt.Sprintf("%v", _m.CacheCreation30mTokens))
builder.WriteString(", ")
builder.WriteString("cache_creation_12h_tokens=")
builder.WriteString(fmt.Sprintf("%v", _m.CacheCreation12hTokens))
builder.WriteString(", ")
builder.WriteString("input_cost=")
builder.WriteString(fmt.Sprintf("%v", _m.InputCost))
builder.WriteString(", ")
+20
View File
@@ -56,6 +56,10 @@ const (
FieldCacheCreation5mTokens = "cache_creation_5m_tokens"
// FieldCacheCreation1hTokens holds the string denoting the cache_creation_1h_tokens field in the database.
FieldCacheCreation1hTokens = "cache_creation_1h_tokens"
// FieldCacheCreation30mTokens holds the string denoting the cache_creation_30m_tokens field in the database.
FieldCacheCreation30mTokens = "cache_creation_30m_tokens"
// FieldCacheCreation12hTokens holds the string denoting the cache_creation_12h_tokens field in the database.
FieldCacheCreation12hTokens = "cache_creation_12h_tokens"
// FieldInputCost holds the string denoting the input_cost field in the database.
FieldInputCost = "input_cost"
// FieldOutputCost holds the string denoting the output_cost field in the database.
@@ -181,6 +185,8 @@ var Columns = []string{
FieldCacheReadTokens,
FieldCacheCreation5mTokens,
FieldCacheCreation1hTokens,
FieldCacheCreation30mTokens,
FieldCacheCreation12hTokens,
FieldInputCost,
FieldOutputCost,
FieldCacheCreationCost,
@@ -248,6 +254,10 @@ var (
DefaultCacheCreation5mTokens int
// DefaultCacheCreation1hTokens holds the default value on creation for the "cache_creation_1h_tokens" field.
DefaultCacheCreation1hTokens int
// DefaultCacheCreation30mTokens holds the default value on creation for the "cache_creation_30m_tokens" field.
DefaultCacheCreation30mTokens int
// DefaultCacheCreation12hTokens holds the default value on creation for the "cache_creation_12h_tokens" field.
DefaultCacheCreation12hTokens int
// DefaultInputCost holds the default value on creation for the "input_cost" field.
DefaultInputCost float64
// DefaultOutputCost holds the default value on creation for the "output_cost" field.
@@ -405,6 +415,16 @@ func ByCacheCreation1hTokens(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCacheCreation1hTokens, opts...).ToFunc()
}
// ByCacheCreation30mTokens orders the results by the cache_creation_30m_tokens field.
func ByCacheCreation30mTokens(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCacheCreation30mTokens, opts...).ToFunc()
}
// ByCacheCreation12hTokens orders the results by the cache_creation_12h_tokens field.
func ByCacheCreation12hTokens(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCacheCreation12hTokens, opts...).ToFunc()
}
// ByInputCost orders the results by the input_cost field.
func ByInputCost(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldInputCost, opts...).ToFunc()
+90
View File
@@ -160,6 +160,16 @@ func CacheCreation1hTokens(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldCacheCreation1hTokens, v))
}
// CacheCreation30mTokens applies equality check predicate on the "cache_creation_30m_tokens" field. It's identical to CacheCreation30mTokensEQ.
func CacheCreation30mTokens(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldCacheCreation30mTokens, v))
}
// CacheCreation12hTokens applies equality check predicate on the "cache_creation_12h_tokens" field. It's identical to CacheCreation12hTokensEQ.
func CacheCreation12hTokens(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldCacheCreation12hTokens, v))
}
// InputCost applies equality check predicate on the "input_cost" field. It's identical to InputCostEQ.
func InputCost(v float64) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldInputCost, v))
@@ -1295,6 +1305,86 @@ func CacheCreation1hTokensLTE(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldLTE(FieldCacheCreation1hTokens, v))
}
// CacheCreation30mTokensEQ applies the EQ predicate on the "cache_creation_30m_tokens" field.
func CacheCreation30mTokensEQ(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldCacheCreation30mTokens, v))
}
// CacheCreation30mTokensNEQ applies the NEQ predicate on the "cache_creation_30m_tokens" field.
func CacheCreation30mTokensNEQ(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldNEQ(FieldCacheCreation30mTokens, v))
}
// CacheCreation30mTokensIn applies the In predicate on the "cache_creation_30m_tokens" field.
func CacheCreation30mTokensIn(vs ...int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldIn(FieldCacheCreation30mTokens, vs...))
}
// CacheCreation30mTokensNotIn applies the NotIn predicate on the "cache_creation_30m_tokens" field.
func CacheCreation30mTokensNotIn(vs ...int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldNotIn(FieldCacheCreation30mTokens, vs...))
}
// CacheCreation30mTokensGT applies the GT predicate on the "cache_creation_30m_tokens" field.
func CacheCreation30mTokensGT(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldGT(FieldCacheCreation30mTokens, v))
}
// CacheCreation30mTokensGTE applies the GTE predicate on the "cache_creation_30m_tokens" field.
func CacheCreation30mTokensGTE(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldGTE(FieldCacheCreation30mTokens, v))
}
// CacheCreation30mTokensLT applies the LT predicate on the "cache_creation_30m_tokens" field.
func CacheCreation30mTokensLT(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldLT(FieldCacheCreation30mTokens, v))
}
// CacheCreation30mTokensLTE applies the LTE predicate on the "cache_creation_30m_tokens" field.
func CacheCreation30mTokensLTE(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldLTE(FieldCacheCreation30mTokens, v))
}
// CacheCreation12hTokensEQ applies the EQ predicate on the "cache_creation_12h_tokens" field.
func CacheCreation12hTokensEQ(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldCacheCreation12hTokens, v))
}
// CacheCreation12hTokensNEQ applies the NEQ predicate on the "cache_creation_12h_tokens" field.
func CacheCreation12hTokensNEQ(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldNEQ(FieldCacheCreation12hTokens, v))
}
// CacheCreation12hTokensIn applies the In predicate on the "cache_creation_12h_tokens" field.
func CacheCreation12hTokensIn(vs ...int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldIn(FieldCacheCreation12hTokens, vs...))
}
// CacheCreation12hTokensNotIn applies the NotIn predicate on the "cache_creation_12h_tokens" field.
func CacheCreation12hTokensNotIn(vs ...int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldNotIn(FieldCacheCreation12hTokens, vs...))
}
// CacheCreation12hTokensGT applies the GT predicate on the "cache_creation_12h_tokens" field.
func CacheCreation12hTokensGT(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldGT(FieldCacheCreation12hTokens, v))
}
// CacheCreation12hTokensGTE applies the GTE predicate on the "cache_creation_12h_tokens" field.
func CacheCreation12hTokensGTE(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldGTE(FieldCacheCreation12hTokens, v))
}
// CacheCreation12hTokensLT applies the LT predicate on the "cache_creation_12h_tokens" field.
func CacheCreation12hTokensLT(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldLT(FieldCacheCreation12hTokens, v))
}
// CacheCreation12hTokensLTE applies the LTE predicate on the "cache_creation_12h_tokens" field.
func CacheCreation12hTokensLTE(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldLTE(FieldCacheCreation12hTokens, v))
}
// InputCostEQ applies the EQ predicate on the "input_cost" field.
func InputCostEQ(v float64) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldInputCost, v))
+170
View File
@@ -281,6 +281,34 @@ func (_c *UsageLogCreate) SetNillableCacheCreation1hTokens(v *int) *UsageLogCrea
return _c
}
// SetCacheCreation30mTokens sets the "cache_creation_30m_tokens" field.
func (_c *UsageLogCreate) SetCacheCreation30mTokens(v int) *UsageLogCreate {
_c.mutation.SetCacheCreation30mTokens(v)
return _c
}
// SetNillableCacheCreation30mTokens sets the "cache_creation_30m_tokens" field if the given value is not nil.
func (_c *UsageLogCreate) SetNillableCacheCreation30mTokens(v *int) *UsageLogCreate {
if v != nil {
_c.SetCacheCreation30mTokens(*v)
}
return _c
}
// SetCacheCreation12hTokens sets the "cache_creation_12h_tokens" field.
func (_c *UsageLogCreate) SetCacheCreation12hTokens(v int) *UsageLogCreate {
_c.mutation.SetCacheCreation12hTokens(v)
return _c
}
// SetNillableCacheCreation12hTokens sets the "cache_creation_12h_tokens" field if the given value is not nil.
func (_c *UsageLogCreate) SetNillableCacheCreation12hTokens(v *int) *UsageLogCreate {
if v != nil {
_c.SetCacheCreation12hTokens(*v)
}
return _c
}
// SetInputCost sets the "input_cost" field.
func (_c *UsageLogCreate) SetInputCost(v float64) *UsageLogCreate {
_c.mutation.SetInputCost(v)
@@ -721,6 +749,14 @@ func (_c *UsageLogCreate) defaults() {
v := usagelog.DefaultCacheCreation1hTokens
_c.mutation.SetCacheCreation1hTokens(v)
}
if _, ok := _c.mutation.CacheCreation30mTokens(); !ok {
v := usagelog.DefaultCacheCreation30mTokens
_c.mutation.SetCacheCreation30mTokens(v)
}
if _, ok := _c.mutation.CacheCreation12hTokens(); !ok {
v := usagelog.DefaultCacheCreation12hTokens
_c.mutation.SetCacheCreation12hTokens(v)
}
if _, ok := _c.mutation.InputCost(); !ok {
v := usagelog.DefaultInputCost
_c.mutation.SetInputCost(v)
@@ -854,6 +890,12 @@ func (_c *UsageLogCreate) check() error {
if _, ok := _c.mutation.CacheCreation1hTokens(); !ok {
return &ValidationError{Name: "cache_creation_1h_tokens", err: errors.New(`ent: missing required field "UsageLog.cache_creation_1h_tokens"`)}
}
if _, ok := _c.mutation.CacheCreation30mTokens(); !ok {
return &ValidationError{Name: "cache_creation_30m_tokens", err: errors.New(`ent: missing required field "UsageLog.cache_creation_30m_tokens"`)}
}
if _, ok := _c.mutation.CacheCreation12hTokens(); !ok {
return &ValidationError{Name: "cache_creation_12h_tokens", err: errors.New(`ent: missing required field "UsageLog.cache_creation_12h_tokens"`)}
}
if _, ok := _c.mutation.InputCost(); !ok {
return &ValidationError{Name: "input_cost", err: errors.New(`ent: missing required field "UsageLog.input_cost"`)}
}
@@ -1031,6 +1073,14 @@ func (_c *UsageLogCreate) createSpec() (*UsageLog, *sqlgraph.CreateSpec) {
_spec.SetField(usagelog.FieldCacheCreation1hTokens, field.TypeInt, value)
_node.CacheCreation1hTokens = value
}
if value, ok := _c.mutation.CacheCreation30mTokens(); ok {
_spec.SetField(usagelog.FieldCacheCreation30mTokens, field.TypeInt, value)
_node.CacheCreation30mTokens = value
}
if value, ok := _c.mutation.CacheCreation12hTokens(); ok {
_spec.SetField(usagelog.FieldCacheCreation12hTokens, field.TypeInt, value)
_node.CacheCreation12hTokens = value
}
if value, ok := _c.mutation.InputCost(); ok {
_spec.SetField(usagelog.FieldInputCost, field.TypeFloat64, value)
_node.InputCost = value
@@ -1626,6 +1676,42 @@ func (u *UsageLogUpsert) AddCacheCreation1hTokens(v int) *UsageLogUpsert {
return u
}
// SetCacheCreation30mTokens sets the "cache_creation_30m_tokens" field.
func (u *UsageLogUpsert) SetCacheCreation30mTokens(v int) *UsageLogUpsert {
u.Set(usagelog.FieldCacheCreation30mTokens, v)
return u
}
// UpdateCacheCreation30mTokens sets the "cache_creation_30m_tokens" field to the value that was provided on create.
func (u *UsageLogUpsert) UpdateCacheCreation30mTokens() *UsageLogUpsert {
u.SetExcluded(usagelog.FieldCacheCreation30mTokens)
return u
}
// AddCacheCreation30mTokens adds v to the "cache_creation_30m_tokens" field.
func (u *UsageLogUpsert) AddCacheCreation30mTokens(v int) *UsageLogUpsert {
u.Add(usagelog.FieldCacheCreation30mTokens, v)
return u
}
// SetCacheCreation12hTokens sets the "cache_creation_12h_tokens" field.
func (u *UsageLogUpsert) SetCacheCreation12hTokens(v int) *UsageLogUpsert {
u.Set(usagelog.FieldCacheCreation12hTokens, v)
return u
}
// UpdateCacheCreation12hTokens sets the "cache_creation_12h_tokens" field to the value that was provided on create.
func (u *UsageLogUpsert) UpdateCacheCreation12hTokens() *UsageLogUpsert {
u.SetExcluded(usagelog.FieldCacheCreation12hTokens)
return u
}
// AddCacheCreation12hTokens adds v to the "cache_creation_12h_tokens" field.
func (u *UsageLogUpsert) AddCacheCreation12hTokens(v int) *UsageLogUpsert {
u.Add(usagelog.FieldCacheCreation12hTokens, v)
return u
}
// SetInputCost sets the "input_cost" field.
func (u *UsageLogUpsert) SetInputCost(v float64) *UsageLogUpsert {
u.Set(usagelog.FieldInputCost, v)
@@ -2540,6 +2626,48 @@ func (u *UsageLogUpsertOne) UpdateCacheCreation1hTokens() *UsageLogUpsertOne {
})
}
// SetCacheCreation30mTokens sets the "cache_creation_30m_tokens" field.
func (u *UsageLogUpsertOne) SetCacheCreation30mTokens(v int) *UsageLogUpsertOne {
return u.Update(func(s *UsageLogUpsert) {
s.SetCacheCreation30mTokens(v)
})
}
// AddCacheCreation30mTokens adds v to the "cache_creation_30m_tokens" field.
func (u *UsageLogUpsertOne) AddCacheCreation30mTokens(v int) *UsageLogUpsertOne {
return u.Update(func(s *UsageLogUpsert) {
s.AddCacheCreation30mTokens(v)
})
}
// UpdateCacheCreation30mTokens sets the "cache_creation_30m_tokens" field to the value that was provided on create.
func (u *UsageLogUpsertOne) UpdateCacheCreation30mTokens() *UsageLogUpsertOne {
return u.Update(func(s *UsageLogUpsert) {
s.UpdateCacheCreation30mTokens()
})
}
// SetCacheCreation12hTokens sets the "cache_creation_12h_tokens" field.
func (u *UsageLogUpsertOne) SetCacheCreation12hTokens(v int) *UsageLogUpsertOne {
return u.Update(func(s *UsageLogUpsert) {
s.SetCacheCreation12hTokens(v)
})
}
// AddCacheCreation12hTokens adds v to the "cache_creation_12h_tokens" field.
func (u *UsageLogUpsertOne) AddCacheCreation12hTokens(v int) *UsageLogUpsertOne {
return u.Update(func(s *UsageLogUpsert) {
s.AddCacheCreation12hTokens(v)
})
}
// UpdateCacheCreation12hTokens sets the "cache_creation_12h_tokens" field to the value that was provided on create.
func (u *UsageLogUpsertOne) UpdateCacheCreation12hTokens() *UsageLogUpsertOne {
return u.Update(func(s *UsageLogUpsert) {
s.UpdateCacheCreation12hTokens()
})
}
// SetInputCost sets the "input_cost" field.
func (u *UsageLogUpsertOne) SetInputCost(v float64) *UsageLogUpsertOne {
return u.Update(func(s *UsageLogUpsert) {
@@ -3696,6 +3824,48 @@ func (u *UsageLogUpsertBulk) UpdateCacheCreation1hTokens() *UsageLogUpsertBulk {
})
}
// SetCacheCreation30mTokens sets the "cache_creation_30m_tokens" field.
func (u *UsageLogUpsertBulk) SetCacheCreation30mTokens(v int) *UsageLogUpsertBulk {
return u.Update(func(s *UsageLogUpsert) {
s.SetCacheCreation30mTokens(v)
})
}
// AddCacheCreation30mTokens adds v to the "cache_creation_30m_tokens" field.
func (u *UsageLogUpsertBulk) AddCacheCreation30mTokens(v int) *UsageLogUpsertBulk {
return u.Update(func(s *UsageLogUpsert) {
s.AddCacheCreation30mTokens(v)
})
}
// UpdateCacheCreation30mTokens sets the "cache_creation_30m_tokens" field to the value that was provided on create.
func (u *UsageLogUpsertBulk) UpdateCacheCreation30mTokens() *UsageLogUpsertBulk {
return u.Update(func(s *UsageLogUpsert) {
s.UpdateCacheCreation30mTokens()
})
}
// SetCacheCreation12hTokens sets the "cache_creation_12h_tokens" field.
func (u *UsageLogUpsertBulk) SetCacheCreation12hTokens(v int) *UsageLogUpsertBulk {
return u.Update(func(s *UsageLogUpsert) {
s.SetCacheCreation12hTokens(v)
})
}
// AddCacheCreation12hTokens adds v to the "cache_creation_12h_tokens" field.
func (u *UsageLogUpsertBulk) AddCacheCreation12hTokens(v int) *UsageLogUpsertBulk {
return u.Update(func(s *UsageLogUpsert) {
s.AddCacheCreation12hTokens(v)
})
}
// UpdateCacheCreation12hTokens sets the "cache_creation_12h_tokens" field to the value that was provided on create.
func (u *UsageLogUpsertBulk) UpdateCacheCreation12hTokens() *UsageLogUpsertBulk {
return u.Update(func(s *UsageLogUpsert) {
s.UpdateCacheCreation12hTokens()
})
}
// SetInputCost sets the "input_cost" field.
func (u *UsageLogUpsertBulk) SetInputCost(v float64) *UsageLogUpsertBulk {
return u.Update(func(s *UsageLogUpsert) {
+108
View File
@@ -435,6 +435,48 @@ func (_u *UsageLogUpdate) AddCacheCreation1hTokens(v int) *UsageLogUpdate {
return _u
}
// SetCacheCreation30mTokens sets the "cache_creation_30m_tokens" field.
func (_u *UsageLogUpdate) SetCacheCreation30mTokens(v int) *UsageLogUpdate {
_u.mutation.ResetCacheCreation30mTokens()
_u.mutation.SetCacheCreation30mTokens(v)
return _u
}
// SetNillableCacheCreation30mTokens sets the "cache_creation_30m_tokens" field if the given value is not nil.
func (_u *UsageLogUpdate) SetNillableCacheCreation30mTokens(v *int) *UsageLogUpdate {
if v != nil {
_u.SetCacheCreation30mTokens(*v)
}
return _u
}
// AddCacheCreation30mTokens adds value to the "cache_creation_30m_tokens" field.
func (_u *UsageLogUpdate) AddCacheCreation30mTokens(v int) *UsageLogUpdate {
_u.mutation.AddCacheCreation30mTokens(v)
return _u
}
// SetCacheCreation12hTokens sets the "cache_creation_12h_tokens" field.
func (_u *UsageLogUpdate) SetCacheCreation12hTokens(v int) *UsageLogUpdate {
_u.mutation.ResetCacheCreation12hTokens()
_u.mutation.SetCacheCreation12hTokens(v)
return _u
}
// SetNillableCacheCreation12hTokens sets the "cache_creation_12h_tokens" field if the given value is not nil.
func (_u *UsageLogUpdate) SetNillableCacheCreation12hTokens(v *int) *UsageLogUpdate {
if v != nil {
_u.SetCacheCreation12hTokens(*v)
}
return _u
}
// AddCacheCreation12hTokens adds value to the "cache_creation_12h_tokens" field.
func (_u *UsageLogUpdate) AddCacheCreation12hTokens(v int) *UsageLogUpdate {
_u.mutation.AddCacheCreation12hTokens(v)
return _u
}
// SetInputCost sets the "input_cost" field.
func (_u *UsageLogUpdate) SetInputCost(v float64) *UsageLogUpdate {
_u.mutation.ResetInputCost()
@@ -1228,6 +1270,18 @@ func (_u *UsageLogUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if value, ok := _u.mutation.AddedCacheCreation1hTokens(); ok {
_spec.AddField(usagelog.FieldCacheCreation1hTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.CacheCreation30mTokens(); ok {
_spec.SetField(usagelog.FieldCacheCreation30mTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedCacheCreation30mTokens(); ok {
_spec.AddField(usagelog.FieldCacheCreation30mTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.CacheCreation12hTokens(); ok {
_spec.SetField(usagelog.FieldCacheCreation12hTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedCacheCreation12hTokens(); ok {
_spec.AddField(usagelog.FieldCacheCreation12hTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.InputCost(); ok {
_spec.SetField(usagelog.FieldInputCost, field.TypeFloat64, value)
}
@@ -1949,6 +2003,48 @@ func (_u *UsageLogUpdateOne) AddCacheCreation1hTokens(v int) *UsageLogUpdateOne
return _u
}
// SetCacheCreation30mTokens sets the "cache_creation_30m_tokens" field.
func (_u *UsageLogUpdateOne) SetCacheCreation30mTokens(v int) *UsageLogUpdateOne {
_u.mutation.ResetCacheCreation30mTokens()
_u.mutation.SetCacheCreation30mTokens(v)
return _u
}
// SetNillableCacheCreation30mTokens sets the "cache_creation_30m_tokens" field if the given value is not nil.
func (_u *UsageLogUpdateOne) SetNillableCacheCreation30mTokens(v *int) *UsageLogUpdateOne {
if v != nil {
_u.SetCacheCreation30mTokens(*v)
}
return _u
}
// AddCacheCreation30mTokens adds value to the "cache_creation_30m_tokens" field.
func (_u *UsageLogUpdateOne) AddCacheCreation30mTokens(v int) *UsageLogUpdateOne {
_u.mutation.AddCacheCreation30mTokens(v)
return _u
}
// SetCacheCreation12hTokens sets the "cache_creation_12h_tokens" field.
func (_u *UsageLogUpdateOne) SetCacheCreation12hTokens(v int) *UsageLogUpdateOne {
_u.mutation.ResetCacheCreation12hTokens()
_u.mutation.SetCacheCreation12hTokens(v)
return _u
}
// SetNillableCacheCreation12hTokens sets the "cache_creation_12h_tokens" field if the given value is not nil.
func (_u *UsageLogUpdateOne) SetNillableCacheCreation12hTokens(v *int) *UsageLogUpdateOne {
if v != nil {
_u.SetCacheCreation12hTokens(*v)
}
return _u
}
// AddCacheCreation12hTokens adds value to the "cache_creation_12h_tokens" field.
func (_u *UsageLogUpdateOne) AddCacheCreation12hTokens(v int) *UsageLogUpdateOne {
_u.mutation.AddCacheCreation12hTokens(v)
return _u
}
// SetInputCost sets the "input_cost" field.
func (_u *UsageLogUpdateOne) SetInputCost(v float64) *UsageLogUpdateOne {
_u.mutation.ResetInputCost()
@@ -2772,6 +2868,18 @@ func (_u *UsageLogUpdateOne) sqlSave(ctx context.Context) (_node *UsageLog, err
if value, ok := _u.mutation.AddedCacheCreation1hTokens(); ok {
_spec.AddField(usagelog.FieldCacheCreation1hTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.CacheCreation30mTokens(); ok {
_spec.SetField(usagelog.FieldCacheCreation30mTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedCacheCreation30mTokens(); ok {
_spec.AddField(usagelog.FieldCacheCreation30mTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.CacheCreation12hTokens(); ok {
_spec.SetField(usagelog.FieldCacheCreation12hTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedCacheCreation12hTokens(); ok {
_spec.AddField(usagelog.FieldCacheCreation12hTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.InputCost(); ok {
_spec.SetField(usagelog.FieldInputCost, field.TypeFloat64, value)
}
+8
View File
@@ -329,6 +329,8 @@ github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27k
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-sqlite3 v1.14.17 h1:mCRHCLDUBXgpKAqIKsaAaAsrAlbkeomtRFKXh2L6YIM=
github.com/mattn/go-sqlite3 v1.14.17/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/mdelapenya/tlscert v0.2.0 h1:7H81W6Z/4weDvZBNOfQte5GpIMo0lGYEeWbkGp5LJHI=
@@ -369,6 +371,8 @@ github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJm
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA=
github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
@@ -403,6 +407,8 @@ github.com/refraction-networking/utls v1.8.2 h1:j4Q1gJj0xngdeH+Ox/qND11aEfhpgoEv
github.com/refraction-networking/utls v1.8.2/go.mod h1:jkSOEkLqn+S/jtpEHPOsVv/4V4EVnelwbMQl4vCWXAM=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
@@ -442,6 +448,8 @@ github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.18.2 h1:LUXCnvUvSM6FXAsj6nnfc8Q2tp1dIgUfY9Kc8GsSOiQ=
@@ -65,6 +65,7 @@ type channelModelPricingRequest struct {
OutputPrice *float64 `json:"output_price" binding:"omitempty,min=0"`
CacheWritePrice *float64 `json:"cache_write_price" binding:"omitempty,min=0"`
CacheWrite1hPrice *float64 `json:"cache_write_1h_price" binding:"omitempty,min=0"`
CacheWrite12hPrice *float64 `json:"cache_write_12h_price" binding:"omitempty,min=0"`
CacheReadPrice *float64 `json:"cache_read_price" binding:"omitempty,min=0"`
FastMultiplier *float64 `json:"fast_multiplier" binding:"omitempty,gt=0"`
FlexMultiplier *float64 `json:"flex_multiplier" binding:"omitempty,gt=0"`
@@ -96,6 +97,7 @@ type pricingIntervalRequest struct {
OutputPrice *float64 `json:"output_price"`
CacheWritePrice *float64 `json:"cache_write_price"`
CacheWrite1hPrice *float64 `json:"cache_write_1h_price"`
CacheWrite12hPrice *float64 `json:"cache_write_12h_price"`
CacheReadPrice *float64 `json:"cache_read_price"`
InputMultiplier *float64 `json:"input_multiplier" binding:"omitempty,gt=0"`
OutputMultiplier *float64 `json:"output_multiplier" binding:"omitempty,gt=0"`
@@ -139,6 +141,7 @@ type channelModelPricingResponse struct {
OutputPrice *float64 `json:"output_price"`
CacheWritePrice *float64 `json:"cache_write_price"`
CacheWrite1hPrice *float64 `json:"cache_write_1h_price"`
CacheWrite12hPrice *float64 `json:"cache_write_12h_price"`
CacheReadPrice *float64 `json:"cache_read_price"`
FastMultiplier *float64 `json:"fast_multiplier"`
FlexMultiplier *float64 `json:"flex_multiplier"`
@@ -171,6 +174,7 @@ type pricingIntervalResponse struct {
OutputPrice *float64 `json:"output_price"`
CacheWritePrice *float64 `json:"cache_write_price"`
CacheWrite1hPrice *float64 `json:"cache_write_1h_price"`
CacheWrite12hPrice *float64 `json:"cache_write_12h_price"`
CacheReadPrice *float64 `json:"cache_read_price"`
InputMultiplier *float64 `json:"input_multiplier"`
OutputMultiplier *float64 `json:"output_multiplier"`
@@ -269,6 +273,7 @@ func pricingToResponse(p *service.ChannelModelPricing) channelModelPricingRespon
OutputPrice: p.OutputPrice,
CacheWritePrice: p.CacheWritePrice,
CacheWrite1hPrice: p.CacheWrite1hPrice,
CacheWrite12hPrice: p.CacheWrite12hPrice,
CacheReadPrice: p.CacheReadPrice,
FastMultiplier: p.FastMultiplier,
FlexMultiplier: p.FlexMultiplier,
@@ -310,6 +315,7 @@ func intervalToResponse(iv service.PricingInterval) pricingIntervalResponse {
OutputPrice: iv.OutputPrice,
CacheWritePrice: iv.CacheWritePrice,
CacheWrite1hPrice: iv.CacheWrite1hPrice,
CacheWrite12hPrice: iv.CacheWrite12hPrice,
CacheReadPrice: iv.CacheReadPrice,
InputMultiplier: iv.InputMultiplier,
OutputMultiplier: iv.OutputMultiplier,
@@ -345,6 +351,7 @@ func pricingRequestToService(reqs []channelModelPricingRequest, allowChannelMult
OutputPrice: iv.OutputPrice,
CacheWritePrice: iv.CacheWritePrice,
CacheWrite1hPrice: iv.CacheWrite1hPrice,
CacheWrite12hPrice: iv.CacheWrite12hPrice,
CacheReadPrice: iv.CacheReadPrice,
InputMultiplier: inputMultiplier,
OutputMultiplier: outputMultiplier,
@@ -367,6 +374,7 @@ func pricingRequestToService(reqs []channelModelPricingRequest, allowChannelMult
OutputPrice: r.OutputPrice,
CacheWritePrice: r.CacheWritePrice,
CacheWrite1hPrice: r.CacheWrite1hPrice,
CacheWrite12hPrice: r.CacheWrite12hPrice,
CacheReadPrice: r.CacheReadPrice,
FastMultiplier: fastMultiplier,
FlexMultiplier: flexMultiplier,
@@ -625,6 +633,7 @@ func (h *ChannelHandler) GetModelDefaultPricing(c *gin.Context) {
"output_price": pricing.OutputPricePerToken,
"cache_write_price": cacheWritePrice,
"cache_write_1h_price": cacheWrite1hPrice,
"cache_write_12h_price": pricing.CacheCreation12hPricePerToken,
"cache_read_price": pricing.CacheReadPricePerToken,
"reasoning_effort_multipliers": pricing.ReasoningEffortMultipliers,
"image_input_price": pricing.ImageInputPricePerToken,
@@ -320,16 +320,17 @@ func TestPricingRequestToService_Defaults(t *testing.T) {
func TestPricingRequestToService_WithAllFields(t *testing.T) {
reqs := []channelModelPricingRequest{
{
Platform: "openai",
Models: []string{"gpt-4", "gpt-4o"},
BillingMode: "per_request",
InputPrice: float64Ptr(0.01),
OutputPrice: float64Ptr(0.03),
CacheWritePrice: float64Ptr(0.005),
CacheWrite1hPrice: float64Ptr(0.008),
CacheReadPrice: float64Ptr(0.002),
ImageOutputPrice: float64Ptr(0.04),
PerRequestPrice: float64Ptr(0.5),
Platform: "openai",
Models: []string{"gpt-4", "gpt-4o"},
BillingMode: "per_request",
InputPrice: float64Ptr(0.01),
OutputPrice: float64Ptr(0.03),
CacheWritePrice: float64Ptr(0.005),
CacheWrite1hPrice: float64Ptr(0.008),
CacheWrite12hPrice: float64Ptr(0.01),
CacheReadPrice: float64Ptr(0.002),
ImageOutputPrice: float64Ptr(0.04),
PerRequestPrice: float64Ptr(0.5),
},
}
@@ -343,6 +344,7 @@ func TestPricingRequestToService_WithAllFields(t *testing.T) {
require.Equal(t, float64Ptr(0.03), r.OutputPrice)
require.Equal(t, float64Ptr(0.005), r.CacheWritePrice)
require.Equal(t, float64Ptr(0.008), r.CacheWrite1hPrice)
require.Equal(t, float64Ptr(0.01), r.CacheWrite12hPrice)
require.Equal(t, float64Ptr(0.002), r.CacheReadPrice)
require.Equal(t, float64Ptr(0.04), r.ImageOutputPrice)
require.Equal(t, float64Ptr(0.5), r.PerRequestPrice)
@@ -355,16 +357,17 @@ func TestPricingRequestToService_WithIntervals(t *testing.T) {
BillingMode: "per_request",
Intervals: []pricingIntervalRequest{
{
MinTokens: 0,
MaxTokens: intPtr(2000),
TierLabel: "small",
InputPrice: float64Ptr(0.01),
OutputPrice: float64Ptr(0.02),
CacheWritePrice: float64Ptr(0.003),
CacheWrite1hPrice: float64Ptr(0.006),
CacheReadPrice: float64Ptr(0.001),
PerRequestPrice: float64Ptr(0.1),
SortOrder: 1,
MinTokens: 0,
MaxTokens: intPtr(2000),
TierLabel: "small",
InputPrice: float64Ptr(0.01),
OutputPrice: float64Ptr(0.02),
CacheWritePrice: float64Ptr(0.003),
CacheWrite1hPrice: float64Ptr(0.006),
CacheWrite12hPrice: float64Ptr(0),
CacheReadPrice: float64Ptr(0.001),
PerRequestPrice: float64Ptr(0.1),
SortOrder: 1,
},
{
MinTokens: 2000,
@@ -388,6 +391,7 @@ func TestPricingRequestToService_WithIntervals(t *testing.T) {
require.Equal(t, float64Ptr(0.02), iv0.OutputPrice)
require.Equal(t, float64Ptr(0.003), iv0.CacheWritePrice)
require.Equal(t, float64Ptr(0.006), iv0.CacheWrite1hPrice)
require.Equal(t, float64Ptr(0), iv0.CacheWrite12hPrice)
require.Equal(t, float64Ptr(0.001), iv0.CacheReadPrice)
require.Equal(t, float64Ptr(0.1), iv0.PerRequestPrice)
require.Equal(t, 1, iv0.SortOrder)
@@ -74,6 +74,7 @@ type userSupportedModelPricing struct {
OutputPrice *float64 `json:"output_price"`
CacheWritePrice *float64 `json:"cache_write_price"`
CacheWrite1hPrice *float64 `json:"cache_write_1h_price"`
CacheWrite12hPrice *float64 `json:"cache_write_12h_price"`
CacheReadPrice *float64 `json:"cache_read_price"`
ReasoningEffortMultipliers map[string]float64 `json:"reasoning_effort_multipliers,omitempty"`
ImageInputPrice *float64 `json:"image_input_price"`
@@ -91,6 +92,7 @@ type userPricingIntervalDTO struct {
OutputPrice *float64 `json:"output_price"`
CacheWritePrice *float64 `json:"cache_write_price"`
CacheWrite1hPrice *float64 `json:"cache_write_1h_price"`
CacheWrite12hPrice *float64 `json:"cache_write_12h_price"`
CacheReadPrice *float64 `json:"cache_read_price"`
InputMultiplier *float64 `json:"input_multiplier"`
OutputMultiplier *float64 `json:"output_multiplier"`
@@ -319,6 +321,7 @@ func toUserPricingIntervals(src []service.PricingInterval) []userPricingInterval
OutputPrice: iv.OutputPrice,
CacheWritePrice: iv.CacheWritePrice,
CacheWrite1hPrice: iv.CacheWrite1hPrice,
CacheWrite12hPrice: iv.CacheWrite12hPrice,
CacheReadPrice: iv.CacheReadPrice,
InputMultiplier: iv.InputMultiplier,
OutputMultiplier: iv.OutputMultiplier,
@@ -350,6 +353,7 @@ func toUserPricing(p *service.ChannelModelPricing) *userSupportedModelPricing {
OutputPrice: p.OutputPrice,
CacheWritePrice: p.CacheWritePrice,
CacheWrite1hPrice: p.CacheWrite1hPrice,
CacheWrite12hPrice: p.CacheWrite12hPrice,
CacheReadPrice: p.CacheReadPrice,
ReasoningEffortMultipliers: p.ReasoningEffortMultipliers,
ImageInputPrice: p.ImageInputPrice,
+2
View File
@@ -709,6 +709,8 @@ func usageLogFromServiceUser(l *service.UsageLog) UsageLog {
CacheReadTokens: l.CacheReadTokens,
CacheCreation5mTokens: l.CacheCreation5mTokens,
CacheCreation1hTokens: l.CacheCreation1hTokens,
CacheCreation30mTokens: l.CacheCreation30mTokens,
CacheCreation12hTokens: l.CacheCreation12hTokens,
InputCost: l.InputCost,
OutputCost: l.OutputCost,
CacheCreationCost: l.CacheCreationCost,
+4 -2
View File
@@ -620,8 +620,10 @@ type UsageLog struct {
CacheCreationTokens int `json:"cache_creation_tokens"`
CacheReadTokens int `json:"cache_read_tokens"`
CacheCreation5mTokens int `json:"cache_creation_5m_tokens"`
CacheCreation1hTokens int `json:"cache_creation_1h_tokens"`
CacheCreation5mTokens int `json:"cache_creation_5m_tokens"`
CacheCreation1hTokens int `json:"cache_creation_1h_tokens"`
CacheCreation30mTokens int `json:"cache_creation_30m_tokens"`
CacheCreation12hTokens int `json:"cache_creation_12h_tokens"`
InputCost float64 `json:"input_cost"`
OutputCost float64 `json:"output_cost"`
+13 -11
View File
@@ -38,11 +38,12 @@ func NewModelPlazaHandler(
// modelPlazaOfficialPricing 官方参考价(USD per token,与计费目录同源)。
type modelPlazaOfficialPricing struct {
InputPrice *float64 `json:"input_price"`
OutputPrice *float64 `json:"output_price"`
CacheWritePrice *float64 `json:"cache_write_price"`
CacheWrite1hPrice *float64 `json:"cache_write_1h_price,omitempty"`
CacheReadPrice *float64 `json:"cache_read_price"`
InputPrice *float64 `json:"input_price"`
OutputPrice *float64 `json:"output_price"`
CacheWritePrice *float64 `json:"cache_write_price"`
CacheWrite1hPrice *float64 `json:"cache_write_1h_price,omitempty"`
CacheWrite12hPrice *float64 `json:"cache_write_12h_price,omitempty"`
CacheReadPrice *float64 `json:"cache_read_price"`
// Intervals 官方长上下文阶梯,仅多档模型给出。
Intervals []userPricingIntervalDTO `json:"intervals,omitempty"`
}
@@ -257,11 +258,12 @@ func toModelPlazaOfficialPricing(p *service.PlazaOfficialPricing) *modelPlazaOff
return nil
}
return &modelPlazaOfficialPricing{
InputPrice: p.InputPrice,
OutputPrice: p.OutputPrice,
CacheWritePrice: p.CacheWritePrice,
CacheWrite1hPrice: p.CacheWrite1hPrice,
CacheReadPrice: p.CacheReadPrice,
Intervals: toUserPricingIntervals(p.Intervals),
InputPrice: p.InputPrice,
OutputPrice: p.OutputPrice,
CacheWritePrice: p.CacheWritePrice,
CacheWrite1hPrice: p.CacheWrite1hPrice,
CacheWrite12hPrice: p.CacheWrite12hPrice,
CacheReadPrice: p.CacheReadPrice,
Intervals: toUserPricingIntervals(p.Intervals),
}
}
@@ -67,7 +67,7 @@ func (r *channelRepository) batchLoadAccountStatsModelPricing(ctx context.Contex
rows, err := r.db.QueryContext(ctx,
`SELECT id, rule_id, platform, models, billing_mode, input_price, output_price,
cache_write_price, cache_write_1h_price, cache_read_price, reasoning_effort_multipliers, image_output_price, per_request_price, created_at, updated_at
cache_write_price, cache_write_1h_price, cache_write_12h_price, cache_read_price, reasoning_effort_multipliers, image_output_price, per_request_price, created_at, updated_at
FROM channel_account_stats_model_pricing WHERE rule_id = ANY($1) ORDER BY rule_id, id`,
pq.Array(ruleIDs),
)
@@ -84,7 +84,7 @@ func (r *channelRepository) batchLoadAccountStatsModelPricing(ctx context.Contex
var reasoningEffortMultipliersJSON []byte
if err := rows.Scan(
&p.ID, &ruleID, &p.Platform, &modelsJSON, &p.BillingMode,
&p.InputPrice, &p.OutputPrice, &p.CacheWritePrice, &p.CacheWrite1hPrice, &p.CacheReadPrice,
&p.InputPrice, &p.OutputPrice, &p.CacheWritePrice, &p.CacheWrite1hPrice, &p.CacheWrite12hPrice, &p.CacheReadPrice,
&reasoningEffortMultipliersJSON, &p.ImageOutputPrice, &p.PerRequestPrice, &p.CreatedAt, &p.UpdatedAt,
); err != nil {
return nil, fmt.Errorf("scan account stats model pricing: %w", err)
@@ -188,10 +188,10 @@ func createAccountStatsModelPricingTx(ctx context.Context, tx *sql.Tx, ruleID in
}
platform := pricing.Platform
err = tx.QueryRowContext(ctx,
`INSERT INTO channel_account_stats_model_pricing (rule_id, platform, models, billing_mode, input_price, output_price, cache_write_price, cache_write_1h_price, cache_read_price, reasoning_effort_multipliers, image_output_price, per_request_price)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING id, created_at, updated_at`,
`INSERT INTO channel_account_stats_model_pricing (rule_id, platform, models, billing_mode, input_price, output_price, cache_write_price, cache_write_1h_price, cache_write_12h_price, cache_read_price, reasoning_effort_multipliers, image_output_price, per_request_price)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) RETURNING id, created_at, updated_at`,
ruleID, platform, modelsJSON, billingMode,
pricing.InputPrice, pricing.OutputPrice, pricing.CacheWritePrice, pricing.CacheWrite1hPrice, pricing.CacheReadPrice,
pricing.InputPrice, pricing.OutputPrice, pricing.CacheWritePrice, pricing.CacheWrite1hPrice, pricing.CacheWrite12hPrice, pricing.CacheReadPrice,
reasoningEffortMultipliersJSON, pricing.ImageOutputPrice, pricing.PerRequestPrice,
).Scan(&pricing.ID, &pricing.CreatedAt, &pricing.UpdatedAt)
if err != nil {
@@ -212,10 +212,10 @@ func createAccountStatsModelPricingTx(ctx context.Context, tx *sql.Tx, ruleID in
func createAccountStatsIntervalTx(ctx context.Context, tx *sql.Tx, iv *service.PricingInterval) error {
return tx.QueryRowContext(ctx,
`INSERT INTO channel_account_stats_pricing_intervals
(pricing_id, min_tokens, max_tokens, tier_label, input_price, output_price, cache_write_price, cache_write_1h_price, cache_read_price, per_request_price, sort_order)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING id, created_at, updated_at`,
(pricing_id, min_tokens, max_tokens, tier_label, input_price, output_price, cache_write_price, cache_write_1h_price, cache_write_12h_price, cache_read_price, per_request_price, sort_order)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING id, created_at, updated_at`,
iv.PricingID, iv.MinTokens, iv.MaxTokens, iv.TierLabel,
iv.InputPrice, iv.OutputPrice, iv.CacheWritePrice, iv.CacheWrite1hPrice, iv.CacheReadPrice,
iv.InputPrice, iv.OutputPrice, iv.CacheWritePrice, iv.CacheWrite1hPrice, iv.CacheWrite12hPrice, iv.CacheReadPrice,
iv.PerRequestPrice, iv.SortOrder,
).Scan(&iv.ID, &iv.CreatedAt, &iv.UpdatedAt)
}
@@ -227,7 +227,7 @@ func (r *channelRepository) batchLoadAccountStatsIntervals(ctx context.Context,
}
rows, err := r.db.QueryContext(ctx,
`SELECT id, pricing_id, min_tokens, max_tokens, tier_label,
input_price, output_price, cache_write_price, cache_write_1h_price, cache_read_price,
input_price, output_price, cache_write_price, cache_write_1h_price, cache_write_12h_price, cache_read_price,
per_request_price, sort_order, created_at, updated_at
FROM channel_account_stats_pricing_intervals
WHERE pricing_id = ANY($1) ORDER BY pricing_id, sort_order, id`,
@@ -243,7 +243,7 @@ func (r *channelRepository) batchLoadAccountStatsIntervals(ctx context.Context,
var iv service.PricingInterval
if err := rows.Scan(
&iv.ID, &iv.PricingID, &iv.MinTokens, &iv.MaxTokens, &iv.TierLabel,
&iv.InputPrice, &iv.OutputPrice, &iv.CacheWritePrice, &iv.CacheWrite1hPrice, &iv.CacheReadPrice,
&iv.InputPrice, &iv.OutputPrice, &iv.CacheWritePrice, &iv.CacheWrite1hPrice, &iv.CacheWrite12hPrice, &iv.CacheReadPrice,
&iv.PerRequestPrice, &iv.SortOrder, &iv.CreatedAt, &iv.UpdatedAt,
); err != nil {
return nil, fmt.Errorf("scan account stats pricing interval: %w", err)
@@ -16,7 +16,7 @@ import (
func (r *channelRepository) ListModelPricing(ctx context.Context, channelID int64) ([]service.ChannelModelPricing, error) {
rows, err := r.db.QueryContext(ctx,
`SELECT id, channel_id, platform, models, billing_mode, input_price, output_price, cache_write_price, cache_write_1h_price, cache_read_price, fast_multiplier, flex_multiplier, reasoning_effort_multipliers, image_input_price, image_output_price, per_request_price, time_pricing, created_at, updated_at
`SELECT id, channel_id, platform, models, billing_mode, input_price, output_price, cache_write_price, cache_write_1h_price, cache_write_12h_price, cache_read_price, fast_multiplier, flex_multiplier, reasoning_effort_multipliers, image_input_price, image_output_price, per_request_price, time_pricing, created_at, updated_at
FROM channel_model_pricing WHERE channel_id = $1 ORDER BY id`, channelID,
)
if err != nil {
@@ -65,9 +65,9 @@ func (r *channelRepository) UpdateModelPricing(ctx context.Context, pricing *ser
}
result, err := r.db.ExecContext(ctx,
`UPDATE channel_model_pricing
SET models = $1, billing_mode = $2, input_price = $3, output_price = $4, cache_write_price = $5, cache_write_1h_price = $6, cache_read_price = $7, fast_multiplier = $8, flex_multiplier = $9, reasoning_effort_multipliers = $10, image_input_price = $11, image_output_price = $12, per_request_price = $13, time_pricing = $14, platform = $15, updated_at = NOW()
WHERE id = $16`,
modelsJSON, billingMode, pricing.InputPrice, pricing.OutputPrice, pricing.CacheWritePrice, pricing.CacheWrite1hPrice, pricing.CacheReadPrice,
SET models = $1, billing_mode = $2, input_price = $3, output_price = $4, cache_write_price = $5, cache_write_1h_price = $6, cache_write_12h_price = $7, cache_read_price = $8, fast_multiplier = $9, flex_multiplier = $10, reasoning_effort_multipliers = $11, image_input_price = $12, image_output_price = $13, per_request_price = $14, time_pricing = $15, platform = $16, updated_at = NOW()
WHERE id = $17`,
modelsJSON, billingMode, pricing.InputPrice, pricing.OutputPrice, pricing.CacheWritePrice, pricing.CacheWrite1hPrice, pricing.CacheWrite12hPrice, pricing.CacheReadPrice,
pricing.FastMultiplier, pricing.FlexMultiplier, reasoningEffortMultipliersJSON, pricing.ImageInputPrice, pricing.ImageOutputPrice, pricing.PerRequestPrice,
timePricingJSON, pricing.Platform, pricing.ID,
)
@@ -100,7 +100,7 @@ func (r *channelRepository) ReplaceModelPricing(ctx context.Context, channelID i
// batchLoadModelPricing 批量加载多个渠道的模型定价(含区间)
func (r *channelRepository) batchLoadModelPricing(ctx context.Context, channelIDs []int64) (map[int64][]service.ChannelModelPricing, error) {
rows, err := r.db.QueryContext(ctx,
`SELECT id, channel_id, platform, models, billing_mode, input_price, output_price, cache_write_price, cache_write_1h_price, cache_read_price, fast_multiplier, flex_multiplier, reasoning_effort_multipliers, image_input_price, image_output_price, per_request_price, time_pricing, created_at, updated_at
`SELECT id, channel_id, platform, models, billing_mode, input_price, output_price, cache_write_price, cache_write_1h_price, cache_write_12h_price, cache_read_price, fast_multiplier, flex_multiplier, reasoning_effort_multipliers, image_input_price, image_output_price, per_request_price, time_pricing, created_at, updated_at
FROM channel_model_pricing WHERE channel_id = ANY($1) ORDER BY channel_id, id`,
pq.Array(channelIDs),
)
@@ -140,7 +140,7 @@ func (r *channelRepository) batchLoadModelPricing(ctx context.Context, channelID
func (r *channelRepository) batchLoadIntervals(ctx context.Context, pricingIDs []int64) (map[int64][]service.PricingInterval, error) {
rows, err := r.db.QueryContext(ctx,
`SELECT id, pricing_id, min_tokens, max_tokens, tier_label,
input_price, output_price, cache_write_price, cache_write_1h_price, cache_read_price,
input_price, output_price, cache_write_price, cache_write_1h_price, cache_write_12h_price, cache_read_price,
input_multiplier, output_multiplier, cache_write_multiplier, cache_read_multiplier,
per_request_price, sort_order, created_at, updated_at
FROM channel_pricing_intervals
@@ -157,7 +157,7 @@ func (r *channelRepository) batchLoadIntervals(ctx context.Context, pricingIDs [
var iv service.PricingInterval
if err := rows.Scan(
&iv.ID, &iv.PricingID, &iv.MinTokens, &iv.MaxTokens, &iv.TierLabel,
&iv.InputPrice, &iv.OutputPrice, &iv.CacheWritePrice, &iv.CacheWrite1hPrice, &iv.CacheReadPrice,
&iv.InputPrice, &iv.OutputPrice, &iv.CacheWritePrice, &iv.CacheWrite1hPrice, &iv.CacheWrite12hPrice, &iv.CacheReadPrice,
&iv.InputMultiplier, &iv.OutputMultiplier, &iv.CacheWriteMultiplier, &iv.CacheReadMultiplier,
&iv.PerRequestPrice, &iv.SortOrder, &iv.CreatedAt, &iv.UpdatedAt,
); err != nil {
@@ -184,7 +184,7 @@ func scanModelPricingRows(rows *sql.Rows) ([]service.ChannelModelPricing, []int6
var reasoningEffortMultipliersJSON []byte
if err := rows.Scan(
&p.ID, &p.ChannelID, &p.Platform, &modelsJSON, &p.BillingMode,
&p.InputPrice, &p.OutputPrice, &p.CacheWritePrice, &p.CacheWrite1hPrice, &p.CacheReadPrice,
&p.InputPrice, &p.OutputPrice, &p.CacheWritePrice, &p.CacheWrite1hPrice, &p.CacheWrite12hPrice, &p.CacheReadPrice,
&p.FastMultiplier, &p.FlexMultiplier, &reasoningEffortMultipliersJSON,
&p.ImageInputPrice, &p.ImageOutputPrice, &p.PerRequestPrice, &timePricingJSON, &p.CreatedAt, &p.UpdatedAt,
); err != nil {
@@ -261,10 +261,10 @@ func createModelPricingExec(ctx context.Context, exec dbExec, pricing *service.C
platform = "anthropic"
}
err = exec.QueryRowContext(ctx,
`INSERT INTO channel_model_pricing (channel_id, platform, models, billing_mode, input_price, output_price, cache_write_price, cache_write_1h_price, cache_read_price, fast_multiplier, flex_multiplier, reasoning_effort_multipliers, image_input_price, image_output_price, per_request_price, time_pricing)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) RETURNING id, created_at, updated_at`,
`INSERT INTO channel_model_pricing (channel_id, platform, models, billing_mode, input_price, output_price, cache_write_price, cache_write_1h_price, cache_write_12h_price, cache_read_price, fast_multiplier, flex_multiplier, reasoning_effort_multipliers, image_input_price, image_output_price, per_request_price, time_pricing)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17) RETURNING id, created_at, updated_at`,
pricing.ChannelID, platform, modelsJSON, billingMode,
pricing.InputPrice, pricing.OutputPrice, pricing.CacheWritePrice, pricing.CacheWrite1hPrice, pricing.CacheReadPrice,
pricing.InputPrice, pricing.OutputPrice, pricing.CacheWritePrice, pricing.CacheWrite1hPrice, pricing.CacheWrite12hPrice, pricing.CacheReadPrice,
pricing.FastMultiplier, pricing.FlexMultiplier, reasoningEffortMultipliersJSON, pricing.ImageInputPrice, pricing.ImageOutputPrice,
pricing.PerRequestPrice, timePricingJSON,
).Scan(&pricing.ID, &pricing.CreatedAt, &pricing.UpdatedAt)
@@ -332,10 +332,10 @@ func unmarshalChannelTimePricing(data []byte) (*service.ChannelTimePricing, erro
func createIntervalExec(ctx context.Context, exec dbExec, iv *service.PricingInterval) error {
return exec.QueryRowContext(ctx,
`INSERT INTO channel_pricing_intervals
(pricing_id, min_tokens, max_tokens, tier_label, input_price, output_price, cache_write_price, cache_write_1h_price, cache_read_price, input_multiplier, output_multiplier, cache_write_multiplier, cache_read_multiplier, per_request_price, sort_order)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15) RETURNING id, created_at, updated_at`,
(pricing_id, min_tokens, max_tokens, tier_label, input_price, output_price, cache_write_price, cache_write_1h_price, cache_write_12h_price, cache_read_price, input_multiplier, output_multiplier, cache_write_multiplier, cache_read_multiplier, per_request_price, sort_order)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) RETURNING id, created_at, updated_at`,
iv.PricingID, iv.MinTokens, iv.MaxTokens, iv.TierLabel,
iv.InputPrice, iv.OutputPrice, iv.CacheWritePrice, iv.CacheWrite1hPrice, iv.CacheReadPrice,
iv.InputPrice, iv.OutputPrice, iv.CacheWritePrice, iv.CacheWrite1hPrice, iv.CacheWrite12hPrice, iv.CacheReadPrice,
iv.InputMultiplier, iv.OutputMultiplier, iv.CacheWriteMultiplier, iv.CacheReadMultiplier,
iv.PerRequestPrice, iv.SortOrder,
).Scan(&iv.ID, &iv.CreatedAt, &iv.UpdatedAt)
@@ -30,7 +30,7 @@ func (c *capturedReasoningMultipliersJSON) Match(value driver.Value) bool {
func reasoningPricingRow(multipliers any) *sqlmock.Rows {
return sqlmock.NewRows(channelModelPricingTimePricingColumns).AddRow(
int64(11), int64(7), "openai", `["custom-model"]`, service.BillingModeToken,
nil, nil, nil, nil, nil, nil, nil, multipliers, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil, multipliers, nil, nil, nil, nil,
time.Time{}, time.Time{},
)
}
@@ -56,9 +56,9 @@ func TestChannelReasoningEffortMultipliersRoundTrip(t *testing.T) {
}
stored := &capturedReasoningMultipliersJSON{}
if operation == "update" {
mock.ExpectExec(`(?s)UPDATE channel_model_pricing.*reasoning_effort_multipliers = \$10.*WHERE id = \$16`).
mock.ExpectExec(`(?s)UPDATE channel_model_pricing.*reasoning_effort_multipliers = \$11.*WHERE id = \$17`).
WithArgs([]byte(`["custom-model"]`), service.BillingModeToken,
nil, nil, nil, nil, nil, nil, nil, stored, nil, nil, nil, nil, "openai", int64(11)).
nil, nil, nil, nil, nil, nil, nil, nil, stored, nil, nil, nil, nil, "openai", int64(11)).
WillReturnResult(sqlmock.NewResult(0, 1))
require.NoError(t, repo.UpdateModelPricing(ctx, pricing))
} else {
@@ -69,7 +69,7 @@ func TestChannelReasoningEffortMultipliersRoundTrip(t *testing.T) {
}
mock.ExpectQuery(`INSERT INTO channel_model_pricing .*reasoning_effort_multipliers`).
WithArgs(int64(7), "openai", []byte(`["custom-model"]`), service.BillingModeToken,
nil, nil, nil, nil, nil, nil, nil, stored, nil, nil, nil, nil).
nil, nil, nil, nil, nil, nil, nil, nil, stored, nil, nil, nil, nil).
WillReturnRows(sqlmock.NewRows([]string{"id", "created_at", "updated_at"}).AddRow(int64(11), time.Time{}, time.Time{}))
if operation == "replace" {
mock.ExpectCommit()
@@ -148,7 +148,7 @@ func TestAccountStatsReasoningEffortMultipliersRoundTrip(t *testing.T) {
require.NoError(t, err)
mock.ExpectQuery(`INSERT INTO channel_account_stats_model_pricing .*reasoning_effort_multipliers`).
WithArgs(int64(9), "anthropic", []byte(`["custom-model"]`), service.BillingModeToken,
nil, nil, nil, nil, nil, stored, nil, nil).
nil, nil, nil, nil, nil, nil, stored, nil, nil).
WillReturnRows(sqlmock.NewRows([]string{"id", "created_at", "updated_at"}).AddRow(int64(11), time.Time{}, time.Time{}))
require.NoError(t, createAccountStatsModelPricingTx(ctx, tx, 9, pricing))
mock.ExpectCommit()
@@ -157,13 +157,13 @@ func TestAccountStatsReasoningEffortMultipliersRoundTrip(t *testing.T) {
columns := []string{
"id", "rule_id", "platform", "models", "billing_mode", "input_price", "output_price",
"cache_write_price", "cache_write_1h_price", "cache_read_price", "reasoning_effort_multipliers",
"cache_write_price", "cache_write_1h_price", "cache_write_12h_price", "cache_read_price", "reasoning_effort_multipliers",
"image_output_price", "per_request_price", "created_at", "updated_at",
}
mock.ExpectQuery(`(?s)SELECT .*reasoning_effort_multipliers.*FROM channel_account_stats_model_pricing`).
WithArgs(pq.Array([]int64{9})).WillReturnRows(sqlmock.NewRows(columns).AddRow(
int64(11), int64(9), "anthropic", `["custom-model"]`, service.BillingModeToken,
nil, nil, nil, nil, nil, stored.value, nil, nil, time.Time{}, time.Time{},
nil, nil, nil, nil, nil, nil, stored.value, nil, nil, time.Time{}, time.Time{},
))
mock.ExpectQuery(`(?s)SELECT .*FROM channel_account_stats_pricing_intervals`).
WithArgs(pq.Array([]int64{11})).WillReturnRows(sqlmock.NewRows([]string{"id"}))
@@ -16,7 +16,7 @@ import (
var channelModelPricingTimePricingColumns = []string{
"id", "channel_id", "platform", "models", "billing_mode", "input_price", "output_price",
"cache_write_price", "cache_write_1h_price", "cache_read_price", "fast_multiplier", "flex_multiplier", "reasoning_effort_multipliers", "image_input_price", "image_output_price",
"cache_write_price", "cache_write_1h_price", "cache_write_12h_price", "cache_read_price", "fast_multiplier", "flex_multiplier", "reasoning_effort_multipliers", "image_input_price", "image_output_price",
"per_request_price", "time_pricing", "created_at", "updated_at",
}
@@ -33,7 +33,7 @@ func newChannelModelPricingTimePricingRepo(t *testing.T) (*channelRepository, sq
func modelPricingTimePricingRow(timePricing any) *sqlmock.Rows {
return sqlmock.NewRows(channelModelPricingTimePricingColumns).AddRow(
int64(11), int64(7), "openai", `["gpt-5"]`, service.BillingModeToken,
nil, nil, nil, nil, nil, nil, nil, "{}", nil, nil, nil, timePricing,
nil, nil, nil, nil, nil, nil, nil, nil, "{}", nil, nil, nil, timePricing,
time.Date(2026, 8, 17, 0, 0, 0, 0, time.UTC), time.Date(2026, 8, 17, 1, 0, 0, 0, time.UTC),
)
}
@@ -105,10 +105,10 @@ func TestChannelModelPricingTimePricingCreateAndUpdateRoundTrip(t *testing.T) {
t.Run("create writes JSON", func(t *testing.T) {
repo, mock := newChannelModelPricingTimePricingRepo(t)
mock.ExpectQuery(regexp.QuoteMeta("INSERT INTO channel_model_pricing (channel_id, platform, models, billing_mode, input_price, output_price, cache_write_price, cache_write_1h_price, cache_read_price, fast_multiplier, flex_multiplier, reasoning_effort_multipliers, image_input_price, image_output_price, per_request_price, time_pricing)")).
mock.ExpectQuery(regexp.QuoteMeta("INSERT INTO channel_model_pricing (channel_id, platform, models, billing_mode, input_price, output_price, cache_write_price, cache_write_1h_price, cache_write_12h_price, cache_read_price, fast_multiplier, flex_multiplier, reasoning_effort_multipliers, image_input_price, image_output_price, per_request_price, time_pricing)")).
WithArgs(
int64(7), "openai", []byte(`["gpt-5"]`), service.BillingModeToken,
nil, nil, nil, nil, nil, nil, nil, "{}", nil, nil, nil, channelModelPricingTimePricingJSON,
nil, nil, nil, nil, nil, nil, nil, nil, "{}", nil, nil, nil, channelModelPricingTimePricingJSON,
).
WillReturnRows(sqlmock.NewRows([]string{"id", "created_at", "updated_at"}).AddRow(int64(11), time.Time{}, time.Time{}))
@@ -118,10 +118,10 @@ func TestChannelModelPricingTimePricingCreateAndUpdateRoundTrip(t *testing.T) {
t.Run("update writes JSON and entry ID", func(t *testing.T) {
repo, mock := newChannelModelPricingTimePricingRepo(t)
mock.ExpectExec(`(?s)UPDATE channel_model_pricing.*per_request_price = \$13, time_pricing = \$14, platform = \$15.*WHERE id = \$16`).
mock.ExpectExec(`(?s)UPDATE channel_model_pricing.*per_request_price = \$14, time_pricing = \$15, platform = \$16.*WHERE id = \$17`).
WithArgs(
[]byte(`["gpt-5"]`), service.BillingModeToken,
nil, nil, nil, nil, nil, nil, nil, "{}", nil, nil, nil, channelModelPricingTimePricingJSON, "openai", int64(11),
nil, nil, nil, nil, nil, nil, nil, nil, "{}", nil, nil, nil, channelModelPricingTimePricingJSON, "openai", int64(11),
).
WillReturnResult(sqlmock.NewResult(0, 1))
@@ -153,10 +153,10 @@ func TestChannelModelPricingTimePricingCreateAndUpdateWriteNullWhenDisabled(t *t
t.Run("create writes SQL NULL", func(t *testing.T) {
repo, mock := newChannelModelPricingTimePricingRepo(t)
mock.ExpectQuery(regexp.QuoteMeta("INSERT INTO channel_model_pricing (channel_id, platform, models, billing_mode, input_price, output_price, cache_write_price, cache_write_1h_price, cache_read_price, fast_multiplier, flex_multiplier, reasoning_effort_multipliers, image_input_price, image_output_price, per_request_price, time_pricing)")).
mock.ExpectQuery(regexp.QuoteMeta("INSERT INTO channel_model_pricing (channel_id, platform, models, billing_mode, input_price, output_price, cache_write_price, cache_write_1h_price, cache_write_12h_price, cache_read_price, fast_multiplier, flex_multiplier, reasoning_effort_multipliers, image_input_price, image_output_price, per_request_price, time_pricing)")).
WithArgs(
int64(7), "openai", []byte(`["gpt-5"]`), service.BillingModeToken,
nil, nil, nil, nil, nil, nil, nil, "{}", nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil, "{}", nil, nil, nil, nil,
).
WillReturnRows(sqlmock.NewRows([]string{"id", "created_at", "updated_at"}).AddRow(int64(11), time.Time{}, time.Time{}))
@@ -166,10 +166,10 @@ func TestChannelModelPricingTimePricingCreateAndUpdateWriteNullWhenDisabled(t *t
t.Run("update writes SQL NULL", func(t *testing.T) {
repo, mock := newChannelModelPricingTimePricingRepo(t)
mock.ExpectExec(`(?s)UPDATE channel_model_pricing.*per_request_price = \$13, time_pricing = \$14, platform = \$15.*WHERE id = \$16`).
mock.ExpectExec(`(?s)UPDATE channel_model_pricing.*per_request_price = \$14, time_pricing = \$15, platform = \$16.*WHERE id = \$17`).
WithArgs(
[]byte(`["gpt-5"]`), service.BillingModeToken,
nil, nil, nil, nil, nil, nil, nil, "{}", nil, nil, nil, nil, "openai", int64(11),
nil, nil, nil, nil, nil, nil, nil, nil, "{}", nil, nil, nil, nil, "openai", int64(11),
).
WillReturnResult(sqlmock.NewResult(0, 1))
@@ -0,0 +1,117 @@
//go:build integration
package repository
import (
"context"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
)
func TestUsageLogRepositoryCacheWriteTTLRoundTrip(t *testing.T) {
ctx := context.Background()
client := testEntClient(t)
repo := newUsageLogRepositoryWithSQL(client, integrationDB)
user := mustCreateUser(t, client, &service.User{Email: uuid.NewString() + "@example.com"})
key := mustCreateApiKey(t, client, &service.APIKey{UserID: user.ID, Key: "synthetic-" + uuid.NewString(), Name: "ttl"})
account := mustCreateAccount(t, client, &service.Account{Name: "ttl-" + uuid.NewString()})
t.Cleanup(func() {
// These committed rows must not leak into later dashboard/global totals.
for _, row := range []struct {
table string
id int64
}{{"usage_logs", key.ID}, {"api_keys", key.ID}, {"accounts", account.ID}, {"users", user.ID}} {
column := "id"
if row.table == "usage_logs" {
column = "api_key_id"
}
_, err := integrationDB.ExecContext(ctx, "DELETE FROM "+row.table+" WHERE "+column+" = $1", row.id)
require.NoError(t, err)
}
})
for _, mode := range []string{"single", "batch", "best_effort"} {
t.Run(mode, func(t *testing.T) {
log := &service.UsageLog{
UserID: user.ID, APIKeyID: key.ID, AccountID: account.ID,
RequestID: uuid.NewString(), Model: "gpt-6-luna", InputTokens: 3,
CacheCreationTokens: 2399, CacheCreation30mTokens: 9, CacheCreation12hTokens: 2390,
CreatedAt: time.Now().UTC(),
}
switch mode {
case "single":
inserted, err := repo.createSingle(ctx, integrationDB, log)
require.NoError(t, err)
require.True(t, inserted)
case "batch":
inserted, err := repo.Create(ctx, log)
require.NoError(t, err)
require.True(t, inserted)
case "best_effort":
require.NoError(t, repo.CreateBestEffort(ctx, log))
require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT id FROM usage_logs WHERE request_id = $1 AND api_key_id = $2", log.RequestID, key.ID).Scan(&log.ID))
}
stored, err := repo.GetByID(ctx, log.ID)
require.NoError(t, err)
require.Equal(t, 2399, stored.CacheCreationTokens)
require.Equal(t, 9, stored.CacheCreation30mTokens)
require.Equal(t, 2390, stored.CacheCreation12hTokens)
require.Zero(t, stored.CacheCreation5mTokens)
require.Zero(t, stored.CacheCreation1hTokens)
})
}
}
func TestChannelCacheWriteTTLPricesRoundTrip(t *testing.T) {
ctx := context.Background()
short, long, statsLong, intervalLong := 0.8125e-6, 1.625e-6, 0.75e-6, 3.25e-6
channel := &service.Channel{
Name: t.Name(), Status: service.StatusActive, BillingModelSource: service.BillingModelSourceRequested,
ModelPricing: []service.ChannelModelPricing{{
Platform: service.PlatformOpenAI, Models: []string{"gpt-6-luna"}, BillingMode: service.BillingModeToken,
CacheWritePrice: &short, CacheWrite12hPrice: &long,
Intervals: []service.PricingInterval{{MinTokens: 100, CacheWrite12hPrice: &intervalLong}},
}},
AccountStatsPricingRules: []service.AccountStatsPricingRule{{
Name: "TTL accounting", GroupIDs: []int64{}, AccountIDs: []int64{}, Pricing: []service.ChannelModelPricing{{
Platform: service.PlatformOpenAI, Models: []string{"gpt-6-luna"}, BillingMode: service.BillingModeToken,
CacheWritePrice: &short, CacheWrite12hPrice: &statsLong,
Intervals: []service.PricingInterval{{MinTokens: 100, CacheWrite12hPrice: &intervalLong}},
}},
}},
}
repo := &channelRepository{db: integrationDB}
require.NoError(t, repo.Create(ctx, channel))
t.Cleanup(func() { require.NoError(t, repo.Delete(ctx, channel.ID)) })
loaded, err := repo.GetByID(ctx, channel.ID)
require.NoError(t, err)
require.InDelta(t, long, *loaded.ModelPricing[0].CacheWrite12hPrice, 1e-15)
require.InDelta(t, intervalLong, *loaded.ModelPricing[0].Intervals[0].CacheWrite12hPrice, 1e-15)
require.InDelta(t, statsLong, *loaded.AccountStatsPricingRules[0].Pricing[0].CacheWrite12hPrice, 1e-15)
require.InDelta(t, intervalLong, *loaded.AccountStatsPricingRules[0].Pricing[0].Intervals[0].CacheWrite12hPrice, 1e-15)
batch, err := repo.batchLoadModelPricing(ctx, []int64{channel.ID})
require.NoError(t, err)
require.InDelta(t, long, *batch[channel.ID][0].CacheWrite12hPrice, 1e-15)
stats, err := repo.batchLoadAccountStatsPricingRules(ctx, []int64{channel.ID})
require.NoError(t, err)
require.InDelta(t, statsLong, *stats[channel.ID][0].Pricing[0].CacheWrite12hPrice, 1e-15)
zero := 0.0
pricing := &loaded.ModelPricing[0]
pricing.CacheWrite12hPrice = &zero
require.NoError(t, repo.UpdateModelPricing(ctx, pricing))
listed, err := repo.ListModelPricing(ctx, channel.ID)
require.NoError(t, err)
require.NotNil(t, listed[0].CacheWrite12hPrice)
require.Zero(t, *listed[0].CacheWrite12hPrice)
pricing.CacheWrite12hPrice = nil
require.NoError(t, repo.ReplaceModelPricing(ctx, channel.ID, []service.ChannelModelPricing{*pricing}))
listed, err = repo.ListModelPricing(ctx, channel.ID)
require.NoError(t, err)
require.Nil(t, listed[0].CacheWrite12hPrice)
require.InDelta(t, intervalLong, *listed[0].Intervals[0].CacheWrite12hPrice, 1e-15)
}
@@ -85,6 +85,8 @@ var usageLogInsertArgTypes = [...]string{
"text", // upstream_request_id
"text", // session_id
"boolean", // native_compaction_v2
"integer", // cache_creation_30m_tokens
"integer", // cache_creation_12h_tokens
"timestamptz", // created_at
}
@@ -286,6 +288,8 @@ func (r *usageLogRepository) createSingle(ctx context.Context, sqlq sqlExecutor,
upstream_request_id,
session_id,
native_compaction_v2,
cache_creation_30m_tokens,
cache_creation_12h_tokens,
created_at
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9,
@@ -293,7 +297,7 @@ func (r *usageLogRepository) createSingle(ctx context.Context, sqlq sqlExecutor,
$12, $13, $14, $15,
$16, $17, $18, $19,
$20, $21, $22, $23, $24, $25,
$26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60, $61, $62
$26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60, $61, $62, $63, $64
)
ON CONFLICT (request_id, api_key_id) DO NOTHING
RETURNING id, created_at
@@ -746,6 +750,8 @@ func buildUsageLogBatchInsertQuery(keys []string, preparedByKey map[string]usage
upstream_request_id,
session_id,
native_compaction_v2,
cache_creation_30m_tokens,
cache_creation_12h_tokens,
created_at
) AS (VALUES `)
@@ -841,6 +847,8 @@ func buildUsageLogBatchInsertQuery(keys []string, preparedByKey map[string]usage
upstream_request_id,
session_id,
native_compaction_v2,
cache_creation_30m_tokens,
cache_creation_12h_tokens,
created_at
)
SELECT
@@ -905,6 +913,8 @@ func buildUsageLogBatchInsertQuery(keys []string, preparedByKey map[string]usage
upstream_request_id,
session_id,
native_compaction_v2,
cache_creation_30m_tokens,
cache_creation_12h_tokens,
created_at
FROM input
ON CONFLICT (request_id, api_key_id) DO NOTHING
@@ -1009,6 +1019,8 @@ func buildUsageLogBestEffortInsertQuery(preparedList []usageLogInsertPrepared) (
upstream_request_id,
session_id,
native_compaction_v2,
cache_creation_30m_tokens,
cache_creation_12h_tokens,
created_at
) AS (VALUES `)
@@ -1099,6 +1111,8 @@ func buildUsageLogBestEffortInsertQuery(preparedList []usageLogInsertPrepared) (
upstream_request_id,
session_id,
native_compaction_v2,
cache_creation_30m_tokens,
cache_creation_12h_tokens,
created_at
)
SELECT
@@ -1163,6 +1177,8 @@ func buildUsageLogBestEffortInsertQuery(preparedList []usageLogInsertPrepared) (
upstream_request_id,
session_id,
native_compaction_v2,
cache_creation_30m_tokens,
cache_creation_12h_tokens,
created_at
FROM input
ON CONFLICT (request_id, api_key_id) DO NOTHING
@@ -1235,6 +1251,8 @@ func execUsageLogInsertNoResult(ctx context.Context, sqlq sqlExecutor, prepared
upstream_request_id,
session_id,
native_compaction_v2,
cache_creation_30m_tokens,
cache_creation_12h_tokens,
created_at
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9,
@@ -1242,7 +1260,7 @@ func execUsageLogInsertNoResult(ctx context.Context, sqlq sqlExecutor, prepared
$12, $13, $14, $15,
$16, $17, $18, $19,
$20, $21, $22, $23, $24, $25,
$26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60, $61, $62
$26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60, $61, $62, $63, $64
)
ON CONFLICT (request_id, api_key_id) DO NOTHING
`, prepared.args...)
@@ -1366,6 +1384,8 @@ func prepareUsageLogInsert(log *service.UsageLog) usageLogInsertPrepared {
upstreamRequestID, // upstream_request_id
sessionID, // session_id
log.NativeCompactionV2,
log.CacheCreation30mTokens,
log.CacheCreation12hTokens,
createdAt,
},
}
@@ -129,7 +129,7 @@ func TestPrepareUsageLogInsert_UpstreamRequestIDArgWiring(t *testing.T) {
})
require.Len(t, prepared.args, len(usageLogInsertArgTypes))
idx := len(prepared.args) - 4
idx := len(prepared.args) - 6
arg, ok := prepared.args[idx].(sql.NullString)
require.True(t, ok, "upstream_request_id arg should be sql.NullString, got %T", prepared.args[idx])
require.True(t, arg.Valid)
@@ -19,7 +19,7 @@ import (
"github.com/Wei-Shaw/sub2api/internal/service"
)
const usageLogSelectColumns = "id, user_id, api_key_id, account_id, request_id, model, requested_model, upstream_model, upstream_response_model, upstream_model_mismatch, group_id, subscription_id, input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens, cache_creation_5m_tokens, cache_creation_1h_tokens, image_output_tokens, image_output_cost, image_input_tokens, image_input_cost, input_cost, output_cost, cache_creation_cost, cache_read_cost, total_cost, actual_cost, rate_multiplier, account_rate_multiplier, billing_type, request_type, stream, openai_ws_mode, duration_ms, first_token_ms, user_agent, ip_address, image_count, image_size, image_input_size, image_output_size, image_size_source, image_size_breakdown, video_count, video_resolution, video_duration_seconds, service_tier, reasoning_effort, requested_reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, long_context_billing_applied, channel_id, model_mapping_chain, billing_tier, billing_mode, account_stats_cost, upstream_request_id, session_id, native_compaction_v2, created_at"
const usageLogSelectColumns = "id, user_id, api_key_id, account_id, request_id, model, requested_model, upstream_model, upstream_response_model, upstream_model_mismatch, group_id, subscription_id, input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens, cache_creation_5m_tokens, cache_creation_1h_tokens, image_output_tokens, image_output_cost, image_input_tokens, image_input_cost, input_cost, output_cost, cache_creation_cost, cache_read_cost, total_cost, actual_cost, rate_multiplier, account_rate_multiplier, billing_type, request_type, stream, openai_ws_mode, duration_ms, first_token_ms, user_agent, ip_address, image_count, image_size, image_input_size, image_output_size, image_size_source, image_size_breakdown, video_count, video_resolution, video_duration_seconds, service_tier, reasoning_effort, requested_reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, long_context_billing_applied, channel_id, model_mapping_chain, billing_tier, billing_mode, account_stats_cost, upstream_request_id, session_id, native_compaction_v2, cache_creation_30m_tokens, cache_creation_12h_tokens, created_at"
func (r *usageLogRepository) GetByID(ctx context.Context, id int64) (log *service.UsageLog, err error) {
query := "SELECT " + usageLogSelectColumns + " FROM usage_logs WHERE id = $1"
@@ -502,6 +502,8 @@ func scanUsageLog(scanner interface{ Scan(...any) error }) (*service.UsageLog, e
upstreamRequestID sql.NullString
sessionID sql.NullString
nativeCompactionV2 bool
cacheCreation30m int
cacheCreation12h int
createdAt time.Time
)
@@ -568,6 +570,8 @@ func scanUsageLog(scanner interface{ Scan(...any) error }) (*service.UsageLog, e
&upstreamRequestID,
&sessionID,
&nativeCompactionV2,
&cacheCreation30m,
&cacheCreation12h,
&createdAt,
); err != nil {
return nil, err
@@ -601,6 +605,8 @@ func scanUsageLog(scanner interface{ Scan(...any) error }) (*service.UsageLog, e
BillingType: int8(billingType),
RequestType: service.RequestTypeFromInt16(requestTypeRaw),
NativeCompactionV2: nativeCompactionV2,
CacheCreation30mTokens: cacheCreation30m,
CacheCreation12hTokens: cacheCreation12h,
ImageCount: imageCount,
VideoCount: videoCount,
CacheTTLOverridden: cacheTTLOverridden,
@@ -102,6 +102,8 @@ func TestUsageLogRepositoryCreateSyncRequestTypeAndLegacyFields(t *testing.T) {
sqlmock.AnyArg(), // upstream_request_id
sqlmock.AnyArg(), // session_id
log.NativeCompactionV2,
log.CacheCreation30mTokens,
log.CacheCreation12hTokens,
createdAt,
).
WillReturnRows(sqlmock.NewRows([]string{"id", "created_at"}).AddRow(int64(99), createdAt))
@@ -197,6 +199,8 @@ func TestUsageLogRepositoryCreate_PersistsServiceTier(t *testing.T) {
sqlmock.AnyArg(), // upstream_request_id
sqlmock.AnyArg(), // session_id
log.NativeCompactionV2,
log.CacheCreation30mTokens,
log.CacheCreation12hTokens,
createdAt,
).
WillReturnRows(sqlmock.NewRows([]string{"id", "created_at"}).AddRow(int64(100), createdAt))
@@ -278,8 +282,8 @@ func TestPrepareUsageLogInsert_PersistsNativeCompactionV2WithoutChangingRequestT
prepared := prepareUsageLogInsert(log)
require.Len(t, prepared.args, len(usageLogInsertArgTypes))
require.Equal(t, "boolean", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-2])
require.Equal(t, true, prepared.args[len(prepared.args)-2])
require.Equal(t, "boolean", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-4])
require.Equal(t, true, prepared.args[len(prepared.args)-4])
require.Equal(t, int16(service.RequestTypeStream), prepared.args[30])
require.Equal(t, service.RequestTypeStream, log.RequestType)
require.True(t, log.Stream)
@@ -960,6 +964,8 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) {
sql.NullString{}, // upstream_request_id
sql.NullString{},
false, // native_compaction_v2
0, // cache_creation_30m_tokens
0, // cache_creation_12h_tokens
now,
}})
require.NoError(t, err)
@@ -1040,6 +1046,8 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) {
sql.NullString{}, // upstream_request_id
sql.NullString{}, // session_id
false, // native_compaction_v2
0, // cache_creation_30m_tokens
0, // cache_creation_12h_tokens
now,
}})
require.NoError(t, err)
@@ -1103,6 +1111,8 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) {
sql.NullString{}, // upstream_request_id
sql.NullString{}, // session_id
true, // native_compaction_v2
0, // cache_creation_30m_tokens
0, // cache_creation_12h_tokens
now,
}})
require.NoError(t, err)
@@ -1167,6 +1177,8 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) {
sql.NullString{}, // upstream_request_id
sql.NullString{}, // session_id
false, // native_compaction_v2
0, // cache_creation_30m_tokens
0, // cache_creation_12h_tokens
now,
}})
require.NoError(t, err)
@@ -39,15 +39,15 @@ func TestPrepareUsageLogInsert_SessionIDArgWiring(t *testing.T) {
"prepared args must match the arg-type table length")
// created_at is last; native_compaction_v2 is penultimate; session_id precedes it.
sessionArg := prepared.args[len(prepared.args)-3]
sessionArg := prepared.args[len(prepared.args)-5]
ns, ok := sessionArg.(sql.NullString)
require.True(t, ok, "session_id arg should be a sql.NullString, got %T", sessionArg)
require.True(t, ns.Valid)
require.Equal(t, sessionID, ns.String)
require.Equal(t, "text", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-3],
require.Equal(t, "text", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-5],
"session_id arg type must be text")
require.Equal(t, "boolean", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-2],
require.Equal(t, "boolean", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-4],
"native_compaction_v2 arg type must be boolean")
}
@@ -55,14 +55,14 @@ func TestPrepareUsageLogInsert_SessionIDArgWiring(t *testing.T) {
// persisted as SQL NULL rather than an empty string.
func TestPrepareUsageLogInsert_SessionIDNullWhenAbsent(t *testing.T) {
prepared := prepareUsageLogInsert(newSessionIDUsageLog(nil))
sessionArg := prepared.args[len(prepared.args)-3]
sessionArg := prepared.args[len(prepared.args)-5]
ns, ok := sessionArg.(sql.NullString)
require.True(t, ok, "session_id arg should be a sql.NullString, got %T", sessionArg)
require.False(t, ns.Valid, "absent session id must be NULL, not empty string")
empty := ""
preparedEmpty := prepareUsageLogInsert(newSessionIDUsageLog(&empty))
nsEmpty := preparedEmpty.args[len(preparedEmpty.args)-3].(sql.NullString)
nsEmpty := preparedEmpty.args[len(preparedEmpty.args)-5].(sql.NullString)
require.False(t, nsEmpty.Valid, "empty session id must also be NULL")
}
@@ -602,6 +602,8 @@ func TestAPIContracts(t *testing.T) {
"cache_read_tokens": 2,
"cache_creation_5m_tokens": 0,
"cache_creation_1h_tokens": 0,
"cache_creation_30m_tokens": 0,
"cache_creation_12h_tokens": 0,
"input_cost": 0,
"output_cost": 0,
"cache_creation_cost": 0,
@@ -226,12 +226,13 @@ func calculateTokenStatsCost(pricing *ChannelModelPricing, tokens UsageTokens) *
totalTokens := tokens.InputTokens + tokens.OutputTokens + tokens.CacheCreationTokens + tokens.CacheReadTokens
if iv := FindMatchingInterval(pricing.Intervals, totalTokens); iv != nil {
p = &ChannelModelPricing{
InputPrice: iv.InputPrice,
OutputPrice: iv.OutputPrice,
CacheWritePrice: iv.CacheWritePrice,
CacheWrite1hPrice: iv.CacheWrite1hPrice,
CacheReadPrice: iv.CacheReadPrice,
PerRequestPrice: iv.PerRequestPrice,
InputPrice: iv.InputPrice,
OutputPrice: iv.OutputPrice,
CacheWritePrice: iv.CacheWritePrice,
CacheWrite1hPrice: iv.CacheWrite1hPrice,
CacheWrite12hPrice: iv.CacheWrite12hPrice,
CacheReadPrice: iv.CacheReadPrice,
PerRequestPrice: iv.PerRequestPrice,
}
}
}
@@ -249,6 +250,9 @@ func calculateTokenStatsCost(pricing *ChannelModelPricing, tokens UsageTokens) *
float64(cache1h)*deref(p.CacheWrite1hPrice)
}
}
if cost, ok := openAICacheCreationTTLCost(tokens, deref(p.CacheWritePrice), p.CacheWrite12hPrice); ok {
cacheCreationCost = cost
}
cost := float64(tokens.InputTokens)*deref(p.InputPrice) +
float64(tokens.OutputTokens)*deref(p.OutputPrice) +
cacheCreationCost +
@@ -21,14 +21,15 @@ const ContextPricingBasisWholeRequest ContextPricingBasis = "whole_request"
// ContextPricingTier (MinTokens, MaxTokens] 区间内的有效 per-token 单价(USD)。
// nil 表示该项无价/不计费;MaxTokens 为 nil 表示无上限。
type ContextPricingTier struct {
MinTokens int
MaxTokens *int
Label string
Input *float64
Output *float64
CacheWrite *float64
CacheWrite1h *float64
CacheRead *float64
MinTokens int
MaxTokens *int
Label string
Input *float64
Output *float64
CacheWrite *float64
CacheWrite1h *float64
CacheWrite12h *float64
CacheRead *float64
}
// TimePricingPeriod 分时倍率时段:配置时区当天 [StartTime, EndTime) 内整单费用乘 Multiplier。
@@ -303,12 +304,18 @@ func probeContextTier(seg contextSegment, resolved *ResolvedPricing, probe func(
if err != nil {
return tier, err
}
explicit := explicitContextPricingFields(resolved, c)
if explicit.cacheWrite12h || (resolved.BasePricing != nil && resolved.BasePricing.CacheCreation12hPricePerToken != nil) {
tier.CacheWrite12h, err = probeComponentPrice(func(n int) UsageTokens { return UsageTokens{CacheCreationTokens: n, CacheCreation12hTokens: n} }, c, delta, probe)
if err != nil {
return tier, err
}
}
tier.Input = contextPricePtr(tier.Input, explicit.input)
tier.Output = contextPricePtr(tier.Output, explicit.output)
tier.CacheWrite = contextPricePtr(tier.CacheWrite, explicit.cacheWrite)
tier.CacheWrite1h = contextPricePtr(tier.CacheWrite1h, explicit.cacheWrite1h)
tier.CacheWrite12h = contextPricePtr(tier.CacheWrite12h, explicit.cacheWrite12h)
tier.CacheRead = contextPricePtr(tier.CacheRead, explicit.cacheRead)
return tier, nil
}
@@ -352,7 +359,7 @@ func roundContextPrice(v float64) float64 {
}
type explicitContextFields struct {
input, output, cacheWrite, cacheWrite1h, cacheRead bool
input, output, cacheWrite, cacheWrite1h, cacheWrite12h, cacheRead bool
}
// explicitContextPricingFields 判断各项是否被分组卡/渠道定价(含命中区间)显式配置。
@@ -367,12 +374,14 @@ func explicitContextPricingFields(resolved *ResolvedPricing, contextTokens int)
out.output = cp.OutputPrice != nil
out.cacheWrite = cp.CacheWritePrice != nil
out.cacheWrite1h = cp.CacheWrite1hPrice != nil || cp.CacheWritePrice != nil
out.cacheWrite12h = cp.CacheWrite12hPrice != nil
out.cacheRead = cp.CacheReadPrice != nil
if iv := FindMatchingInterval(resolved.Intervals, contextTokens); iv != nil {
out.input = out.input || iv.InputPrice != nil
out.output = out.output || iv.OutputPrice != nil
out.cacheWrite = out.cacheWrite || iv.CacheWritePrice != nil
out.cacheWrite1h = out.cacheWrite1h || iv.CacheWrite1hPrice != nil || iv.CacheWritePrice != nil
out.cacheWrite12h = out.cacheWrite12h || iv.CacheWrite12hPrice != nil
out.cacheRead = out.cacheRead || iv.CacheReadPrice != nil
}
return out
@@ -406,7 +415,8 @@ func mergeEqualContextTiers(tiers []ContextPricingTier) []ContextPricingTier {
func sameContextPrices(a, b ContextPricingTier) bool {
return samePricePtr(a.Input, b.Input) && samePricePtr(a.Output, b.Output) &&
samePricePtr(a.CacheWrite, b.CacheWrite) && samePricePtr(a.CacheWrite1h, b.CacheWrite1h) && samePricePtr(a.CacheRead, b.CacheRead)
samePricePtr(a.CacheWrite, b.CacheWrite) && samePricePtr(a.CacheWrite1h, b.CacheWrite1h) &&
samePricePtr(a.CacheWrite12h, b.CacheWrite12h) && samePricePtr(a.CacheRead, b.CacheRead)
}
func samePricePtr(a, b *float64) bool {
+56 -12
View File
@@ -121,6 +121,7 @@ type ModelPricing struct {
LongContextOutputMultiplier float64 // 长上下文整次会话输出倍率
ImageOutputPricePerToken float64 // 图片输出 token 价格 (USD)
ImageOutputPriceExplicit bool // 是否由渠道定价显式设定(为 true 时即使 == 0 也不回退)
CacheCreation12hPricePerToken *float64 // OpenAI 12h writes; nil preserves the generic price on existing operator cards.
}
func normalizeBillingServiceTier(serviceTier string) string {
@@ -186,15 +187,17 @@ func pricingWithPriorityMultiplier(base *ModelPricing, multiplier float64) *Mode
// UsageTokens 使用的token数量
type UsageTokens struct {
InputTokens int
ImageInputTokens int
ImageCacheReadTokens int
OutputTokens int
CacheCreationTokens int
CacheReadTokens int
CacheCreation5mTokens int
CacheCreation1hTokens int
ImageOutputTokens int
InputTokens int
ImageInputTokens int
ImageCacheReadTokens int
OutputTokens int
CacheCreationTokens int
CacheReadTokens int
CacheCreation5mTokens int
CacheCreation1hTokens int
CacheCreation30mTokens int
CacheCreation12hTokens int
ImageOutputTokens int
}
// CostBreakdown 费用明细
@@ -1532,6 +1535,12 @@ func applyChannelTokenPriceOverrides(pricing *ModelPricing, channelPricing *Chan
pricing.CacheCreation1hPrice = *channelPricing.CacheWrite1hPrice
pricing.SupportsCacheBreakdown = true
}
if channelPricing.CacheWrite12hPrice != nil {
pricing.CacheCreation12hPricePerToken = channelPricing.CacheWrite12hPrice
} else if channelPricing.CacheWritePrice != nil {
// An existing flat operator price remains flat until 12h is configured.
pricing.CacheCreation12hPricePerToken = nil
}
if channelPricing.CacheReadPrice != nil {
priority := channelTierOverridePrice(pricing.CacheReadPricePerToken, pricing.CacheReadPricePerTokenPriority, *channelPricing.CacheReadPrice)
pricing.CacheReadPricePerToken = *channelPricing.CacheReadPrice
@@ -1685,6 +1694,7 @@ func (s *BillingService) computeTokenBreakdown(
outputPrice := pricing.OutputPricePerToken
cacheReadPrice := pricing.CacheReadPricePerToken
cacheCreationPrice := pricing.CacheCreationPricePerToken
cacheCreationPricing := pricing
cacheCreationMultiplier := 1.0
tierMultiplier := 1.0
@@ -1701,6 +1711,18 @@ func (s *BillingService) computeTokenBreakdown(
if pricing.CacheCreationPricePerTokenPriority > 0 {
cacheCreationPrice = pricing.CacheCreationPricePerTokenPriority
}
if pricing.CacheCreation12hPricePerToken != nil {
ratio := 1.0
if pricing.CacheCreationPricePerToken > 0 {
ratio = cacheCreationPrice / pricing.CacheCreationPricePerToken
} else if pricing.InputPricePerToken > 0 {
ratio = inputPrice / pricing.InputPricePerToken
}
cloned := *pricing
price := *pricing.CacheCreation12hPricePerToken * ratio
cloned.CacheCreation12hPricePerToken = &price
cacheCreationPricing = &cloned
}
} else {
tierMultiplier = configuredServiceTierMultiplier(serviceTier, pricing)
}
@@ -1762,7 +1784,7 @@ func (s *BillingService) computeTokenBreakdown(
}
// 缓存创建费用
bd.CacheCreationCost = s.computeCacheCreationCost(pricing, tokens, cacheCreationPrice, cacheCreationMultiplier)
bd.CacheCreationCost = s.computeCacheCreationCost(cacheCreationPricing, tokens, cacheCreationPrice, cacheCreationMultiplier)
bd.CacheReadCost = float64(tokens.CacheReadTokens) * cacheReadPrice
if imageCached := min(max(tokens.ImageCacheReadTokens, 0), max(tokens.CacheReadTokens, 0)); imageCached > 0 && pricing.ImageCacheReadPricePerToken > 0 {
@@ -1786,9 +1808,12 @@ func (s *BillingService) computeTokenBreakdown(
return bd
}
// computeCacheCreationCost 计算缓存创建费用(支持 5m/1h 分类或标准计费)。
// computeCacheCreationCost handles OpenAI 30m/12h, Anthropic 5m/1h, or aggregate writes.
// multiplier 用于长上下文等场景下的整体价格缩放(普通调用传 1.0 即可)。
func (s *BillingService) computeCacheCreationCost(pricing *ModelPricing, tokens UsageTokens, price, multiplier float64) float64 {
if cost, ok := openAICacheCreationTTLCost(tokens, price, pricing.CacheCreation12hPricePerToken); ok {
return cost * multiplier
}
if pricing.SupportsCacheBreakdown && (pricing.CacheCreation5mPrice > 0 || pricing.CacheCreation1hPrice > 0) {
cacheCreation5mTokens, cacheCreation1hTokens := normalizeCacheCreationBreakdown(tokens)
if cacheCreation5mTokens == 0 && cacheCreation1hTokens == 0 && tokens.CacheCreationTokens > 0 {
@@ -1801,6 +1826,21 @@ func (s *BillingService) computeCacheCreationCost(pricing *ModelPricing, tokens
return float64(tokens.CacheCreationTokens) * price * multiplier
}
// OpenAI's two write buckets are disjoint and exhaustive. Do not add the
// aggregate again or reuse the Anthropic 5m/1h buckets. Invalid or unknown
// breakdowns fall back to the aggregate's existing price.
func openAICacheCreationTTLCost(tokens UsageTokens, shortPrice float64, longPrice *float64) (float64, bool) {
a, b := tokens.CacheCreation30mTokens, tokens.CacheCreation12hTokens
if tokens.CacheCreationTokens <= 0 || a < 0 || b < 0 || a > tokens.CacheCreationTokens || b != tokens.CacheCreationTokens-a {
return 0, false
}
p := shortPrice
if longPrice != nil {
p = *longPrice
}
return float64(a)*shortPrice + float64(b)*p, true
}
// normalizeCacheCreationBreakdown caps contradictory 5m/1h details at an explicitly
// positive aggregate while retaining their reported ratio as closely as integer tokens allow.
func normalizeCacheCreationBreakdown(tokens UsageTokens) (int, int) {
@@ -1952,7 +1992,7 @@ func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing
return &cloned
}
normalized := normalizeKnownOpenAICodexModel(model)
usesCacheWritePremium := isOpenAIGPT56Model(normalized) || (openai.IsGPT6SolOrLunaModelSpelling(normalized) || openai.IsGPT61SolModelSpelling(normalized) || openai.IsGPT61TerraModelSpelling(normalized))
usesCacheWritePremium := isOpenAIGPT56Model(normalized) || isOpenAIGPT6AstraModel(normalized) || (openai.IsGPT6SolOrLunaModelSpelling(normalized) || openai.IsGPT61SolModelSpelling(normalized) || openai.IsGPT61TerraModelSpelling(normalized))
needsCacheCreationPolicy := usesCacheWritePremium && !pricing.CacheCreationPriceExplicit && (pricing.CacheCreationPricePerToken <= 0 ||
(pricing.InputPricePerTokenPriority > 0 && pricing.CacheCreationPricePerTokenPriority <= 0))
fastRatio := openAIModelFastPricingRatio(normalized)
@@ -1976,6 +2016,10 @@ func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing
cloned.CacheCreationPricePerTokenPriority = cloned.InputPricePerTokenPriority * 1.25
}
}
if usesCacheWritePremium && cloned.CacheCreation12hPricePerToken == nil && (forceDeepSeekRates || !cloned.CacheCreationPriceExplicit) {
price := cloned.InputPricePerToken * 2.5
cloned.CacheCreation12hPricePerToken = &price
}
if fastRatio > 0 {
enforceOpenAIFastPricingRatio(&cloned, fastRatio)
if (openai.IsGPT6SolOrLunaModelSpelling(normalized) || openai.IsGPT61SolModelSpelling(normalized) || openai.IsGPT61TerraModelSpelling(normalized)) && cloned.CacheCreationPriceExplicit {
+3
View File
@@ -97,6 +97,7 @@ type ChannelModelPricing struct {
OutputPrice *float64 `json:"output_price"`
CacheWritePrice *float64 `json:"cache_write_price"`
CacheWrite1hPrice *float64 `json:"cache_write_1h_price"`
CacheWrite12hPrice *float64 `json:"cache_write_12h_price"`
CacheReadPrice *float64 `json:"cache_read_price"`
FastMultiplier *float64 `json:"fast_multiplier"`
FlexMultiplier *float64 `json:"flex_multiplier"`
@@ -135,6 +136,7 @@ type PricingInterval struct {
OutputPrice *float64 `json:"output_price"`
CacheWritePrice *float64 `json:"cache_write_price"`
CacheWrite1hPrice *float64 `json:"cache_write_1h_price"`
CacheWrite12hPrice *float64 `json:"cache_write_12h_price"`
CacheReadPrice *float64 `json:"cache_read_price"`
InputMultiplier *float64 `json:"input_multiplier"`
OutputMultiplier *float64 `json:"output_multiplier"`
@@ -383,6 +385,7 @@ func validateIntervalPrices(iv *PricingInterval, idx int) error {
{"output_price", iv.OutputPrice},
{"cache_write_price", iv.CacheWritePrice},
{"cache_write_1h_price", iv.CacheWrite1hPrice},
{"cache_write_12h_price", iv.CacheWrite12hPrice},
{"cache_read_price", iv.CacheReadPrice},
{"per_request_price", iv.PerRequestPrice},
}
@@ -139,13 +139,13 @@ func pricingNeedsFallback(p *ChannelModelPricing) bool {
return true
}
if p.InputPrice != nil || p.OutputPrice != nil ||
p.CacheWritePrice != nil || p.CacheWrite1hPrice != nil || p.CacheReadPrice != nil ||
p.CacheWritePrice != nil || p.CacheWrite1hPrice != nil || p.CacheWrite12hPrice != nil || p.CacheReadPrice != nil ||
p.ImageOutputPrice != nil || p.PerRequestPrice != nil {
return false
}
for _, iv := range p.Intervals {
if iv.InputPrice != nil || iv.OutputPrice != nil ||
iv.CacheWritePrice != nil || iv.CacheWrite1hPrice != nil || iv.CacheReadPrice != nil ||
iv.CacheWritePrice != nil || iv.CacheWrite1hPrice != nil || iv.CacheWrite12hPrice != nil || iv.CacheReadPrice != nil ||
iv.PerRequestPrice != nil {
return false
}
+2 -1
View File
@@ -787,6 +787,7 @@ func checkPricesNotNegative(p ChannelModelPricing) error {
{"output_price", p.OutputPrice},
{"cache_write_price", p.CacheWritePrice},
{"cache_write_1h_price", p.CacheWrite1hPrice},
{"cache_write_12h_price", p.CacheWrite12hPrice},
{"cache_read_price", p.CacheReadPrice},
{"image_input_price", p.ImageInputPrice},
{"image_output_price", p.ImageOutputPrice},
@@ -814,7 +815,7 @@ func checkPricesNotNegative(p ChannelModelPricing) error {
func checkIntervalsHavePrices(p ChannelModelPricing) error {
for _, iv := range p.Intervals {
if iv.InputPrice == nil && iv.OutputPrice == nil &&
iv.CacheWritePrice == nil && iv.CacheWrite1hPrice == nil && iv.CacheReadPrice == nil &&
iv.CacheWritePrice == nil && iv.CacheWrite1hPrice == nil && iv.CacheWrite12hPrice == nil && iv.CacheReadPrice == nil &&
iv.PerRequestPrice == nil && iv.InputMultiplier == nil &&
iv.OutputMultiplier == nil && iv.CacheWriteMultiplier == nil &&
iv.CacheReadMultiplier == nil {
+19 -15
View File
@@ -10,11 +10,12 @@ import (
// PlazaOfficialPricing 模型广场展示用的官方参考价(USD per token),与计费同源:
// LiteLLM → 内置兜底价卡 → 模型策略。字段为 nil 表示该项缺失(0 视为未配置)。
type PlazaOfficialPricing struct {
InputPrice *float64
OutputPrice *float64
CacheWritePrice *float64 // 5m 缓存写入(= LiteLLM cache_creation)
CacheWrite1hPrice *float64 // 1h 缓存写入,仅计费会区分 5m/1h 时给出
CacheReadPrice *float64
InputPrice *float64
OutputPrice *float64
CacheWritePrice *float64 // 5m 缓存写入(= LiteLLM cache_creation)
CacheWrite1hPrice *float64 // 1h 缓存写入,仅计费会区分 5m/1h 时给出
CacheWrite12hPrice *float64 // OpenAI 12h cache-write price
CacheReadPrice *float64
// Intervals 官方长上下文阶梯(多档时给出),不受分组开关影响。
Intervals []PricingInterval
}
@@ -272,6 +273,7 @@ func plazaPricingFromSchedule(raw *ChannelModelPricing, sched *ContextPricingSch
out.OutputPrice = first.Output
out.CacheWritePrice = first.CacheWrite
out.CacheWrite1hPrice = first.CacheWrite1h
out.CacheWrite12hPrice = first.CacheWrite12h
out.CacheReadPrice = first.CacheRead
if len(sched.Tiers) > 1 {
out.Intervals = plazaIntervalsFromTiers(sched.Tiers)
@@ -283,15 +285,16 @@ func plazaIntervalsFromTiers(tiers []ContextPricingTier) []PricingInterval {
intervals := make([]PricingInterval, 0, len(tiers))
for i, t := range tiers {
intervals = append(intervals, PricingInterval{
MinTokens: t.MinTokens,
MaxTokens: t.MaxTokens,
TierLabel: t.Label,
InputPrice: t.Input,
OutputPrice: t.Output,
CacheWritePrice: t.CacheWrite,
CacheWrite1hPrice: t.CacheWrite1h,
CacheReadPrice: t.CacheRead,
SortOrder: i,
MinTokens: t.MinTokens,
MaxTokens: t.MaxTokens,
TierLabel: t.Label,
InputPrice: t.Input,
OutputPrice: t.Output,
CacheWritePrice: t.CacheWrite,
CacheWrite1hPrice: t.CacheWrite1h,
CacheWrite12hPrice: t.CacheWrite12h,
CacheReadPrice: t.CacheRead,
SortOrder: i,
})
}
return intervals
@@ -366,6 +369,7 @@ func (s *ModelPlazaService) lookupOfficialPricing(ctx context.Context, modelName
if mp.SupportsCacheBreakdown {
result.CacheWrite1hPrice = nonZeroPtr(mp.CacheCreation1hPrice)
}
result.CacheWrite12hPrice = mp.CacheCreation12hPricePerToken
if s.resolver != nil {
sched, schedErr := s.billingService.ResolveContextPricingSchedule(ctx, s.resolver, ContextPricingScheduleInput{Model: modelName})
if schedErr == nil && sched != nil && len(sched.Tiers) > 1 {
@@ -373,7 +377,7 @@ func (s *ModelPlazaService) lookupOfficialPricing(ctx context.Context, modelName
}
}
if result.InputPrice == nil && result.OutputPrice == nil && result.CacheWritePrice == nil &&
result.CacheWrite1hPrice == nil && result.CacheReadPrice == nil && len(result.Intervals) == 0 {
result.CacheWrite1hPrice == nil && result.CacheWrite12hPrice == nil && result.CacheReadPrice == nil && len(result.Intervals) == 0 {
result = nil
}
}
@@ -290,7 +290,7 @@ func filterValidIntervals(intervals []PricingInterval) []PricingInterval {
var valid []PricingInterval
for _, iv := range intervals {
if iv.InputPrice != nil || iv.OutputPrice != nil ||
iv.CacheWritePrice != nil || iv.CacheWrite1hPrice != nil || iv.CacheReadPrice != nil ||
iv.CacheWritePrice != nil || iv.CacheWrite1hPrice != nil || iv.CacheWrite12hPrice != nil || iv.CacheReadPrice != nil ||
iv.PerRequestPrice != nil || iv.InputMultiplier != nil ||
iv.OutputMultiplier != nil || iv.CacheWriteMultiplier != nil ||
iv.CacheReadMultiplier != nil {
@@ -358,6 +358,15 @@ func intervalToModelPricing(iv *PricingInterval, base *ModelPricing, chPricing *
pricing.CacheCreationPricePerTokenPriority = applyMultiplier(pricing.CacheCreationPricePerTokenPriority, iv.CacheWriteMultiplier)
pricing.CacheCreation5mPrice = applyMultiplier(pricing.CacheCreation5mPrice, iv.CacheWriteMultiplier)
pricing.CacheCreation1hPrice = applyMultiplier(pricing.CacheCreation1hPrice, iv.CacheWriteMultiplier)
if pricing.CacheCreation12hPricePerToken != nil {
price := applyMultiplier(*pricing.CacheCreation12hPricePerToken, iv.CacheWriteMultiplier)
pricing.CacheCreation12hPricePerToken = &price
}
}
if iv.CacheWrite12hPrice != nil {
pricing.CacheCreation12hPricePerToken = iv.CacheWrite12hPrice
} else if iv.CacheWritePrice != nil {
pricing.CacheCreation12hPricePerToken = nil
}
if iv.CacheWrite1hPrice != nil {
pricing.CacheCreation1hPrice = *iv.CacheWrite1hPrice
@@ -0,0 +1,201 @@
//go:build unit
package service
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
// The mixed case is the sanitized usage and channel price card from #8604.
// Observe the actual response handlers and RecordUsage, including the debit and
// account-statistics cost, rather than reconstructing the billing formula there.
func TestOpenAICacheWriteTTLRecordUsage(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tc := range []struct {
name string
short, long int
}{
{"30m", 2399, 0},
{"12h", 0, 2399},
{"mixed", 9, 2390},
} {
for _, route := range []string{"json", "sse", "passthrough_json", "passthrough_sse"} {
t.Run(tc.name+"/"+route, func(t *testing.T) {
const groupID int64 = 777
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
userRepo := &openAIRecordUsageUserRepoStub{}
svc := newOpenAIRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{}, nil)
var pricing ChannelModelPricing
require.NoError(t, json.Unmarshal([]byte(`{"platform":"openai","models":["gpt-6-luna"],"billing_mode":"token","input_price":0.00000065,"output_price":0.00000325,"cache_write_price":0.0000008125,"cache_write_12h_price":0.000001625,"cache_read_price":0.000000065}`), &pricing))
channel := Channel{ID: 1, Status: StatusActive, GroupIDs: []int64{groupID}, ModelPricing: []ChannelModelPricing{pricing}, ApplyPricingToAccountStats: true}
svc.channelService = &ChannelService{}
svc.channelService.cache.Store(populateChannelCache([]Channel{channel}, map[int64]string{groupID: PlatformOpenAI}))
svc.resolver = NewModelPricingResolver(svc.channelService, svc.billingService)
svc.cfg.Gateway.MaxLineSize = defaultMaxLineSize
account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}
response := fmt.Sprintf(`{"id":"resp_ttl","object":"response","model":"gpt-6-luna","status":"completed","output":[],"usage":{"input_tokens":2402,"input_tokens_details":{"cached_tokens":0,"cache_write_tokens":2399,"cache_write_tokens_details":{"ttl_30m_tokens":%d,"ttl_12h_tokens":%d}},"output_tokens":5,"total_tokens":2407}}`, tc.short, tc.long)
stream := strings.HasSuffix(route, "sse")
contentType := "application/json"
if stream {
response = `data: {"type":"response.completed","response":` + response + "}\n\n"
contentType = "text/event-stream"
}
resp := &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {contentType}}, Body: io.NopCloser(strings.NewReader(response))}
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
var usage *OpenAIUsage
switch route {
case "json":
result, err := svc.handleNonStreamingResponse(context.Background(), resp, c, account, "gpt-6-luna", "gpt-6-luna")
require.NoError(t, err)
usage = result.usage
case "sse":
result, err := svc.handleStreamingResponse(context.Background(), resp, c, account, time.Now(), "gpt-6-luna", "gpt-6-luna")
require.NoError(t, err)
usage = result.usage
case "passthrough_json":
result, err := svc.handleNonStreamingResponsePassthrough(context.Background(), resp, c, account, "gpt-6-luna", "gpt-6-luna")
require.NoError(t, err)
usage = result.usage
case "passthrough_sse":
result, err := svc.handleStreamingResponsePassthrough(context.Background(), resp, c, account, time.Now(), "gpt-6-luna", "gpt-6-luna")
require.NoError(t, err)
usage = result.usage
}
require.NotNil(t, usage)
err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
Result: &OpenAIForwardResult{RequestID: "resp_ttl", Model: "gpt-6-luna", Usage: *usage, Stream: stream},
APIKey: &APIKey{ID: 1, GroupID: i64p(groupID), Group: &Group{ID: groupID, Platform: PlatformOpenAI, RateMultiplier: 0.5}},
User: &User{ID: 1}, Account: account,
ChannelUsageFields: ChannelUsageFields{OriginalModel: "gpt-6-luna", BillingModelSource: BillingModelSourceRequested},
})
require.NoError(t, err)
log := usageRepo.lastLog
require.NotNil(t, log)
assert.Equal(t, 3, log.InputTokens)
assert.Equal(t, 2399, log.CacheCreationTokens)
assert.Equal(t, tc.short, log.CacheCreation30mTokens)
assert.Equal(t, tc.long, log.CacheCreation12hTokens)
assert.Zero(t, log.CacheCreation5mTokens)
assert.Zero(t, log.CacheCreation1hTokens)
cacheCost := (float64(tc.short)*0.8125 + float64(tc.long)*1.625) / 1e6
totalCost := cacheCost + 3*0.65/1e6 + 5*3.25/1e6
assert.InDelta(t, cacheCost, log.CacheCreationCost, 1e-12)
assert.InDelta(t, totalCost, log.TotalCost, 1e-12)
assert.InDelta(t, totalCost*0.5, log.ActualCost, 1e-12)
assert.InDelta(t, totalCost*0.5, userRepo.lastAmount, 1e-12)
require.NotNil(t, log.AccountStatsCost)
assert.InDelta(t, totalCost, *log.AccountStatsCost, 1e-12)
})
}
}
}
func TestOpenAICacheWriteTTLInvalidDetailsKeepAggregate(t *testing.T) {
for _, details := range []string{
`null`, `{}`, `{"ttl_12h_tokens":10}`,
`{"ttl_30m_tokens":0,"ttl_12h_tokens":9}`,
`{"ttl_30m_tokens":9,"ttl_12h_tokens":9}`,
`{"ttl_30m_tokens":-1,"ttl_12h_tokens":11}`,
`{"ttl_30m_tokens":0.5,"ttl_12h_tokens":9.5}`,
`{"ttl_30m_tokens":"0","ttl_12h_tokens":"10"}`,
} {
t.Run(details, func(t *testing.T) {
usage, ok := openAIUsageFromGJSON(gjson.Parse(`{"input_tokens":10,"input_tokens_details":{"cache_write_tokens":10,"cache_write_tokens_details":` + details + `}}`))
require.True(t, ok)
require.Equal(t, 10, usage.CacheCreationInputTokens)
require.Zero(t, usage.CacheCreation30mInputTokens)
require.Zero(t, usage.CacheCreation12hInputTokens)
})
}
}
func TestOpenAICacheWriteTTLPrices(t *testing.T) {
service := NewBillingService(nil, nil)
base, err := service.GetModelPricing("gpt-6-luna")
require.NoError(t, err)
tokens := UsageTokens{InputTokens: 3, OutputTokens: 5, CacheCreationTokens: 2399, CacheCreation30mTokens: 9, CacheCreation12hTokens: 2390}
t.Run("catalog 12h rate", func(t *testing.T) {
cost := service.computeTokenBreakdown(base, tokens, 1, "", false)
require.InDelta(t, (9*0.125+2390*0.25)/1e6, cost.CacheCreationCost, 1e-12)
})
t.Run("legacy flat channel price", func(t *testing.T) {
p := *base
applyChannelTokenPriceOverrides(&p, &ChannelModelPricing{CacheWritePrice: float64Ptr(0.8125e-6)})
cost := service.computeTokenBreakdown(&p, tokens, 1, "", false)
require.InDelta(t, 2399*0.8125e-6, cost.CacheCreationCost, 1e-12)
})
for _, tier := range []struct {
name string
rate float64
}{{"default", 1}, {"fast", 2}, {"flex", 0.5}} {
t.Run(tier.name+"/long context and group rate", func(t *testing.T) {
p := *base
applyChannelTokenPriceOverrides(&p, &ChannelModelPricing{
InputPrice: float64Ptr(0.65e-6), OutputPrice: float64Ptr(3.25e-6),
CacheWritePrice: float64Ptr(0.8125e-6), CacheWrite12hPrice: float64Ptr(1.625e-6),
})
p.LongContextInputThreshold = 1
p.LongContextInputMultiplier = 2
p.LongContextOutputMultiplier = 1.5
cost := service.computeTokenBreakdown(&p, tokens, 0.5, tier.name, true)
cacheCost := (9*0.8125 + 2390*1.625) / 1e6 * 2 * tier.rate
want := cacheCost + 3*0.65e-6*2*tier.rate + 5*3.25e-6*1.5*tier.rate
require.InDelta(t, cacheCost, cost.CacheCreationCost, 1e-12)
require.InDelta(t, want*0.5, cost.ActualCost, 1e-12)
})
}
t.Run("Astra catalog ultrafast", func(t *testing.T) {
p, err := service.GetModelPricing("gpt-6-astra")
require.NoError(t, err)
cost := service.computeTokenBreakdown(p, UsageTokens{CacheCreationTokens: 1_000_000, CacheCreation12hTokens: 1_000_000}, 1, "ultrafast", false)
require.InDelta(t, 150, cost.CacheCreationCost, 1e-12)
})
t.Run("explicit free 12h", func(t *testing.T) {
p := *base
applyChannelTokenPriceOverrides(&p, &ChannelModelPricing{CacheWritePrice: float64Ptr(1e-6), CacheWrite12hPrice: float64Ptr(0)})
cost := service.computeTokenBreakdown(&p, tokens, 1, "", false)
require.InDelta(t, 9e-6, cost.CacheCreationCost, 1e-12)
})
t.Run("explicit free 30m with fast 12h", func(t *testing.T) {
p := *base
applyChannelTokenPriceOverrides(&p, &ChannelModelPricing{CacheWritePrice: float64Ptr(0), CacheWrite12hPrice: float64Ptr(2e-6)})
cost := service.computeTokenBreakdown(&p, tokens, 1, "fast", false)
require.InDelta(t, 2390*4e-6, cost.CacheCreationCost, 1e-12)
})
t.Run("missing TTL does not infer a 12h write", func(t *testing.T) {
p := *base
applyChannelTokenPriceOverrides(&p, &ChannelModelPricing{CacheWritePrice: float64Ptr(1e-6), CacheWrite12hPrice: float64Ptr(2e-6)})
cost := service.computeTokenBreakdown(&p, UsageTokens{CacheCreationTokens: 2399}, 1, "", false)
require.InDelta(t, 2399e-6, cost.CacheCreationCost, 1e-12)
})
t.Run("interval scales both write rates", func(t *testing.T) {
p := *base
applyChannelTokenPriceOverrides(&p, &ChannelModelPricing{CacheWritePrice: float64Ptr(1e-6), CacheWrite12hPrice: float64Ptr(2e-6)})
iv := intervalToModelPricing(&PricingInterval{CacheWriteMultiplier: float64Ptr(3)}, &p, nil)
cost := service.computeTokenBreakdown(iv, tokens, 1, "fast", false)
require.InDelta(t, (9*1e-6+2390*2e-6)*3*2, cost.CacheCreationCost, 1e-12)
require.InDelta(t, 2e-6, *p.CacheCreation12hPricePerToken, 1e-12, "the shared base price is immutable")
})
t.Run("account stats custom TTL prices", func(t *testing.T) {
cost := calculateStatsCost(&ChannelModelPricing{
BillingMode: BillingModeToken, CacheWritePrice: float64Ptr(1e-6), CacheWrite12hPrice: float64Ptr(2e-6),
}, tokens, 1)
require.NotNil(t, cost)
require.InDelta(t, 9e-6+2390*2e-6, *cost, 1e-12)
})
}
@@ -1290,6 +1290,8 @@ func mergeOpenAIUsageNonZero(dst *OpenAIUsage, src OpenAIUsage) {
}
if src.CacheCreationInputTokens > 0 {
dst.CacheCreationInputTokens = src.CacheCreationInputTokens
dst.CacheCreation30mInputTokens = src.CacheCreation30mInputTokens
dst.CacheCreation12hInputTokens = src.CacheCreation12hInputTokens
}
if src.CacheReadInputTokens > 0 {
dst.CacheReadInputTokens = src.CacheReadInputTokens
@@ -1563,6 +1565,7 @@ func openAIUsageFromGJSON(value gjson.Result) (OpenAIUsage, bool) {
}
cacheReadTokens := openAICacheReadTokensFromUsage(value)
cacheCreationTokens := openAICacheCreationTokensFromUsage(value)
cache30m, cache12h := openAICacheCreationTTLTokensFromUsage(value, cacheCreationTokens)
imageOutputTokens := value.Get("output_tokens_details.image_tokens").Int()
if imageOutputTokens == 0 {
imageOutputTokens = value.Get("completion_tokens_details.image_tokens").Int()
@@ -1575,12 +1578,14 @@ func openAIUsageFromGJSON(value gjson.Result) (OpenAIUsage, bool) {
value.Get("prompt_tokens_details.image_tokens"),
)
return OpenAIUsage{
InputTokens: int(inputTokens),
ImageInputTokens: imageInputTokens,
OutputTokens: int(outputTokens),
CacheCreationInputTokens: cacheCreationTokens,
CacheReadInputTokens: cacheReadTokens,
ImageOutputTokens: int(imageOutputTokens),
InputTokens: int(inputTokens),
ImageInputTokens: imageInputTokens,
OutputTokens: int(outputTokens),
CacheCreationInputTokens: cacheCreationTokens,
CacheCreation30mInputTokens: cache30m,
CacheCreation12hInputTokens: cache12h,
CacheReadInputTokens: cacheReadTokens,
ImageOutputTokens: int(imageOutputTokens),
}, true
}
@@ -1622,6 +1627,28 @@ func openAICacheCreationTokensFromUsage(value gjson.Result) int {
)
}
// Only reported usage determines the lifetime. Missing, partial or inconsistent
// details keep the aggregate's legacy price; request TTLs cannot prove writes.
func openAICacheCreationTTLTokensFromUsage(value gjson.Result, aggregate int) (int, int) {
for _, path := range []string{"input_tokens_details", "prompt_tokens_details"} {
details := value.Get(path + ".cache_write_tokens_details")
if !details.Exists() {
continue
}
short, long := details.Get("ttl_30m_tokens"), details.Get("ttl_12h_tokens")
if short.Type != gjson.Number || long.Type != gjson.Number {
return 0, 0
}
a, b := short.Int(), long.Int()
if a < 0 || b < 0 || float64(a) != short.Float() || float64(b) != long.Float() ||
a > int64(aggregate) || b != int64(aggregate)-a {
return 0, 0
}
return int(a), int(b)
}
return 0, 0
}
func (s *OpenAIGatewayService) handleNonStreamingResponse(ctx context.Context, resp *http.Response, c *gin.Context, account *Account, originalModel, mappedModel string) (*openaiNonStreamingResult, error) {
body, err := ReadUpstreamResponseBody(resp.Body, s.cfg, c, openAITooLargeError)
if err != nil {
@@ -222,13 +222,15 @@ func (s *OpenAICodexUsageSnapshot) Normalize() *NormalizedCodexLimits {
// OpenAIUsage represents OpenAI API response usage
type OpenAIUsage struct {
InputTokens int `json:"input_tokens"`
ImageInputTokens int `json:"image_input_tokens,omitempty"`
ImageCacheReadTokens int `json:"image_cache_read_tokens,omitempty"`
OutputTokens int `json:"output_tokens"`
CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"`
CacheReadInputTokens int `json:"cache_read_input_tokens,omitempty"`
ImageOutputTokens int `json:"image_output_tokens,omitempty"`
InputTokens int `json:"input_tokens"`
ImageInputTokens int `json:"image_input_tokens,omitempty"`
ImageCacheReadTokens int `json:"image_cache_read_tokens,omitempty"`
OutputTokens int `json:"output_tokens"`
CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"`
CacheCreation30mInputTokens int `json:"cache_creation_30m_input_tokens,omitempty"`
CacheCreation12hInputTokens int `json:"cache_creation_12h_input_tokens,omitempty"`
CacheReadInputTokens int `json:"cache_read_input_tokens,omitempty"`
ImageOutputTokens int `json:"image_output_tokens,omitempty"`
}
// OpenAIForwardResult represents the result of forwarding
@@ -186,13 +186,15 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec
// Calculate cost
tokens := UsageTokens{
InputTokens: actualInputTokens,
ImageInputTokens: max(result.Usage.ImageInputTokens-result.Usage.ImageCacheReadTokens, 0),
ImageCacheReadTokens: result.Usage.ImageCacheReadTokens,
OutputTokens: result.Usage.OutputTokens,
CacheCreationTokens: result.Usage.CacheCreationInputTokens,
CacheReadTokens: result.Usage.CacheReadInputTokens,
ImageOutputTokens: result.Usage.ImageOutputTokens,
InputTokens: actualInputTokens,
ImageInputTokens: max(result.Usage.ImageInputTokens-result.Usage.ImageCacheReadTokens, 0),
ImageCacheReadTokens: result.Usage.ImageCacheReadTokens,
OutputTokens: result.Usage.OutputTokens,
CacheCreationTokens: result.Usage.CacheCreationInputTokens,
CacheCreation30mTokens: result.Usage.CacheCreation30mInputTokens,
CacheCreation12hTokens: result.Usage.CacheCreation12hInputTokens,
CacheReadTokens: result.Usage.CacheReadInputTokens,
ImageOutputTokens: result.Usage.ImageOutputTokens,
}
// Get rate multiplier
@@ -400,6 +402,8 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec
InputTokens: actualInputTokens,
OutputTokens: result.Usage.OutputTokens,
CacheCreationTokens: result.Usage.CacheCreationInputTokens,
CacheCreation30mTokens: result.Usage.CacheCreation30mInputTokens,
CacheCreation12hTokens: result.Usage.CacheCreation12hInputTokens,
CacheReadTokens: result.Usage.CacheReadInputTokens,
ImageInputTokens: result.Usage.ImageInputTokens,
ImageOutputTokens: result.Usage.ImageOutputTokens,
+4 -2
View File
@@ -152,8 +152,10 @@ type UsageLog struct {
CacheCreationTokens int
CacheReadTokens int
CacheCreation5mTokens int `gorm:"column:cache_creation_5m_tokens"`
CacheCreation1hTokens int `gorm:"column:cache_creation_1h_tokens"`
CacheCreation5mTokens int `gorm:"column:cache_creation_5m_tokens"`
CacheCreation1hTokens int `gorm:"column:cache_creation_1h_tokens"`
CacheCreation30mTokens int `gorm:"column:cache_creation_30m_tokens"`
CacheCreation12hTokens int `gorm:"column:cache_creation_12h_tokens"`
ImageInputTokens int
ImageInputCost float64
@@ -0,0 +1,25 @@
-- OpenAI cache-write lifetimes are separate from Anthropic 5m/1h buckets.
ALTER TABLE usage_logs
ADD COLUMN IF NOT EXISTS cache_creation_30m_tokens INTEGER NOT NULL DEFAULT 0,
ADD COLUMN IF NOT EXISTS cache_creation_12h_tokens INTEGER NOT NULL DEFAULT 0;
ALTER TABLE channel_model_pricing
ADD COLUMN IF NOT EXISTS cache_write_12h_price NUMERIC(20,12);
COMMENT ON COLUMN channel_model_pricing.cache_write_12h_price IS
'OpenAI 12h cache write price per token; NULL preserves the generic cache_write_price';
ALTER TABLE channel_pricing_intervals
ADD COLUMN IF NOT EXISTS cache_write_12h_price NUMERIC(20,12);
COMMENT ON COLUMN channel_pricing_intervals.cache_write_12h_price IS
'OpenAI 12h cache write price per token; NULL preserves the generic cache_write_price';
ALTER TABLE channel_account_stats_model_pricing
ADD COLUMN IF NOT EXISTS cache_write_12h_price NUMERIC(20,12);
COMMENT ON COLUMN channel_account_stats_model_pricing.cache_write_12h_price IS
'OpenAI 12h cache write price per token; NULL preserves the generic cache_write_price';
ALTER TABLE channel_account_stats_pricing_intervals
ADD COLUMN IF NOT EXISTS cache_write_12h_price NUMERIC(20,12);
COMMENT ON COLUMN channel_account_stats_pricing_intervals.cache_write_12h_price IS
'OpenAI 12h cache write price per token; NULL preserves the generic cache_write_price';
+3
View File
@@ -17,6 +17,7 @@ export interface PricingInterval {
output_price: number | null
cache_write_price: number | null
cache_write_1h_price?: number | null
cache_write_12h_price?: number | null
cache_read_price: number | null
input_multiplier: number | null
output_multiplier: number | null
@@ -47,6 +48,7 @@ export interface ChannelModelPricing {
output_price: number | null
cache_write_price: number | null
cache_write_1h_price?: number | null
cache_write_12h_price?: number | null
cache_read_price: number | null
fast_multiplier?: number | null
flex_multiplier?: number | null
@@ -177,6 +179,7 @@ export interface ModelDefaultPricing {
output_price?: number
cache_write_price?: number
cache_write_1h_price?: number | null
cache_write_12h_price?: number | null
cache_read_price?: number
image_input_price?: number
image_output_price?: number
+2
View File
@@ -30,6 +30,7 @@ export interface UserPricingInterval {
output_price: number | null
cache_write_price: number | null
cache_write_1h_price?: number | null
cache_write_12h_price?: number | null
cache_read_price: number | null
input_multiplier?: number | null
output_multiplier?: number | null
@@ -44,6 +45,7 @@ export interface UserSupportedModelPricing {
output_price: number | null
cache_write_price: number | null
cache_write_1h_price?: number | null
cache_write_12h_price?: number | null
cache_read_price: number | null
reasoning_effort_multipliers?: Record<string, number> | null
image_input_price: number | null
+1
View File
@@ -15,6 +15,7 @@ export interface PlazaOfficialPricing {
cache_write_price: number | null
/** 1h 缓存写入(LiteLLM cache_creation_above_1hr),多数模型缺失。 */
cache_write_1h_price?: number | null
cache_write_12h_price?: number | null
cache_read_price: number | null
/** 官方长上下文阶梯(多档模型才有),不受分组开关影响。 */
intervals?: UserPricingInterval[]
@@ -25,15 +25,20 @@
type="number" step="any" min="0" class="input mt-0.5 text-xs" />
</div>
<div>
<label class="text-xs text-gray-400">{{ t('admin.channels.form.cacheWrite5mPriceShort') }} <span class="text-gray-300">$/M</span></label>
<label class="text-xs text-gray-400">{{ t(props.platform === 'openai' ? 'admin.channels.form.cacheWrite30mPrice' : 'admin.channels.form.cacheWrite5mPriceShort') }} <span class="text-gray-300">$/M</span></label>
<input :value="interval.cache_write_price" @input="emitField('cache_write_price', ($event.target as HTMLInputElement).value)"
type="number" step="any" min="0" class="input mt-0.5 text-xs" />
</div>
<div>
<div v-if="props.platform !== 'openai'">
<label class="text-xs text-gray-400">{{ t('admin.channels.form.cacheWrite1hPriceShort') }} <span class="text-gray-300">$/M</span></label>
<input :value="interval.cache_write_1h_price" @input="emitField('cache_write_1h_price', ($event.target as HTMLInputElement).value)"
type="number" step="any" min="0" class="input mt-0.5 text-xs" />
</div>
<div v-if="props.platform === 'openai'">
<label class="text-xs text-gray-400">{{ t('admin.channels.form.cacheWrite12hPriceShort') }} <span class="text-gray-300">$/M</span></label>
<input :value="interval.cache_write_12h_price" @input="emitField('cache_write_12h_price', ($event.target as HTMLInputElement).value)"
type="number" step="any" min="0" class="input mt-0.5 text-xs" />
</div>
<div>
<label class="text-xs text-gray-400">{{ t('admin.channels.form.cacheReadPriceShort') }} <span class="text-gray-300">$/M</span></label>
<input :value="interval.cache_read_price" @input="emitField('cache_read_price', ($event.target as HTMLInputElement).value)"
@@ -108,6 +113,7 @@ const { t } = useI18n()
const props = defineProps<{
interval: IntervalFormEntry
mode: BillingMode
platform?: string
enableMultipliers?: boolean
}>()
@@ -123,6 +129,7 @@ const isEmpty = computed(() => {
(iv.output_price == null || iv.output_price === '') &&
(iv.cache_write_price == null || iv.cache_write_price === '') &&
(iv.cache_write_1h_price == null || iv.cache_write_1h_price === '') &&
(iv.cache_write_12h_price == null || iv.cache_write_12h_price === '') &&
(iv.cache_read_price == null || iv.cache_read_price === '') &&
(iv.input_multiplier == null || iv.input_multiplier === '') &&
(iv.output_multiplier == null || iv.output_multiplier === '') &&
@@ -118,15 +118,20 @@
type="number" step="any" min="0" class="input mt-0.5 text-sm" :placeholder="t('admin.channels.form.pricePlaceholder')" />
</div>
<div>
<label class="text-xs text-gray-400">{{ t('admin.channels.form.cacheWrite5mPrice') }}</label>
<label class="text-xs text-gray-400">{{ t(props.platform === 'openai' ? 'admin.channels.form.cacheWrite30mPrice' : 'admin.channels.form.cacheWrite5mPrice') }}</label>
<input :value="entry.cache_write_price" @input="emitField('cache_write_price', ($event.target as HTMLInputElement).value)"
type="number" step="any" min="0" class="input mt-0.5 text-sm" :placeholder="t('admin.channels.form.pricePlaceholder')" />
</div>
<div>
<div v-if="props.platform !== 'openai'">
<label class="text-xs text-gray-400">{{ t('admin.channels.form.cacheWrite1hPrice') }}</label>
<input :value="entry.cache_write_1h_price" @input="emitField('cache_write_1h_price', ($event.target as HTMLInputElement).value)"
type="number" step="any" min="0" class="input mt-0.5 text-sm" :placeholder="t('admin.channels.form.pricePlaceholder')" />
</div>
<div v-if="props.platform === 'openai'">
<label class="text-xs text-gray-400" :title="t('admin.channels.form.cacheWrite12hHint')">{{ t('admin.channels.form.cacheWrite12hPrice') }}</label>
<input :value="entry.cache_write_12h_price" @input="emitField('cache_write_12h_price', ($event.target as HTMLInputElement).value)"
type="number" step="any" min="0" class="input mt-0.5 text-sm" :placeholder="t('admin.channels.form.pricePlaceholder')" />
</div>
<div>
<label class="text-xs text-gray-400">{{ t('admin.channels.form.cacheReadPrice') }}</label>
<input :value="entry.cache_read_price" @input="emitField('cache_read_price', ($event.target as HTMLInputElement).value)"
@@ -173,6 +178,7 @@
v-for="(iv, idx) in entry.intervals"
:key="idx"
:interval="iv"
:platform="props.platform"
:mode="entry.billing_mode"
:enable-multipliers="enableTierMultipliers"
@update="updateInterval(idx, $event)"
@@ -370,6 +376,7 @@ function addInterval() {
min_tokens: 0, max_tokens: null, tier_label: '',
input_price: null, output_price: null, cache_write_price: null,
cache_write_1h_price: null,
cache_write_12h_price: null,
cache_read_price: null, per_request_price: null,
input_multiplier: null, output_multiplier: null,
cache_write_multiplier: null, cache_read_multiplier: null,
@@ -387,6 +394,7 @@ function addMediaTier() {
min_tokens: 0, max_tokens: null, tier_label: labels[intervals.length] || '',
input_price: null, output_price: null, cache_write_price: null,
cache_write_1h_price: null,
cache_write_12h_price: null,
cache_read_price: null, per_request_price: null,
input_multiplier: null, output_multiplier: null,
cache_write_multiplier: null, cache_read_multiplier: null,
@@ -420,7 +428,7 @@ async function onModelsUpdate(newModels: string[]) {
// 检查是否所有价格字段都为空
const e = props.entry
const hasPrice = e.input_price != null || e.output_price != null ||
e.cache_write_price != null || e.cache_write_1h_price != null || e.cache_read_price != null
e.cache_write_price != null || e.cache_write_1h_price != null || e.cache_write_12h_price != null || e.cache_read_price != null
if (hasPrice) return
// 查询第一个新增模型的默认价格
@@ -434,6 +442,7 @@ async function onModelsUpdate(newModels: string[]) {
output_price: perTokenToMTok(result.output_price ?? null),
cache_write_price: perTokenToMTok(result.cache_write_price ?? null),
cache_write_1h_price: perTokenToMTok(result.cache_write_1h_price ?? null),
cache_write_12h_price: perTokenToMTok(result.cache_write_12h_price ?? null),
cache_read_price: perTokenToMTok(result.cache_read_price ?? null),
image_input_price: perTokenToMTok(result.image_input_price ?? null),
image_output_price: perTokenToMTok(result.image_output_price ?? null),
@@ -42,6 +42,14 @@ describe('reasoning effort multipliers', () => {
})
describe('interval multiplier conversion', () => {
it('round-trips independent OpenAI TTL prices and explicit zero', () => {
const form = [makeInterval({ cache_write_price: 0, cache_write_12h_price: '1.625' })]
const serialized = formIntervalsToAPI(form)
expect(serialized[0]).toMatchObject({ cache_write_price: 0, cache_write_12h_price: 0.000001625 })
expect(apiIntervalsToForm(serialized)[0]).toMatchObject({ cache_write_price: 0, cache_write_12h_price: 1.625 })
expect(validateIntervals([makeInterval({ cache_write_12h_price: -1 })], 'token', t)).toContain('negativePrice')
})
it('preserves component multipliers without MTok conversion', () => {
const form = apiIntervalsToForm([{
min_tokens: 272000,
@@ -11,6 +11,7 @@ export interface IntervalFormEntry {
output_price: number | string | null
cache_write_price: number | string | null
cache_write_1h_price?: number | string | null
cache_write_12h_price?: number | string | null
cache_read_price: number | string | null
input_multiplier: number | string | null
output_multiplier: number | string | null
@@ -27,6 +28,7 @@ export interface PricingFormEntry {
output_price: number | string | null
cache_write_price: number | string | null
cache_write_1h_price?: number | string | null
cache_write_12h_price?: number | string | null
cache_read_price: number | string | null
fast_multiplier?: number | string | null
flex_multiplier?: number | string | null
@@ -229,6 +231,7 @@ export function apiIntervalsToForm(intervals: PricingInterval[]): IntervalFormEn
output_price: perTokenToMTok(iv.output_price),
cache_write_price: perTokenToMTok(iv.cache_write_price),
cache_write_1h_price: perTokenToMTok(iv.cache_write_1h_price),
cache_write_12h_price: perTokenToMTok(iv.cache_write_12h_price),
cache_read_price: perTokenToMTok(iv.cache_read_price),
input_multiplier: iv.input_multiplier,
output_multiplier: iv.output_multiplier,
@@ -248,6 +251,7 @@ export function formIntervalsToAPI(intervals: IntervalFormEntry[]): PricingInter
output_price: mTokToPerToken(iv.output_price),
cache_write_price: mTokToPerToken(iv.cache_write_price),
cache_write_1h_price: mTokToPerToken(iv.cache_write_1h_price),
cache_write_12h_price: mTokToPerToken(iv.cache_write_12h_price),
cache_read_price: mTokToPerToken(iv.cache_read_price),
input_multiplier: toNullableNumber(iv.input_multiplier),
output_multiplier: toNullableNumber(iv.output_multiplier),
@@ -373,6 +377,7 @@ function validateIntervalPrices(iv: IntervalFormEntry, idx: number, t: Translate
['outputPrice', iv.output_price],
['cacheWritePrice', iv.cache_write_price],
['cacheWrite1hPrice', iv.cache_write_1h_price ?? null],
['cacheWrite12hPrice', iv.cache_write_12h_price ?? null],
['cacheReadPrice', iv.cache_read_price],
['perRequestPrice', iv.per_request_price],
]
@@ -176,6 +176,7 @@
<svg class="h-3.5 w-3.5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" /></svg>
<span class="font-medium text-amber-600 dark:text-amber-400">{{ formatCacheTokens(row.cache_creation_tokens) }}</span>
<span v-if="row.cache_creation_1h_tokens > 0" class="inline-flex items-center rounded px-1 py-px text-[10px] font-medium leading-tight bg-orange-100 text-orange-600 ring-1 ring-inset ring-orange-200 dark:bg-orange-500/20 dark:text-orange-400 dark:ring-orange-500/30">1h</span>
<span v-if="(row.cache_creation_12h_tokens ?? 0) > 0" class="inline-flex items-center rounded px-1 py-px text-[10px] font-medium leading-tight bg-orange-100 text-orange-600 ring-1 ring-inset ring-orange-200 dark:bg-orange-500/20 dark:text-orange-400 dark:ring-orange-500/30">12h</span>
<span v-if="row.cache_ttl_overridden" :title="t('usage.cacheTtlOverriddenHint')" class="inline-flex items-center rounded px-1 py-px text-[10px] font-medium leading-tight bg-rose-100 text-rose-600 ring-1 ring-inset ring-rose-200 dark:bg-rose-500/20 dark:text-rose-400 dark:ring-rose-500/30 cursor-help">R</span>
</div>
</div>
@@ -351,8 +352,8 @@
<span class="font-medium text-pink-300">{{ tokenTooltipData.image_output_tokens.toLocaleString() }}</span>
</div>
<div v-if="tokenTooltipData && tokenTooltipData.cache_creation_tokens > 0">
<!-- 有 5m/1h 明细时,展开显示 -->
<template v-if="tokenTooltipData.cache_creation_5m_tokens > 0 || tokenTooltipData.cache_creation_1h_tokens > 0">
<!-- Expand only the lifetimes reported by the upstream. -->
<template v-if="tokenTooltipData.cache_creation_5m_tokens > 0 || tokenTooltipData.cache_creation_1h_tokens > 0 || (tokenTooltipData.cache_creation_30m_tokens ?? 0) > 0 || (tokenTooltipData.cache_creation_12h_tokens ?? 0) > 0">
<div v-if="tokenTooltipData.cache_creation_5m_tokens > 0" class="flex items-center justify-between gap-4">
<span class="text-gray-400 flex items-center gap-1.5">
{{ t('admin.usage.cacheCreation5mTokens') }}
@@ -367,6 +368,15 @@
</span>
<span class="font-medium text-white">{{ tokenTooltipData.cache_creation_1h_tokens.toLocaleString() }}</span>
</div>
<template v-for="bucket in [{ ttl: '30m', tokens: tokenTooltipData.cache_creation_30m_tokens ?? 0 }, { ttl: '12h', tokens: tokenTooltipData.cache_creation_12h_tokens ?? 0 }]" :key="bucket.ttl">
<div v-if="bucket.tokens > 0" class="flex items-center justify-between gap-4">
<span class="text-gray-400 flex items-center gap-1.5">
{{ t('admin.usage.cacheCreationTokens') }}
<span class="inline-flex items-center rounded px-1 py-px text-[10px] font-medium leading-tight bg-amber-500/20 text-amber-400 ring-1 ring-inset ring-amber-500/30">{{ bucket.ttl }}</span>
</span>
<span class="font-medium text-white">{{ bucket.tokens.toLocaleString() }}</span>
</div>
</template>
</template>
<!-- 无明细时,只显示聚合值 -->
<div v-else class="flex items-center justify-between gap-4">
@@ -145,6 +145,26 @@ const baseImageRow = {
}
describe('admin UsageTable tooltip', () => {
it('shows the two OpenAI cache-write buckets without Anthropic lifetime labels', async () => {
const row = { ...baseImageRow, image_count: 0, billing_mode: 'token', cache_creation_tokens: 2399, cache_creation_30m_tokens: 9, cache_creation_12h_tokens: 2390 }
const wrapper = mount(UsageTable, {
props: { data: [row], loading: false, columns: [] },
global: { stubs: { DataTable: DataTableStub, EmptyState: true, Icon: true, Teleport: true } },
})
try {
await wrapper.find('.group.relative').trigger('mouseenter')
await nextTick()
const text = wrapper.get('.fixed').text()
expect(text).toContain('30m')
expect(text).toContain('12h')
expect(text).toContain('2,390')
expect(text).not.toContain('5m')
expect(text).not.toMatch(/\b1h\b/)
} finally {
wrapper.unmount()
}
})
it('shows output TPS in the latency cell using total duration', () => {
const row = { ...baseImageRow, image_count: 0, billing_mode: 'token', output_tokens: 1000, duration_ms: 20_000, first_token_ms: 10_000 }
const wrapper = mount(UsageTable, {
@@ -91,6 +91,13 @@
:unit="t(prefixKey('unitPerMillion'))"
:scale="perMillionScale"
/>
<PricingRow
v-if="model.pricing.cache_write_12h_price != null"
:label="t(prefixKey('cacheWrite12hPrice'))"
:value="model.pricing.cache_write_12h_price"
:unit="t(prefixKey('unitPerMillion'))"
:scale="perMillionScale"
/>
<PricingRow
:label="t(prefixKey('cacheReadPrice'))"
:value="model.pricing.cache_read_price"
@@ -147,12 +147,15 @@
class="whitespace-nowrap font-mono text-xs leading-5 text-gray-800 dark:text-gray-200"
:title="tierHint(m)"
>
<template v-if="iv.cache_write_price != null || iv.cache_write_1h_price != null || iv.cache_read_price != null">
<template v-if="iv.cache_write_price != null || iv.cache_write_1h_price != null || iv.cache_write_12h_price != null || iv.cache_read_price != null">
<span class="font-sans font-normal text-gray-400 dark:text-dark-500">{{ t('modelPlaza.table.cacheWriteShort') }}</span>
{{ paidPerMillion(iv.cache_write_price, period) }}
<template v-if="iv.cache_write_1h_price != null"
><span class="font-sans font-normal text-gray-400 dark:text-dark-500"> (1h </span>{{ paidPerMillion(iv.cache_write_1h_price, period)
}}<span class="font-sans font-normal text-gray-400 dark:text-dark-500">)</span></template
><template v-if="iv.cache_write_12h_price != null"
><span class="font-sans font-normal text-gray-400 dark:text-dark-500"> (12h </span>{{ paidPerMillion(iv.cache_write_12h_price, period)
}}<span class="font-sans font-normal text-gray-400 dark:text-dark-500">)</span></template
>
<span class="ml-1 font-sans font-normal text-gray-400 dark:text-dark-500">{{ t('modelPlaza.table.cacheReadShort') }}</span>
{{ paidPerMillion(iv.cache_read_price, period) }}
@@ -170,6 +173,9 @@
}}<template v-if="m.pricing?.cache_write_1h_price != null"
><span class="font-sans font-normal text-gray-400 dark:text-dark-500"> (1h </span>{{ paidPerMillion(m.pricing.cache_write_1h_price, period)
}}<span class="font-sans font-normal text-gray-400 dark:text-dark-500">)</span></template
><template v-if="m.pricing?.cache_write_12h_price != null"
><span class="font-sans font-normal text-gray-400 dark:text-dark-500"> (12h </span>{{ paidPerMillion(m.pricing.cache_write_12h_price, period)
}}<span class="font-sans font-normal text-gray-400 dark:text-dark-500">)</span></template
>
</div>
<div>
@@ -245,12 +251,15 @@
class="whitespace-nowrap font-mono text-xs leading-5 text-gray-500 dark:text-dark-400"
:title="t('modelPlaza.table.tierHint')"
>
<template v-if="iv.cache_write_price != null || iv.cache_write_1h_price != null || iv.cache_read_price != null">
<template v-if="iv.cache_write_price != null || iv.cache_write_1h_price != null || iv.cache_write_12h_price != null || iv.cache_read_price != null">
<span class="font-sans text-gray-400 dark:text-dark-500">{{ t('modelPlaza.table.cacheWriteShort') }}</span>
{{ official(iv.cache_write_price) }}
<template v-if="iv.cache_write_1h_price != null"
><span class="font-sans text-gray-400 dark:text-dark-500"> (1h </span>{{ official(iv.cache_write_1h_price)
}}<span class="font-sans text-gray-400 dark:text-dark-500">)</span></template
><template v-if="iv.cache_write_12h_price != null"
><span class="font-sans text-gray-400 dark:text-dark-500"> (12h </span>{{ official(iv.cache_write_12h_price)
}}<span class="font-sans text-gray-400 dark:text-dark-500">)</span></template
>
<span class="ml-1 font-sans text-gray-400 dark:text-dark-500">{{ t('modelPlaza.table.cacheReadShort') }}</span>
{{ official(iv.cache_read_price) }}
@@ -268,6 +277,9 @@
}}<template v-if="m.official_pricing.cache_write_1h_price != null"
><span class="font-sans text-gray-400 dark:text-dark-500"> (1h </span>{{ official(m.official_pricing.cache_write_1h_price)
}}<span class="font-sans text-gray-400 dark:text-dark-500">)</span></template
><template v-if="m.official_pricing.cache_write_12h_price != null"
><span class="font-sans text-gray-400 dark:text-dark-500"> (12h </span>{{ official(m.official_pricing.cache_write_12h_price)
}}<span class="font-sans text-gray-400 dark:text-dark-500">)</span></template
>
</div>
<div>
@@ -465,11 +477,11 @@ function perUnitSuffix(m: PlazaModel): string {
}
function hasCachePricing(m: PlazaModel): boolean {
return m.pricing?.cache_write_price != null || m.pricing?.cache_write_1h_price != null || m.pricing?.cache_read_price != null
return m.pricing?.cache_write_price != null || m.pricing?.cache_write_1h_price != null || m.pricing?.cache_write_12h_price != null || m.pricing?.cache_read_price != null
}
function hasOfficialCache(o: NonNullable<PlazaModel['official_pricing']>): boolean {
return o.cache_write_price != null || o.cache_read_price != null || o.cache_write_1h_price != null
return o.cache_write_price != null || o.cache_read_price != null || o.cache_write_1h_price != null || o.cache_write_12h_price != null
}
/** 分时倍率时段(后端只给出倍率 ≠ 1 的时段,已升序)。 */
@@ -519,7 +531,7 @@ function officialIntervals(m: PlazaModel): UserPricingInterval[] {
/** 任一档带缓存价才按档渲染缓存列;否则沿用平价的写入/读取两行。 */
function hasTierCachePricing(intervals: UserPricingInterval[]): boolean {
return intervals.some((iv) =>
iv.cache_write_price != null || iv.cache_write_1h_price != null || iv.cache_read_price != null ||
iv.cache_write_price != null || iv.cache_write_1h_price != null || iv.cache_write_12h_price != null || iv.cache_read_price != null ||
iv.cache_write_multiplier != null || iv.cache_read_multiplier != null
)
}
@@ -58,6 +58,26 @@ function mountTable(
}
describe('PlazaModelPricingTable', () => {
it.each([false, true])('shows independent 12h prices without a 1h label (intervals=%s)', (intervals) => {
const model = tokenModel({ name: 'gpt-6-luna', platform: 'openai' })
model.pricing!.cache_write_price = null
model.pricing!.cache_write_12h_price = 2e-6
model.pricing!.cache_read_price = null
model.official_pricing = { input_price: 1e-6, output_price: 5e-6, cache_write_price: null, cache_write_12h_price: 4e-6, cache_read_price: null }
if (intervals) {
model.pricing!.intervals = [{ min_tokens: 0, max_tokens: null, input_price: null, output_price: null, cache_write_price: null, cache_write_12h_price: 2e-6, cache_read_price: null, per_request_price: null }]
model.official_pricing.intervals = [{ min_tokens: 0, max_tokens: null, input_price: 1e-6, output_price: 5e-6, cache_write_price: null, cache_write_12h_price: 4e-6, cache_read_price: null, per_request_price: null }]
}
const wrapper = mountTable([model], 0.5)
try {
expect(wrapper.text()).toContain('(12h $1.00)')
expect(wrapper.text()).toContain('(12h $4.00)')
expect(wrapper.text()).not.toContain('(1h')
} finally {
wrapper.unmount()
}
})
it.each([
{ enabled: true, multiplier: 1, userRate: 0.05, expected: 1 },
{ enabled: true, multiplier: 0.5, userRate: null, expected: 0.5 },
@@ -33,7 +33,10 @@ export default {
outputPrice: 'Output',
cacheWritePrice: 'Cache Write',
cacheWrite5mPrice: 'Cache Write (5m)',
cacheWrite30mPrice: 'Cache Write (30m)',
cacheWrite12hHint: 'Leave empty to use the generic cache-write price. Applies only to reported OpenAI 12h writes.',
cacheWrite1hPrice: 'Cache Write (1h)',
cacheWrite12hPrice: 'Cache Write (12h)',
cacheReadPrice: 'Cache Read',
imageOutputPrice: 'Image Output',
perRequestPrice: 'Per Request',
@@ -84,6 +87,7 @@ export default {
outputPrice: 'output price',
cacheWritePrice: 'cache write price',
cacheWrite1hPrice: '1h cache write price',
cacheWrite12hPrice: '12h cache write price',
cacheReadPrice: 'cache read price',
perRequestPrice: 'per-request price'
}
@@ -130,11 +134,15 @@ export default {
outputPrice: 'Output',
cacheWritePrice: 'Cache Write',
cacheWrite5mPrice: 'Cache Write (5m)',
cacheWrite30mPrice: 'Cache Write (30m)',
cacheWrite12hHint: 'Leave empty to use the generic cache-write price. Applies only to reported OpenAI 12h writes.',
cacheWrite1hPrice: 'Cache Write (1h)',
cacheWrite12hPrice: 'Cache Write (12h)',
cacheReadPrice: 'Cache Read',
cacheWritePriceShort: 'Cache W',
cacheWrite5mPriceShort: 'Cache W 5m',
cacheWrite1hPriceShort: 'Cache W 1h',
cacheWrite12hPriceShort: 'Cache W 12h',
cacheReadPriceShort: 'Cache R',
imageInputPrice: 'Image Input',
imageTokenPrice: 'Image Output',
@@ -639,6 +639,7 @@ export default {
cacheWritePrice: 'Cache Write',
cacheWrite5mPrice: 'Cache Write (5m)',
cacheWrite1hPrice: 'Cache Write (1h)',
cacheWrite12hPrice: 'Cache Write (12h)',
cacheReadPrice: 'Cache Read',
imageInputPrice: 'Image Input',
imageOutputPrice: 'Image Output',
@@ -33,7 +33,10 @@ export default {
outputPrice: '输出',
cacheWritePrice: '缓存写入',
cacheWrite5mPrice: '缓存写入(5m)',
cacheWrite30mPrice: '缓存写入(30m)',
cacheWrite12hHint: '留空沿用通用缓存写入价,仅对上游报告的 OpenAI 12h 写入生效。',
cacheWrite1hPrice: '缓存写入(1h)',
cacheWrite12hPrice: '缓存写入(12h)',
cacheReadPrice: '缓存读取',
imageOutputPrice: '图片输出',
perRequestPrice: '每次请求',
@@ -84,6 +87,7 @@ export default {
outputPrice: '输出价格',
cacheWritePrice: '缓存写入价格',
cacheWrite1hPrice: '1h 缓存写入价格',
cacheWrite12hPrice: '12h 缓存写入价格',
cacheReadPrice: '缓存读取价格',
perRequestPrice: '单次价格'
}
@@ -130,11 +134,15 @@ export default {
outputPrice: '输出',
cacheWritePrice: '缓存写入',
cacheWrite5mPrice: '缓存写入(5m)',
cacheWrite30mPrice: '缓存写入(30m)',
cacheWrite12hHint: '留空沿用通用缓存写入价,仅对上游报告的 OpenAI 12h 写入生效。',
cacheWrite1hPrice: '缓存写入(1h)',
cacheWrite12hPrice: '缓存写入(12h)',
cacheReadPrice: '缓存读取',
cacheWritePriceShort: '缓存写',
cacheWrite5mPriceShort: '缓存写 5m',
cacheWrite1hPriceShort: '缓存写 1h',
cacheWrite12hPriceShort: '缓存写 12h',
cacheReadPriceShort: '缓存读',
imageInputPrice: '图片输入',
imageTokenPrice: '图片输出',
@@ -644,6 +644,7 @@ export default {
cacheWritePrice: '缓存写入',
cacheWrite5mPrice: '缓存写入(5m)',
cacheWrite1hPrice: '缓存写入(1h)',
cacheWrite12hPrice: '缓存写入(12h)',
cacheReadPrice: '缓存读取',
imageInputPrice: '图片输入',
imageOutputPrice: '图片输出',
+2
View File
@@ -1839,6 +1839,8 @@ export interface UsageLog {
cache_read_tokens: number
cache_creation_5m_tokens: number
cache_creation_1h_tokens: number
cache_creation_30m_tokens?: number
cache_creation_12h_tokens?: number
input_cost: number
output_cost: number
@@ -7,6 +7,7 @@ const interval = { min_tokens: 272000, max_tokens: null, input_price: null, outp
describe('resolveIntervalPrices', () => {
it('inherits base prices without overrides', () => {
expect(resolveIntervalPrices(interval, base)).toMatchObject(base)
expect(resolveIntervalPrices(interval, base).cache_write_12h_price).toBeNull()
})
it('applies cache multiplier to both durations', () => {
expect(resolveIntervalPrices({ ...interval, cache_write_multiplier: 2 }, base)).toMatchObject({ cache_write_price: 25, cache_write_1h_price: 60 })
@@ -17,4 +18,13 @@ describe('resolveIntervalPrices', () => {
it('preserves explicit zero and separate 1h override', () => {
expect(resolveIntervalPrices({ ...interval, cache_write_price: 0, cache_write_1h_price: 7, cache_write_multiplier: 2 }, base)).toMatchObject({ cache_write_price: 0, cache_write_1h_price: 7 })
})
it('inherits and scales the OpenAI 12h rate independently', () => {
const openai = { ...base, cache_write_12h_price: 25 }
expect(resolveIntervalPrices({ ...interval, cache_write_multiplier: 2 }, openai))
.toMatchObject({ cache_write_price: 25, cache_write_12h_price: 50 })
expect(resolveIntervalPrices({ ...interval, cache_write_12h_price: 0, cache_write_multiplier: 2 }, openai))
.toMatchObject({ cache_write_price: 25, cache_write_12h_price: 0 })
expect(resolveIntervalPrices({ ...interval, cache_write_price: 7 }, openai))
.toMatchObject({ cache_write_price: 7, cache_write_12h_price: 7 })
})
})
+2 -1
View File
@@ -25,7 +25,7 @@ export function formatScaled(value: number | null, scale: number, minFractionDig
import type { UserPricingInterval } from '@/api/channels'
type TokenPrices = Pick<UserPricingInterval, 'input_price' | 'output_price' | 'cache_write_price' | 'cache_write_1h_price' | 'cache_read_price'>
type TokenPrices = Pick<UserPricingInterval, 'input_price' | 'output_price' | 'cache_write_price' | 'cache_write_1h_price' | 'cache_write_12h_price' | 'cache_read_price'>
export function resolveIntervalPrices(iv: UserPricingInterval, base: TokenPrices): UserPricingInterval {
const price = (absolute: number | null | undefined, multiplier: number | null | undefined, fallback: number | null | undefined) =>
@@ -37,6 +37,7 @@ export function resolveIntervalPrices(iv: UserPricingInterval, base: TokenPrices
cache_write_price: price(iv.cache_write_price, iv.cache_write_multiplier, base.cache_write_price),
// Resolver uses an explicit cache-write price for both durations unless 1h is overridden.
cache_write_1h_price: iv.cache_write_1h_price ?? iv.cache_write_price ?? price(null, iv.cache_write_multiplier, base.cache_write_1h_price),
cache_write_12h_price: iv.cache_write_12h_price ?? (base.cache_write_12h_price == null ? null : iv.cache_write_price ?? price(null, iv.cache_write_multiplier, base.cache_write_12h_price)),
cache_read_price: price(iv.cache_read_price, iv.cache_read_multiplier, base.cache_read_price)
}
}
@@ -879,6 +879,7 @@ function addPricingEntry(sectionIdx: number) {
output_price: null,
cache_write_price: null,
cache_write_1h_price: null,
cache_write_12h_price: null,
cache_read_price: null,
fast_multiplier: null,
flex_multiplier: null,
@@ -918,6 +919,7 @@ async function syncLatestModels(sectionIdx: number) {
output_price: null,
cache_write_price: null,
cache_write_1h_price: null,
cache_write_12h_price: null,
cache_read_price: null,
fast_multiplier: null,
flex_multiplier: null,
@@ -988,6 +990,7 @@ function addRulePricingEntry(sectionIdx: number, ruleIndex: number) {
output_price: null,
cache_write_price: null,
cache_write_1h_price: null,
cache_write_12h_price: null,
cache_read_price: null,
image_input_price: null,
image_output_price: null,
@@ -1106,6 +1109,7 @@ function accountStatsRulesToAPI(): AccountStatsPricingRule[] {
output_price: mTokToPerToken(p.output_price),
cache_write_price: mTokToPerToken(p.cache_write_price),
cache_write_1h_price: mTokToPerToken(p.cache_write_1h_price),
cache_write_12h_price: mTokToPerToken(p.cache_write_12h_price),
cache_read_price: mTokToPerToken(p.cache_read_price),
reasoning_effort_multipliers: formReasoningEffortMultipliersToAPI(p.reasoning_effort_multipliers),
image_input_price: mTokToPerToken(p.image_input_price),
@@ -1150,6 +1154,7 @@ function formToAPI(): { group_ids: number[], model_pricing: ChannelModelPricing[
output_price: mTokToPerToken(entry.output_price),
cache_write_price: mTokToPerToken(entry.cache_write_price),
cache_write_1h_price: mTokToPerToken(entry.cache_write_1h_price),
cache_write_12h_price: mTokToPerToken(entry.cache_write_12h_price),
cache_read_price: mTokToPerToken(entry.cache_read_price),
fast_multiplier: entry.fast_multiplier != null && entry.fast_multiplier !== '' ? Number(entry.fast_multiplier) : null,
flex_multiplier: entry.flex_multiplier != null && entry.flex_multiplier !== '' ? Number(entry.flex_multiplier) : null,
@@ -1251,6 +1256,7 @@ function apiToForm(channel: Channel): PlatformSection[] {
output_price: perTokenToMTok(p.output_price),
cache_write_price: perTokenToMTok(p.cache_write_price),
cache_write_1h_price: perTokenToMTok(p.cache_write_1h_price),
cache_write_12h_price: perTokenToMTok(p.cache_write_12h_price),
cache_read_price: perTokenToMTok(p.cache_read_price),
fast_multiplier: p.fast_multiplier,
flex_multiplier: p.flex_multiplier,
@@ -1445,6 +1451,7 @@ function distributeRulesToPlatforms(apiRules: AccountStatsPricingRule[]) {
output_price: perTokenToMTok(p.output_price),
cache_write_price: perTokenToMTok(p.cache_write_price),
cache_write_1h_price: perTokenToMTok(p.cache_write_1h_price),
cache_write_12h_price: perTokenToMTok(p.cache_write_12h_price),
cache_read_price: perTokenToMTok(p.cache_read_price),
reasoning_effort_multipliers: p.reasoning_effort_multipliers ? { ...p.reasoning_effort_multipliers } : null,
image_input_price: perTokenToMTok(p.image_input_price),
+3
View File
@@ -4419,6 +4419,7 @@ const emptyGroupPricing = (): PricingFormEntry => ({
output_price: null,
cache_write_price: null,
cache_write_1h_price: null,
cache_write_12h_price: null,
cache_read_price: null,
reasoning_effort_multipliers: null,
image_input_price: null,
@@ -4441,6 +4442,7 @@ const groupPricingFromAPI = (
output_price: perTokenToMTok(entry.output_price),
cache_write_price: perTokenToMTok(entry.cache_write_price),
cache_write_1h_price: perTokenToMTok(entry.cache_write_1h_price),
cache_write_12h_price: perTokenToMTok(entry.cache_write_12h_price),
cache_read_price: perTokenToMTok(entry.cache_read_price),
reasoning_effort_multipliers: entry.reasoning_effort_multipliers
? { ...entry.reasoning_effort_multipliers }
@@ -4466,6 +4468,7 @@ const groupPricingToAPI = (
output_price: mTokToPerToken(entry.output_price),
cache_write_price: mTokToPerToken(entry.cache_write_price),
cache_write_1h_price: mTokToPerToken(entry.cache_write_1h_price),
cache_write_12h_price: mTokToPerToken(entry.cache_write_12h_price),
cache_read_price: mTokToPerToken(entry.cache_read_price),
reasoning_effort_multipliers: formReasoningEffortMultipliersToAPI(
entry.reasoning_effort_multipliers,