-
Notifications
You must be signed in to change notification settings - Fork 64
/
handler.go
435 lines (354 loc) · 14.3 KB
/
handler.go
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
package message
import (
"errors"
"net/http"
"strings"
"time"
"github.com/bricks-cloud/bricksllm/internal/event"
"github.com/bricks-cloud/bricksllm/internal/key"
"github.com/bricks-cloud/bricksllm/internal/provider/anthropic"
"github.com/bricks-cloud/bricksllm/internal/provider/custom"
"github.com/bricks-cloud/bricksllm/internal/stats"
"github.com/tidwall/gjson"
"go.uber.org/zap"
goopenai "github.com/sashabaranov/go-openai"
)
type anthropicEstimator interface {
EstimateTotalCost(model string, promptTks, completionTks int) (float64, error)
EstimateCompletionCost(model string, tks int) (float64, error)
EstimatePromptCost(model string, tks int) (float64, error)
Count(input string) int
}
type estimator interface {
EstimateSpeechCost(input string, model string) (float64, error)
EstimateChatCompletionPromptCostWithTokenCounts(r *goopenai.ChatCompletionRequest) (int, float64, error)
EstimateEmbeddingsCost(r *goopenai.EmbeddingRequest) (float64, error)
EstimateChatCompletionStreamCostWithTokenCounts(model, content string) (int, float64, error)
EstimateCompletionCost(model string, tks int) (float64, error)
EstimateTotalCost(model string, promptTks, completionTks int) (float64, error)
EstimateEmbeddingsInputCost(model string, tks int) (float64, error)
EstimateChatCompletionPromptTokenCounts(model string, r *goopenai.ChatCompletionRequest) (int, error)
}
type azureEstimator interface {
EstimateChatCompletionStreamCostWithTokenCounts(model, content string) (int, float64, error)
EstimateEmbeddingsCost(r *goopenai.EmbeddingRequest) (float64, error)
EstimateCompletionCost(model string, tks int) (float64, error)
EstimatePromptCost(model string, tks int) (float64, error)
EstimateTotalCost(model string, promptTks, completionTks int) (float64, error)
EstimateEmbeddingsInputCost(model string, tks int) (float64, error)
}
type validator interface {
Validate(k *key.ResponseKey, promptCost float64) error
}
type keyManager interface {
UpdateKey(id string, uk *key.UpdateKey) (*key.ResponseKey, error)
}
type rateLimitManager interface {
Increment(keyId string, timeUnit key.TimeUnit) error
}
type accessCache interface {
Set(key string, timeUnit key.TimeUnit) error
}
type Handler struct {
recorder recorder
log *zap.Logger
ae anthropicEstimator
e estimator
aze azureEstimator
v validator
km keyManager
rlm rateLimitManager
ac accessCache
}
func NewHandler(r recorder, log *zap.Logger, ae anthropicEstimator, e estimator, aze azureEstimator, v validator, km keyManager, rlm rateLimitManager, ac accessCache) *Handler {
return &Handler{
recorder: r,
log: log,
ae: ae,
e: e,
aze: aze,
v: v,
km: km,
rlm: rlm,
ac: ac,
}
}
func (h *Handler) HandleEvent(m Message) error {
stats.Incr("bricksllm.message.handler.handle_event.requests", nil, 1)
e, ok := m.Data.(*event.Event)
if !ok {
stats.Incr("bricksllm.message.handler.handle_event.event_parsing_error", nil, 1)
h.log.Info("message contains data that cannot be converted to event format", zap.Any("data", m.Data))
return errors.New("message data cannot be parsed as event")
}
start := time.Now()
err := h.recorder.RecordEvent(e)
if err != nil {
stats.Incr("bricksllm.message.handler.handle_event.record_event_error", nil, 1)
h.log.Sugar().Debugf("error when publish in event: %v", err)
return err
}
stats.Timing("bricksllm.message.handler.handle_event.record_event_latency", time.Since(start), nil, 1)
stats.Incr("bricksllm.message.handler.handle_event.success", nil, 1)
return nil
}
const (
anthropicPromptMagicNum int = 1
anthropicCompletionMagicNum int = 4
)
func countTokensFromJson(bytes []byte, contentLoc string) (int, error) {
content := getContentFromJson(bytes, contentLoc)
return custom.Count(content)
}
func getContentFromJson(bytes []byte, contentLoc string) string {
result := gjson.Get(string(bytes), contentLoc)
content := ""
if len(result.Str) != 0 {
content += result.Str
}
if result.IsArray() {
for _, val := range result.Array() {
if len(val.Str) != 0 {
content += val.Str
}
}
}
return content
}
type costLimitError interface {
Error() string
CostLimit()
}
type rateLimitError interface {
Error() string
RateLimit()
}
type expirationError interface {
Error() string
Reason() string
}
func (h *Handler) handleValidationResult(kc *key.ResponseKey, cost float64) error {
err := h.v.Validate(kc, cost)
if err != nil {
stats.Incr("bricksllm.message.handler.handle_validation_result.handle_validation_result", nil, 1)
if _, ok := err.(expirationError); ok {
stats.Incr("bricksllm.message.handler.handle_validation_result.expiraton_error", nil, 1)
truePtr := true
_, err = h.km.UpdateKey(kc.KeyId, &key.UpdateKey{
Revoked: &truePtr,
RevokedReason: key.RevokedReasonExpired,
})
if err != nil {
stats.Incr("bricksllm.message.handler.handle_validation_result.update_key_error", nil, 1)
return err
}
return nil
}
if _, ok := err.(rateLimitError); ok {
stats.Incr("bricksllm.message.handler.handle_validation_result.rate_limit_error", nil, 1)
err = h.ac.Set(kc.KeyId, kc.RateLimitUnit)
if err != nil {
stats.Incr("bricksllm.message.handler.handle_validation_result.set_rate_limit_error", nil, 1)
return err
}
return nil
}
if _, ok := err.(costLimitError); ok {
stats.Incr("bricksllm.message.handler.handle_validation_result.cost_limit_error", nil, 1)
err = h.ac.Set(kc.KeyId, kc.CostLimitInUsdUnit)
if err != nil {
stats.Incr("bricksllm.message.handler.handle_validation_result.set_cost_limit_error", nil, 1)
return err
}
return nil
}
return err
}
return nil
}
func (h *Handler) HandleEventWithRequestAndResponse(m Message) error {
e, ok := m.Data.(*event.EventWithRequestAndContent)
if !ok {
stats.Incr("bricksllm.message.handler.handle_event_with_request_and_response.message_data_parsing_error", nil, 1)
h.log.Debug("message contains data that cannot be converted to event with request and response format", zap.Any("data", m.Data))
return errors.New("message data cannot be parsed as event with request and response")
}
if e.Key != nil && !e.Key.Revoked && e.Event != nil {
err := h.decorateEvent(m)
if err != nil {
stats.Incr("bricksllm.message.handler.handle_event_with_request_and_response.decorate_event_error", nil, 1)
h.log.Debug("error when decorating event", zap.Error(err))
}
if e.Event.CostInUsd != 0 {
micros := int64(e.Event.CostInUsd * 1000000)
err = h.recorder.RecordKeySpend(e.Event.KeyId, micros, e.Key.CostLimitInUsdUnit)
if err != nil {
stats.Incr("bricksllm.message.handler.handle_event_with_request_and_response.record_key_spend_error", nil, 1)
h.log.Debug("error when recording key spend", zap.Error(err))
}
}
if len(e.Key.RateLimitUnit) != 0 {
if err := h.rlm.Increment(e.Key.KeyId, e.Key.RateLimitUnit); err != nil {
stats.Incr("bricksllm.message.handler.handle_event_with_request_and_response.rate_limit_increment_error", nil, 1)
h.log.Debug("error when incrementing rate limit", zap.Error(err))
}
}
err = h.handleValidationResult(e.Key, e.Event.CostInUsd)
if err != nil {
stats.Incr("bricksllm.message.handler.handle_event_with_request_and_response.handle_validation_result_error", nil, 1)
h.log.Debug("error when handling validation result", zap.Error(err))
}
}
start := time.Now()
err := h.recorder.RecordEvent(e.Event)
if err != nil {
h.log.Debug("error when recording an event", zap.Error(err))
stats.Incr("bricksllm.message.handler.handle_event_with_request_and_response.record_event_error", nil, 1)
return err
}
stats.Timing("bricksllm.message.handler.handle_event_with_request_and_response.latency", time.Since(start), nil, 1)
stats.Incr("bricksllm.message.handler.handle_event_with_request_and_response.success", nil, 1)
return nil
}
func (h *Handler) decorateEvent(m Message) error {
stats.Incr("bricksllm.message.handler.decorate_event.request", nil, 1)
e, ok := m.Data.(*event.EventWithRequestAndContent)
if !ok {
stats.Incr("bricksllm.message.handler.decorate_event.message_data_parsing_error", nil, 1)
h.log.Debug("message contains data that cannot be converted to event with request and response format", zap.Any("data", m.Data))
return errors.New("message data cannot be parsed as event with request and response")
}
if e.Event.Path == "/api/providers/openai/v1/audio/speech" {
csr, ok := e.Request.(*goopenai.CreateSpeechRequest)
if !ok {
stats.Incr("bricksllm.message.handler.decorate_event.event_request_parsing_error", nil, 1)
h.log.Debug("event contains request that cannot be converted to anthropic completion request", zap.Any("data", m.Data))
return errors.New("event request data cannot be parsed as anthropic completon request")
}
if e.Event.Status == http.StatusOK {
cost, err := h.e.EstimateSpeechCost(csr.Input, string(csr.Model))
if err != nil {
stats.Incr("bricksllm.message.handler.decorate_event.estimate_prompt_cost", nil, 1)
h.log.Debug("event contains request that cannot be converted to anthropic completion request", zap.Error(err))
return err
}
e.Event.CostInUsd = cost
}
}
if e.Event.Path == "/api/providers/anthropic/v1/complete" {
cr, ok := e.Request.(*anthropic.CompletionRequest)
if !ok {
stats.Incr("bricksllm.message.handler.decorate_event.event_request_parsing_error", nil, 1)
h.log.Debug("event contains request that cannot be converted to anthropic completion request", zap.Any("data", m.Data))
return errors.New("event request data cannot be parsed as anthropic completon request")
}
tks := h.ae.Count(cr.Prompt)
tks += anthropicPromptMagicNum
model := cr.Model
cost, err := h.ae.EstimatePromptCost(model, tks)
if err != nil {
stats.Incr("bricksllm.message.handler.decorate_event.estimate_prompt_cost", nil, 1)
h.log.Debug("event contains request that cannot be converted to anthropic completion request", zap.Error(err))
return err
}
completiontks := h.ae.Count(e.Content)
completiontks += anthropicCompletionMagicNum
completionCost, err := h.ae.EstimateCompletionCost(model, completiontks)
if err != nil {
stats.Incr("bricksllm.message.handler.decorate_event.estimate_completion_cost_error", nil, 1)
return err
}
e.Event.PromptTokenCount = tks
e.Event.CompletionTokenCount = completiontks
e.Event.CostInUsd = completionCost + cost
}
if e.Event.Path == "/api/providers/azure/openai/deployments/:deployment_id/chat/completions" {
ccr, ok := e.Request.(*goopenai.ChatCompletionRequest)
if !ok {
stats.Incr("bricksllm.message.handler.decorate_event.event_request_parsing_error", nil, 1)
h.log.Debug("event contains data that cannot be converted to azure openai completion request", zap.Any("data", m.Data))
return errors.New("event request data cannot be parsed as azure openai completon request")
}
if ccr.Stream {
tks, err := h.e.EstimateChatCompletionPromptTokenCounts("gpt-3.5-turbo", ccr)
if err != nil {
stats.Incr("bricksllm.message.decorate_event.estimate_chat_completion_prompt_token_counts_error", nil, 1)
return err
}
cost, err := h.aze.EstimatePromptCost(e.Event.Model, tks)
if err != nil {
stats.Incr("bricksllm.message.decorate_event.estimate_prompt_cost_error", nil, 1)
return err
}
completiontks, completionCost, err := h.aze.EstimateChatCompletionStreamCostWithTokenCounts(e.Event.Model, e.Content)
if err != nil {
stats.Incr("bricksllm.message.decorate_event.estimate_chat_completion_stream_cost_with_token_counts_error", nil, 1)
return err
}
e.Event.PromptTokenCount = tks
e.Event.CompletionTokenCount = completiontks
e.Event.CostInUsd = cost + completionCost
}
}
if e.Event.Path == "/api/providers/openai/v1/chat/completions" {
ccr, ok := e.Request.(*goopenai.ChatCompletionRequest)
if !ok {
stats.Incr("bricksllm.message.handler.decorate_event.event_request_parsing_error", nil, 1)
h.log.Debug("event contains data that cannot be converted to openai completion request", zap.Any("data", m.Data))
return errors.New("event request data cannot be parsed as openai completon request")
}
if ccr.Stream {
tks, cost, err := h.e.EstimateChatCompletionPromptCostWithTokenCounts(ccr)
if err != nil {
stats.Incr("bricksllm.message.handler.decorate_event.estimate_chat_completion_prompt_cost_with_token_counts", nil, 1)
return err
}
completiontks, completionCost, err := h.e.EstimateChatCompletionStreamCostWithTokenCounts(e.Event.Model, e.Content)
if err != nil {
stats.Incr("bricksllm.message.handler.decorate_event.estimate_chat_completion_stream_cost_with_token_counts", nil, 1)
return err
}
e.Event.PromptTokenCount = tks
e.Event.CompletionTokenCount = completiontks
e.Event.CostInUsd = cost + completionCost
}
}
if strings.HasPrefix(e.Event.Path, "/api/custom/providers/:provider") && e.RouteConfig != nil {
body, ok := e.Request.([]byte)
if !ok {
stats.Incr("bricksllm.message.handler.decorate_event.event_request_custom_provider_parsing_error", nil, 1)
h.log.Debug("event contains request that cannot be converted to bytes", zap.Any("data", m.Data))
return errors.New("event request data cannot be parsed as anthropic completon request")
}
tks, err := countTokensFromJson(body, e.RouteConfig.RequestPromptLocation)
if err != nil {
stats.Incr("bricksllm.message.handler.decorate_event.count_tokens_from_json_error", nil, 1)
return err
}
e.Event.PromptTokenCount = tks
result := gjson.Get(string(body), e.RouteConfig.StreamLocation)
if result.IsBool() {
completiontks, err := custom.Count(e.Content)
if err != nil {
stats.Incr("bricksllm.message.handler.decorate_event.custom_count_error", nil, 1)
return err
}
e.Event.CompletionTokenCount = completiontks
}
if !result.IsBool() {
content, ok := e.Response.([]byte)
if !ok {
stats.Incr("bricksllm.message.handler.decorate_event.event_response_custom_provider_parsing_error", nil, 1)
h.log.Debug("event contains response that cannot be converted to bytes", zap.Any("data", m.Data))
return errors.New("event response data cannot be converted to bytes")
}
completiontks, err := countTokensFromJson(content, e.RouteConfig.ResponseCompletionLocation)
if err != nil {
stats.Incr("bricksllm.message.handler.decorate_event.count_tokens_from_json_error", nil, 1)
return err
}
e.Event.CompletionTokenCount = completiontks
}
}
return nil
}