Chen-BUPT commented on code in PR #878: URL: https://github.com/apache/dubbo-go-pixiu/pull/878#discussion_r2779261552
########## pkg/filter/ai/kvcache/token_manager.go: ########## @@ -0,0 +1,305 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package kvcache + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "strings" + "sync" + "sync/atomic" + "time" +) + +import ( + "github.com/go-resty/resty/v2" +) + +type TokenManager struct { + httpClient *resty.Client + endpoint string + cache sync.Map + config TokenCacheConfig + circuitBreaker *CircuitBreaker + + cacheSize int64 + hitCount int64 + missCount int64 + + hotWindow time.Duration + hotMax int + hotMu sync.Mutex + hotMap map[string][]time.Time +} + +type TokenizeRequest struct { + Model string `json:"model,omitempty"` + Prompt string `json:"prompt"` +} + +type TokenizeResponse struct { + Count int `json:"count"` + Tokens []int `json:"tokens"` + MaxLen int `json:"max_model_len"` +} + +type tokenCacheEntry struct { + tokens []int + expiresAt time.Time +} + +func NewTokenManager(endpoint string, httpClient *resty.Client, cfg TokenCacheConfig, cb *CircuitBreaker, hotWindow time.Duration, hotMax int) *TokenManager { + return &TokenManager{ + httpClient: httpClient, + endpoint: endpoint, + config: cfg, + circuitBreaker: cb, + hotWindow: hotWindow, + hotMax: hotMax, + hotMap: make(map[string][]time.Time), + } +} + +func (tm *TokenManager) GetTokens(ctx context.Context, model string, prompt string, rawBody []byte) ([]int, error) { + cacheKey := tm.cacheKey(model, prompt) + if tm.config.Enabled { + if tokens, ok := tm.loadCache(cacheKey); ok { + atomic.AddInt64(&tm.hitCount, 1) + return tokens, nil + } + atomic.AddInt64(&tm.missCount, 1) + } + + tokens, err := tm.tokenize(ctx, model, prompt, rawBody) + if err != nil { + return nil, err + } + + if tm.config.Enabled { + tm.storeCache(cacheKey, tokens) + } + return tokens, nil +} + +func (tm *TokenManager) GetCachedTokens(model string, prompt string) ([]int, bool) { + if !tm.config.Enabled { + return nil, false + } + cacheKey := tm.cacheKey(model, prompt) + tokens, ok := tm.loadCache(cacheKey) + if ok { + atomic.AddInt64(&tm.hitCount, 1) + } else { + atomic.AddInt64(&tm.missCount, 1) + } + return tokens, ok +} + +func (tm *TokenManager) InvalidateCache(model string, prompt string) { + cacheKey := tm.cacheKey(model, prompt) + tm.deleteCache(cacheKey) +} + +func (tm *TokenManager) GetCacheStats() CacheStats { + size := atomic.LoadInt64(&tm.cacheSize) + hit := atomic.LoadInt64(&tm.hitCount) + miss := atomic.LoadInt64(&tm.missCount) + total := hit + miss + var hitRate float64 + if total > 0 { + hitRate = float64(hit) / float64(total) + } + return CacheStats{ + Size: int(size), + HitRate: hitRate, + HitCount: hit, + MissCount: miss, + } +} + +func (tm *TokenManager) tokenize(ctx context.Context, model string, prompt string, rawBody []byte) ([]int, error) { + var tokens []int + err := tm.execute(ctx, func() error { + body, err := tm.buildTokenizeBody(model, prompt, rawBody) + if err != nil { + return err + } + resp, err := tm.doTokenizeRequest(ctx, body) + if err != nil { + return err + } + tokens = resp.Tokens + return nil + }) + if err != nil { + return nil, err + } + return tokens, nil +} + +func (tm *TokenManager) buildTokenizeBody(model string, prompt string, rawBody []byte) (any, error) { + if len(rawBody) > 0 { + return rawBody, nil + } + return TokenizeRequest{Model: model, Prompt: prompt}, nil +} + +func (tm *TokenManager) doTokenizeRequest(ctx context.Context, body any) (*TokenizeResponse, error) { Review Comment: 因为向下游进行智能路由等操作需要prompt对应的token 这里选择向推理引擎发/tokenizer请求来获得token -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
