Alanxtl commented on code in PR #878:
URL: https://github.com/apache/dubbo-go-pixiu/pull/878#discussion_r2779145903


##########
pkg/filter/ai/kvcache/config.go:
##########
@@ -0,0 +1,150 @@
+/*
+ * 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 (
+       "fmt"
+       "strings"
+       "time"
+)
+
+type Config struct {
+       Enabled              bool                 `yaml:"enabled" 
json:"enabled" mapstructure:"enabled"`
+       VLLMEndpoint         string               `yaml:"vllm_endpoint" 
json:"vllm_endpoint" mapstructure:"vllm_endpoint"`
+       LMCacheEndpoint      string               `yaml:"lmcache_endpoint" 
json:"lmcache_endpoint" mapstructure:"lmcache_endpoint"`
+       DefaultModel         string               `yaml:"default_model" 
json:"default_model" mapstructure:"default_model"`
+       RequestTimeout       time.Duration        `yaml:"request_timeout" 
json:"request_timeout" mapstructure:"request_timeout"`
+       LookupRoutingTimeout time.Duration        
`yaml:"lookup_routing_timeout" json:"lookup_routing_timeout" 
mapstructure:"lookup_routing_timeout"`
+       HotWindow            time.Duration        `yaml:"hot_window" 
json:"hot_window" mapstructure:"hot_window"`
+       HotMaxRecords        int                  `yaml:"hot_max_records" 
json:"hot_max_records" mapstructure:"hot_max_records"`
+       MaxIdleConns         int                  `yaml:"max_idle_conns" 
json:"max_idle_conns" mapstructure:"max_idle_conns"`
+       MaxIdleConnsPerHost  int                  
`yaml:"max_idle_conns_per_host" json:"max_idle_conns_per_host" 
mapstructure:"max_idle_conns_per_host"`
+       MaxConnsPerHost      int                  `yaml:"max_conns_per_host" 
json:"max_conns_per_host" mapstructure:"max_conns_per_host"`
+       TokenCache           TokenCacheConfig     `yaml:"token_cache" 
json:"token_cache" mapstructure:"token_cache"`
+       CacheStrategy        CacheStrategyConfig  `yaml:"cache_strategy" 
json:"cache_strategy" mapstructure:"cache_strategy"`
+       CircuitBreaker       CircuitBreakerConfig `yaml:"circuit_breaker" 
json:"circuit_breaker" mapstructure:"circuit_breaker"`
+       Retry                RetryConfig          `yaml:"retry" json:"retry" 
mapstructure:"retry"`
+}
+
+type TokenCacheConfig struct {
+       MaxSize int           `yaml:"max_size" json:"max_size" 
mapstructure:"max_size"`
+       TTL     time.Duration `yaml:"ttl" json:"ttl" mapstructure:"ttl"`
+       Enabled bool          `yaml:"enabled" json:"enabled" 
mapstructure:"enabled"`
+}
+
+type CacheStrategyConfig struct {
+       EnableCompression   bool    `yaml:"enable_compression" 
json:"enable_compression" mapstructure:"enable_compression"`
+       EnablePinning       bool    `yaml:"enable_pinning" 
json:"enable_pinning" mapstructure:"enable_pinning"`
+       EnableEviction      bool    `yaml:"enable_eviction" 
json:"enable_eviction" mapstructure:"enable_eviction"`
+       MemoryThreshold     float64 `yaml:"memory_threshold" 
json:"memory_threshold" mapstructure:"memory_threshold"`
+       HotContentThreshold int     `yaml:"hot_content_threshold" 
json:"hot_content_threshold" mapstructure:"hot_content_threshold"`
+       LoadThreshold       float64 `yaml:"load_threshold" 
json:"load_threshold" mapstructure:"load_threshold"`
+       PinInstanceID       string  `yaml:"pin_instance_id" 
json:"pin_instance_id" mapstructure:"pin_instance_id"`
+       PinLocation         string  `yaml:"pin_location" json:"pin_location" 
mapstructure:"pin_location"`
+       CompressInstanceID  string  `yaml:"compress_instance_id" 
json:"compress_instance_id" mapstructure:"compress_instance_id"`
+       CompressLocation    string  `yaml:"compress_location" 
json:"compress_location" mapstructure:"compress_location"`
+       CompressMethod      string  `yaml:"compress_method" 
json:"compress_method" mapstructure:"compress_method"`
+       EvictInstanceID     string  `yaml:"evict_instance_id" 
json:"evict_instance_id" mapstructure:"evict_instance_id"`
+}
+
+type RetryConfig struct {
+       MaxAttempts int           `yaml:"max_attempts" json:"max_attempts" 
mapstructure:"max_attempts"`
+       BaseBackoff time.Duration `yaml:"base_backoff" json:"base_backoff" 
mapstructure:"base_backoff"`
+       MaxBackoff  time.Duration `yaml:"max_backoff" json:"max_backoff" 
mapstructure:"max_backoff"`
+}
+
+func (c *Config) Validate() error {
+       if !c.Enabled {
+               return nil
+       }
+       if strings.TrimSpace(c.VLLMEndpoint) == "" {
+               return fmt.Errorf("kvcache: vllm_endpoint is required when 
enabled")
+       }
+       if strings.TrimSpace(c.LMCacheEndpoint) == "" {
+               return fmt.Errorf("kvcache: lmcache_endpoint is required when 
enabled")
+       }
+       if c.TokenCache.MaxSize < 0 {
+               return fmt.Errorf("kvcache: token_cache.max_size must be >= 0")
+       }
+       if c.CacheStrategy.MemoryThreshold < 0 || 
c.CacheStrategy.MemoryThreshold > 1 {
+               return fmt.Errorf("kvcache: cache_strategy.memory_threshold 
must be between 0 and 1")
+       }
+       if c.CacheStrategy.LoadThreshold < 0 || c.CacheStrategy.LoadThreshold > 
1 {
+               return fmt.Errorf("kvcache: cache_strategy.load_threshold must 
be between 0 and 1")
+       }
+       if c.CacheStrategy.HotContentThreshold < 0 {
+               return fmt.Errorf("kvcache: 
cache_strategy.hot_content_threshold must be >= 0")
+       }
+       if c.Retry.MaxAttempts < 0 {
+               return fmt.Errorf("kvcache: retry.max_attempts must be >= 0")
+       }
+       if c.Retry.BaseBackoff < 0 || c.Retry.MaxBackoff < 0 {
+               return fmt.Errorf("kvcache: retry backoff durations must be >= 
0")
+       }
+       if c.HotWindow < 0 {
+               return fmt.Errorf("kvcache: hot_window must be >= 0")
+       }
+       if c.HotMaxRecords < 0 {
+               return fmt.Errorf("kvcache: hot_max_records must be >= 0")
+       }
+       return nil
+}
+
+func (c *Config) ApplyDefaults() {
+       if c.RequestTimeout <= 0 {
+               c.RequestTimeout = 2 * time.Second

Review Comment:
   把常量都抽出去



##########
pkg/filter/llm/proxy/filter.go:
##########
@@ -98,6 +98,18 @@ type (
        }
 )
 
+func getPreferredEndpointID(hc *contexthttp.HttpContext) string {
+       if hc == nil || hc.Params == nil {
+               return ""
+       }
+       val, ok := hc.Params[constant.LLMPreferredEndpointID]
+       if !ok {
+               return ""
+       }
+       endpointID, _ := val.(string)
+       return endpointID

Review Comment:
   ```suggestion
        if val, ok := hc.Params[constant.LLMPreferredEndpointID]; !ok {
                return ""
        }
        if val, ok := val.(string); ok {
                return val
        }
        return endpointID
   ```



##########
pkg/filter/ai/kvcache/circuit_breaker.go:
##########
@@ -0,0 +1,106 @@
+/*
+ * 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 (
+       "errors"
+       "sync"
+       "time"
+)
+
+var ErrCircuitBreakerOpen = errors.New("kvcache circuit breaker open")
+
+type CircuitState int
+
+const (
+       CircuitClosed CircuitState = iota

Review Comment:
   not suggest using iota



##########
pkg/common/constant/key.go:
##########
@@ -59,8 +59,11 @@ const (
 
        LLMProxyFilter     = "dgp.filter.llm.proxy"
        LLMTokenizerFilter = "dgp.filter.llm.tokenizer"
+       AIKVCacheFilter    = "dgp.filter.ai.kvcache"
 
        MCPServerFilter = "dgp.filter.mcp.mcpserver"
+
+       LLMPreferredEndpointID = "llm_preferred_endpoint_id"

Review Comment:
   这个常量放到这里不合适吧



##########
pkg/filter/ai/kvcache/config.go:
##########
@@ -0,0 +1,150 @@
+/*
+ * 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 (
+       "fmt"
+       "strings"
+       "time"
+)
+
+type Config struct {
+       Enabled              bool                 `yaml:"enabled" 
json:"enabled" mapstructure:"enabled"`
+       VLLMEndpoint         string               `yaml:"vllm_endpoint" 
json:"vllm_endpoint" mapstructure:"vllm_endpoint"`
+       LMCacheEndpoint      string               `yaml:"lmcache_endpoint" 
json:"lmcache_endpoint" mapstructure:"lmcache_endpoint"`
+       DefaultModel         string               `yaml:"default_model" 
json:"default_model" mapstructure:"default_model"`
+       RequestTimeout       time.Duration        `yaml:"request_timeout" 
json:"request_timeout" mapstructure:"request_timeout"`
+       LookupRoutingTimeout time.Duration        
`yaml:"lookup_routing_timeout" json:"lookup_routing_timeout" 
mapstructure:"lookup_routing_timeout"`
+       HotWindow            time.Duration        `yaml:"hot_window" 
json:"hot_window" mapstructure:"hot_window"`
+       HotMaxRecords        int                  `yaml:"hot_max_records" 
json:"hot_max_records" mapstructure:"hot_max_records"`
+       MaxIdleConns         int                  `yaml:"max_idle_conns" 
json:"max_idle_conns" mapstructure:"max_idle_conns"`
+       MaxIdleConnsPerHost  int                  
`yaml:"max_idle_conns_per_host" json:"max_idle_conns_per_host" 
mapstructure:"max_idle_conns_per_host"`
+       MaxConnsPerHost      int                  `yaml:"max_conns_per_host" 
json:"max_conns_per_host" mapstructure:"max_conns_per_host"`
+       TokenCache           TokenCacheConfig     `yaml:"token_cache" 
json:"token_cache" mapstructure:"token_cache"`
+       CacheStrategy        CacheStrategyConfig  `yaml:"cache_strategy" 
json:"cache_strategy" mapstructure:"cache_strategy"`
+       CircuitBreaker       CircuitBreakerConfig `yaml:"circuit_breaker" 
json:"circuit_breaker" mapstructure:"circuit_breaker"`
+       Retry                RetryConfig          `yaml:"retry" json:"retry" 
mapstructure:"retry"`
+}
+
+type TokenCacheConfig struct {
+       MaxSize int           `yaml:"max_size" json:"max_size" 
mapstructure:"max_size"`
+       TTL     time.Duration `yaml:"ttl" json:"ttl" mapstructure:"ttl"`
+       Enabled bool          `yaml:"enabled" json:"enabled" 
mapstructure:"enabled"`
+}
+
+type CacheStrategyConfig struct {
+       EnableCompression   bool    `yaml:"enable_compression" 
json:"enable_compression" mapstructure:"enable_compression"`
+       EnablePinning       bool    `yaml:"enable_pinning" 
json:"enable_pinning" mapstructure:"enable_pinning"`
+       EnableEviction      bool    `yaml:"enable_eviction" 
json:"enable_eviction" mapstructure:"enable_eviction"`
+       MemoryThreshold     float64 `yaml:"memory_threshold" 
json:"memory_threshold" mapstructure:"memory_threshold"`
+       HotContentThreshold int     `yaml:"hot_content_threshold" 
json:"hot_content_threshold" mapstructure:"hot_content_threshold"`
+       LoadThreshold       float64 `yaml:"load_threshold" 
json:"load_threshold" mapstructure:"load_threshold"`
+       PinInstanceID       string  `yaml:"pin_instance_id" 
json:"pin_instance_id" mapstructure:"pin_instance_id"`
+       PinLocation         string  `yaml:"pin_location" json:"pin_location" 
mapstructure:"pin_location"`
+       CompressInstanceID  string  `yaml:"compress_instance_id" 
json:"compress_instance_id" mapstructure:"compress_instance_id"`
+       CompressLocation    string  `yaml:"compress_location" 
json:"compress_location" mapstructure:"compress_location"`
+       CompressMethod      string  `yaml:"compress_method" 
json:"compress_method" mapstructure:"compress_method"`
+       EvictInstanceID     string  `yaml:"evict_instance_id" 
json:"evict_instance_id" mapstructure:"evict_instance_id"`
+}
+
+type RetryConfig struct {
+       MaxAttempts int           `yaml:"max_attempts" json:"max_attempts" 
mapstructure:"max_attempts"`
+       BaseBackoff time.Duration `yaml:"base_backoff" json:"base_backoff" 
mapstructure:"base_backoff"`
+       MaxBackoff  time.Duration `yaml:"max_backoff" json:"max_backoff" 
mapstructure:"max_backoff"`
+}

Review Comment:
   这个retry能不能复用pixiu已有的retry呀



##########
pkg/filter/ai/kvcache/config.go:
##########
@@ -0,0 +1,150 @@
+/*
+ * 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 (
+       "fmt"
+       "strings"
+       "time"
+)
+
+type Config struct {
+       Enabled              bool                 `yaml:"enabled" 
json:"enabled" mapstructure:"enabled"`
+       VLLMEndpoint         string               `yaml:"vllm_endpoint" 
json:"vllm_endpoint" mapstructure:"vllm_endpoint"`
+       LMCacheEndpoint      string               `yaml:"lmcache_endpoint" 
json:"lmcache_endpoint" mapstructure:"lmcache_endpoint"`
+       DefaultModel         string               `yaml:"default_model" 
json:"default_model" mapstructure:"default_model"`
+       RequestTimeout       time.Duration        `yaml:"request_timeout" 
json:"request_timeout" mapstructure:"request_timeout"`
+       LookupRoutingTimeout time.Duration        
`yaml:"lookup_routing_timeout" json:"lookup_routing_timeout" 
mapstructure:"lookup_routing_timeout"`
+       HotWindow            time.Duration        `yaml:"hot_window" 
json:"hot_window" mapstructure:"hot_window"`
+       HotMaxRecords        int                  `yaml:"hot_max_records" 
json:"hot_max_records" mapstructure:"hot_max_records"`
+       MaxIdleConns         int                  `yaml:"max_idle_conns" 
json:"max_idle_conns" mapstructure:"max_idle_conns"`
+       MaxIdleConnsPerHost  int                  
`yaml:"max_idle_conns_per_host" json:"max_idle_conns_per_host" 
mapstructure:"max_idle_conns_per_host"`
+       MaxConnsPerHost      int                  `yaml:"max_conns_per_host" 
json:"max_conns_per_host" mapstructure:"max_conns_per_host"`
+       TokenCache           TokenCacheConfig     `yaml:"token_cache" 
json:"token_cache" mapstructure:"token_cache"`
+       CacheStrategy        CacheStrategyConfig  `yaml:"cache_strategy" 
json:"cache_strategy" mapstructure:"cache_strategy"`
+       CircuitBreaker       CircuitBreakerConfig `yaml:"circuit_breaker" 
json:"circuit_breaker" mapstructure:"circuit_breaker"`
+       Retry                RetryConfig          `yaml:"retry" json:"retry" 
mapstructure:"retry"`
+}
+
+type TokenCacheConfig struct {
+       MaxSize int           `yaml:"max_size" json:"max_size" 
mapstructure:"max_size"`
+       TTL     time.Duration `yaml:"ttl" json:"ttl" mapstructure:"ttl"`
+       Enabled bool          `yaml:"enabled" json:"enabled" 
mapstructure:"enabled"`
+}
+
+type CacheStrategyConfig struct {
+       EnableCompression   bool    `yaml:"enable_compression" 
json:"enable_compression" mapstructure:"enable_compression"`
+       EnablePinning       bool    `yaml:"enable_pinning" 
json:"enable_pinning" mapstructure:"enable_pinning"`
+       EnableEviction      bool    `yaml:"enable_eviction" 
json:"enable_eviction" mapstructure:"enable_eviction"`
+       MemoryThreshold     float64 `yaml:"memory_threshold" 
json:"memory_threshold" mapstructure:"memory_threshold"`
+       HotContentThreshold int     `yaml:"hot_content_threshold" 
json:"hot_content_threshold" mapstructure:"hot_content_threshold"`
+       LoadThreshold       float64 `yaml:"load_threshold" 
json:"load_threshold" mapstructure:"load_threshold"`
+       PinInstanceID       string  `yaml:"pin_instance_id" 
json:"pin_instance_id" mapstructure:"pin_instance_id"`
+       PinLocation         string  `yaml:"pin_location" json:"pin_location" 
mapstructure:"pin_location"`
+       CompressInstanceID  string  `yaml:"compress_instance_id" 
json:"compress_instance_id" mapstructure:"compress_instance_id"`
+       CompressLocation    string  `yaml:"compress_location" 
json:"compress_location" mapstructure:"compress_location"`
+       CompressMethod      string  `yaml:"compress_method" 
json:"compress_method" mapstructure:"compress_method"`
+       EvictInstanceID     string  `yaml:"evict_instance_id" 
json:"evict_instance_id" mapstructure:"evict_instance_id"`
+}
+
+type RetryConfig struct {
+       MaxAttempts int           `yaml:"max_attempts" json:"max_attempts" 
mapstructure:"max_attempts"`
+       BaseBackoff time.Duration `yaml:"base_backoff" json:"base_backoff" 
mapstructure:"base_backoff"`
+       MaxBackoff  time.Duration `yaml:"max_backoff" json:"max_backoff" 
mapstructure:"max_backoff"`
+}
+
+func (c *Config) Validate() error {
+       if !c.Enabled {
+               return nil
+       }
+       if strings.TrimSpace(c.VLLMEndpoint) == "" {
+               return fmt.Errorf("kvcache: vllm_endpoint is required when 
enabled")

Review Comment:
   把error的格式都改成这样的格式
   ```
   [kvcache] vllm_endpoint is required when enabled
   ```



##########
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:
   这个Tokenize是什么概念呀



-- 
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]

Reply via email to