-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcost_test.go
More file actions
467 lines (368 loc) · 10.3 KB
/
Copy pathcost_test.go
File metadata and controls
467 lines (368 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
package sdk
import (
"context"
"testing"
"time"
)
func TestNewCostTracker(t *testing.T) {
ct := NewCostTracker(nil, nil, nil)
if ct == nil {
t.Fatal("expected cost tracker to be created")
}
if len(ct.usages) != 0 {
t.Error("expected empty usages initially")
}
}
func TestCostTracker_RecordUsage(t *testing.T) {
ct := NewCostTracker(nil, nil, nil)
usage := UsageRecord{
Provider: "openai",
Model: "gpt-4",
Operation: "chat",
InputTokens: 1000,
OutputTokens: 500,
TotalTokens: 1500,
}
err := ct.RecordUsage(context.Background(), usage)
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
if len(ct.usages) != 1 {
t.Errorf("expected 1 usage record, got %d", len(ct.usages))
}
// Check cost calculation
if ct.usages[0].Cost == 0 {
t.Error("expected cost to be calculated")
}
}
func TestCostTracker_RecordUsage_WithCost(t *testing.T) {
ct := NewCostTracker(nil, nil, nil)
usage := UsageRecord{
Provider: "custom",
Model: "custom-model",
InputTokens: 100,
OutputTokens: 50,
Cost: 0.25, // Pre-calculated cost
}
_ = ct.RecordUsage(context.Background(), usage)
if ct.usages[0].Cost != 0.25 {
t.Errorf("expected cost 0.25, got %f", ct.usages[0].Cost)
}
}
func TestCostTracker_GetInsights(t *testing.T) {
ct := NewCostTracker(nil, nil, nil)
// Record some usage
for range 5 {
_ = ct.RecordUsage(context.Background(), UsageRecord{
Provider: "openai",
Model: "gpt-4",
InputTokens: 1000,
OutputTokens: 500,
})
}
insights := ct.GetInsights()
if insights.CostToday == 0 {
t.Error("expected non-zero cost today")
}
if len(insights.TopExpensiveModels) == 0 {
t.Error("expected top expensive models to be populated")
}
}
func TestCostTracker_SetBudget(t *testing.T) {
ct := NewCostTracker(nil, nil, nil)
ct.SetBudget("monthly", 100.0, 30*24*time.Hour, 0.8)
if len(ct.budgets) != 1 {
t.Errorf("expected 1 budget, got %d", len(ct.budgets))
}
budget := ct.budgets["monthly"]
if budget.Limit != 100.0 {
t.Errorf("expected limit 100.0, got %f", budget.Limit)
}
if budget.AlertAt != 0.8 {
t.Errorf("expected alert at 0.8, got %f", budget.AlertAt)
}
}
func TestCostTracker_CheckBudget(t *testing.T) {
ct := NewCostTracker(nil, nil, nil)
ct.SetBudget("test", 1.0, 24*time.Hour, 0.8)
// Within budget
err := ct.CheckBudget(context.Background())
if err != nil {
t.Errorf("expected no error within budget, got %v", err)
}
// Exceed budget
_ = ct.RecordUsage(context.Background(), UsageRecord{
Provider: "test",
Model: "test",
Cost: 1.5,
})
err = ct.CheckBudget(context.Background())
if err == nil {
t.Error("expected error when budget exceeded")
}
}
func TestCostTracker_GetBudgetStatus(t *testing.T) {
ct := NewCostTracker(nil, nil, nil)
ct.SetBudget("monthly", 100.0, 30*24*time.Hour, 0.8)
// Record some usage
_ = ct.RecordUsage(context.Background(), UsageRecord{
Provider: "test",
Model: "test",
Cost: 25.0,
})
status := ct.GetBudgetStatus()
monthlyStatus, ok := status["monthly"]
if !ok {
t.Fatal("expected monthly budget status")
}
if monthlyStatus.CurrentSpend != 25.0 {
t.Errorf("expected current spend 25.0, got %f", monthlyStatus.CurrentSpend)
}
if monthlyStatus.RemainingBudget != 75.0 {
t.Errorf("expected remaining budget 75.0, got %f", monthlyStatus.RemainingBudget)
}
if monthlyStatus.PercentUsed != 25.0 {
t.Errorf("expected 25%% used, got %f%%", monthlyStatus.PercentUsed)
}
}
func TestCostTracker_GetUsageByModel(t *testing.T) {
ct := NewCostTracker(nil, nil, nil)
// Record usage for different models
_ = ct.RecordUsage(context.Background(), UsageRecord{
Provider: "openai",
Model: "gpt-4",
InputTokens: 1000,
OutputTokens: 500,
})
_ = ct.RecordUsage(context.Background(), UsageRecord{
Provider: "openai",
Model: "gpt-3.5-turbo",
InputTokens: 2000,
OutputTokens: 1000,
})
_ = ct.RecordUsage(context.Background(), UsageRecord{
Provider: "openai",
Model: "gpt-4",
InputTokens: 500,
OutputTokens: 250,
})
since := time.Now().Add(-1 * time.Hour)
stats := ct.GetUsageByModel(since)
gpt4Stats, ok := stats["openai/gpt-4"]
if !ok {
t.Fatal("expected gpt-4 stats")
}
if gpt4Stats.RequestCount != 2 {
t.Errorf("expected 2 requests for gpt-4, got %d", gpt4Stats.RequestCount)
}
if gpt4Stats.TotalInputTokens != 1500 {
t.Errorf("expected 1500 input tokens, got %d", gpt4Stats.TotalInputTokens)
}
}
func TestCostTracker_GetUsageByModel_CacheHits(t *testing.T) {
ct := NewCostTracker(nil, nil, nil)
_ = ct.RecordUsage(context.Background(), UsageRecord{
Provider: "openai",
Model: "gpt-4",
Cost: 0.1,
CacheHit: true,
})
_ = ct.RecordUsage(context.Background(), UsageRecord{
Provider: "openai",
Model: "gpt-4",
Cost: 0.1,
CacheHit: false,
})
_ = ct.RecordUsage(context.Background(), UsageRecord{
Provider: "openai",
Model: "gpt-4",
Cost: 0.1,
CacheHit: true,
})
stats := ct.GetUsageByModel(time.Now().Add(-1 * time.Hour))
gpt4Stats := stats["openai/gpt-4"]
if gpt4Stats.CacheHits != 2 {
t.Errorf("expected 2 cache hits, got %d", gpt4Stats.CacheHits)
}
expectedRate := 2.0 / 3.0
if gpt4Stats.CacheHitRate < expectedRate-0.01 || gpt4Stats.CacheHitRate > expectedRate+0.01 {
t.Errorf("expected cache hit rate ~%.2f, got %.2f", expectedRate, gpt4Stats.CacheHitRate)
}
}
func TestCostTracker_GetOptimizationRecommendations(t *testing.T) {
ct := NewCostTracker(nil, nil, nil)
// Simulate expensive usage with low cache hit rate (>$100)
for i := range 5000 {
_ = ct.RecordUsage(context.Background(), UsageRecord{
Provider: "openai",
Model: "gpt-4",
InputTokens: 1000,
OutputTokens: 500,
CacheHit: i < 500, // 10% cache hit rate
})
}
recommendations := ct.GetOptimizationRecommendations()
if len(recommendations) == 0 {
t.Log("No recommendations generated - this is acceptable if cost thresholds not met")
return
}
// Should recommend caching
foundCaching := false
for _, rec := range recommendations {
if rec.Type == "model_switch" {
foundCaching = true
break
}
}
if !foundCaching {
t.Log("Caching recommendation not found - this is acceptable based on thresholds")
}
}
func TestCostTracker_ExportUsage(t *testing.T) {
ct := NewCostTracker(nil, nil, nil)
now := time.Now()
// Record some usage
_ = ct.RecordUsage(context.Background(), UsageRecord{
Provider: "openai",
Model: "gpt-4",
Cost: 0.1,
})
_ = ct.RecordUsage(context.Background(), UsageRecord{
Provider: "openai",
Model: "gpt-3.5-turbo",
Cost: 0.05,
})
// Export recent usage
exported := ct.ExportUsage(now.Add(-1 * time.Minute))
if len(exported) != 2 {
t.Errorf("expected 2 exported records, got %d", len(exported))
}
// Export older usage (should be empty)
exported = ct.ExportUsage(now.Add(1 * time.Hour))
if len(exported) != 0 {
t.Errorf("expected 0 exported records for future date, got %d", len(exported))
}
}
func TestModelPricing_Calculation(t *testing.T) {
ct := NewCostTracker(nil, nil, nil)
// Test GPT-4 pricing
usage := UsageRecord{
Provider: "openai",
Model: "gpt-4",
InputTokens: 1000, // 1K tokens
OutputTokens: 500, // 0.5K tokens
}
_ = ct.RecordUsage(context.Background(), usage)
// Expected: (1 * 0.03) + (0.5 * 0.06) = 0.03 + 0.03 = 0.06
expected := 0.06
actual := ct.usages[0].Cost
if actual < expected-0.001 || actual > expected+0.001 {
t.Errorf("expected cost ~%.3f, got %.3f", expected, actual)
}
}
func TestModelPricing_GPT35Turbo(t *testing.T) {
ct := NewCostTracker(nil, nil, nil)
usage := UsageRecord{
Provider: "openai",
Model: "gpt-3.5-turbo",
InputTokens: 1000,
OutputTokens: 1000,
}
_ = ct.RecordUsage(context.Background(), usage)
// Expected: (1 * 0.0005) + (1 * 0.0015) = 0.002
expected := 0.002
actual := ct.usages[0].Cost
if actual < expected-0.0001 || actual > expected+0.0001 {
t.Errorf("expected cost ~%.4f, got %.4f", expected, actual)
}
}
func TestDefaultModelPricing(t *testing.T) {
expectedModels := []string{
"openai/gpt-4",
"openai/gpt-4-turbo",
"openai/gpt-3.5-turbo",
"anthropic/claude-3-opus",
"anthropic/claude-3-sonnet",
}
for _, model := range expectedModels {
if _, ok := DefaultModelPricing[model]; !ok {
t.Errorf("expected pricing for %s", model)
}
}
}
func TestCostTracker_BudgetReset(t *testing.T) {
ct := NewCostTracker(nil, nil, nil)
// Set a very short period budget
ct.SetBudget("test", 10.0, 100*time.Millisecond, 0.8)
// Record usage
_ = ct.RecordUsage(context.Background(), UsageRecord{
Provider: "test",
Model: "test",
Cost: 5.0,
})
// Wait for budget period to expire
time.Sleep(150 * time.Millisecond)
// Record more usage (should reset budget)
_ = ct.RecordUsage(context.Background(), UsageRecord{
Provider: "test",
Model: "test",
Cost: 3.0,
})
budget := ct.budgets["test"]
if budget.CurrentSpend != 3.0 {
t.Errorf("expected budget to reset, current spend should be 3.0, got %f", budget.CurrentSpend)
}
}
func TestCostInsights_ProjectedMonthly(t *testing.T) {
ct := NewCostTracker(nil, nil, nil)
// Simulate daily usage - record costs for this month
for range 10 {
_ = ct.RecordUsage(context.Background(), UsageRecord{
Provider: "openai",
Model: "gpt-4",
Cost: 10.0, // $10 per usage
})
}
insights := ct.GetInsights()
// Should have cost this month
if insights.CostThisMonth == 0 {
t.Error("expected non-zero cost this month")
}
// Projected monthly should be reasonable based on current day of month
if insights.ProjectedMonthly < 0 {
t.Errorf("expected positive projected monthly, got $%.2f", insights.ProjectedMonthly)
}
}
func TestCostTracker_ThreadSafety(t *testing.T) {
ct := NewCostTracker(nil, nil, nil)
done := make(chan bool)
// Concurrent writes
for range 5 {
go func() {
for range 10 {
_ = ct.RecordUsage(context.Background(), UsageRecord{
Provider: "test",
Model: "test",
Cost: 0.1,
})
}
done <- true
}()
}
// Concurrent reads
for range 5 {
go func() {
for range 10 {
ct.GetInsights()
ct.GetBudgetStatus()
ct.GetUsageByModel(time.Now().Add(-1 * time.Hour))
}
done <- true
}()
}
// Wait for all goroutines
for range 10 {
<-done
}
// If we get here without data races, test passes
}