Debian Codegraph @

vertexai/genai/tokenizer/tokenizer.go

raw
1 // Copyright 2024 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package tokenizer provides local token counting for Gemini models. This
16 // tokenizer downloads its model from the web, but otherwise doesn't require
17 // an API call for every [CountTokens] invocation.
18 package tokenizer
19
20 import (
21 "bytes"
22 "crypto/sha256"
23 "encoding/hex"
24 "fmt"
25 "io"
26 "net/http"
27 "os"
28 "path/filepath"
29
30 "cloud.google.com/go/vertexai/genai"
31 "cloud.google.com/go/vertexai/internal/sentencepiece"
32 )
33
34 var supportedModels = map[string]bool{
35 "gemini-1.0-pro": true,
36 "gemini-1.5-pro": true,
37 "gemini-1.5-flash": true,
38 "gemini-1.0-pro-001": true,
39 "gemini-1.0-pro-002": true,
40 "gemini-1.5-pro-001": true,
41 "gemini-1.5-pro-002": true,
42 "gemini-1.5-flash-001": true,
43 "gemini-1.5-flash-002": true,
44 }
45
46 // Tokenizer is a local tokenizer for text.
47 type Tokenizer struct {
48 processor *sentencepiece.Processor
49 }
50
51 // CountTokensResponse is the response of [Tokenizer.CountTokens].
52 type CountTokensResponse struct {
53 TotalTokens int32
54 }
55
56 // New creates a new [Tokenizer] from a model name; the model name is the same
57 // as you would pass to a [genai.Client.GenerativeModel].
58 func New(modelName string) (*Tokenizer, error) {
59 if !supportedModels[modelName] {
60 return nil, fmt.Errorf("model %s is not supported", modelName)
61 }
62
63 data, err := loadModelData(gemmaModelURL, gemmaModelHash)
64 if err != nil {
65 return nil, fmt.Errorf("loading model: %w", err)
66 }
67
68 processor, err := sentencepiece.NewProcessor(bytes.NewReader(data))
69 if err != nil {
70 return nil, fmt.Errorf("creating processor: %w", err)
71 }
72
73 return &Tokenizer{processor: processor}, nil
74 }
75
76 // CountTokens counts the tokens in all the given parts and returns their
77 // sum. Only [genai.Text] parts are suppored; an error will be returned if
78 // non-text parts are provided.
79 func (tok *Tokenizer) CountTokens(parts ...genai.Part) (*CountTokensResponse, error) {
80 sum := 0
81
82 for _, part := range parts {
83 if t, ok := part.(genai.Text); ok {
84 toks := tok.processor.Encode(string(t))
85 sum += len(toks)
86 } else {
87 return nil, fmt.Errorf("Tokenizer.CountTokens only supports Text parts")
88 }
89 }
90
91 return &CountTokensResponse{TotalTokens: int32(sum)}, nil
92 }
93
94 // gemmaModelURL is the URL from which we download the model file.
95 const gemmaModelURL = "https://raw.githubusercontent.com/google/gemma_pytorch/33b652c465537c6158f9a472ea5700e5e770ad3f/tokenizer/tokenizer.model"
96
97 // gemmaModelHash is the expected hash of the model file (as calculated
98 // by [hashString]).
99 const gemmaModelHash = "61a7b147390c64585d6c3543dd6fc636906c9af3865a5548f27f31aee1d4c8e2"
100
101 // downloadModelFile downloads a file from the given URL.
102 func downloadModelFile(url string) ([]byte, error) {
103 resp, err := http.Get(url)
104 if err != nil {
105 return nil, err
106 }
107 defer resp.Body.Close()
108
109 return io.ReadAll(resp.Body)
110 }
111
112 // hashString computes a hex string of the SHA256 hash of data.
113 func hashString(data []byte) string {
114 hash256 := sha256.Sum256(data)
115 return hex.EncodeToString(hash256[:])
116 }
117
118 // loadModelData loads model data from the given URL, using a local file-system
119 // cache. wantHash is the hash (as returned by [hashString] expected on the
120 // loaded data.
121 //
122 // Caching logic:
123 //
124 // Assuming $TEMP_DIR is the temporary directory used by the OS, this function
125 // uses the file $TEMP_DIR/vertexai_tokenizer_model/$urlhash as a cache, where
126 // $urlhash is hashString(url).
127 //
128 // If this cache file doesn't exist, or the data it contains doesn't match
129 // wantHash, downloads data from the URL and writes it into the cache. If the
130 // URL's data doesn't match the hash, an error is returned.
131 func loadModelData(url string, wantHash string) ([]byte, error) {
132 urlhash := hashString([]byte(url))
133 cacheDir := filepath.Join(os.TempDir(), "vertexai_tokenizer_model")
134 cachePath := filepath.Join(cacheDir, urlhash)
135
136 cacheData, err := os.ReadFile(cachePath)
137 if err != nil || hashString(cacheData) != wantHash {
138 cacheData, err = downloadModelFile(url)
139 if err != nil {
140 return nil, fmt.Errorf("loading cache and downloading model: %w", err)
141 }
142
143 if hashString(cacheData) != wantHash {
144 return nil, fmt.Errorf("downloaded model hash mismatch")
145 }
146
147 err = os.MkdirAll(cacheDir, 0770)
148 if err != nil {
149 return nil, fmt.Errorf("creating cache dir: %w", err)
150 }
151 err = os.WriteFile(cachePath, cacheData, 0660)
152 if err != nil {
153 return nil, fmt.Errorf("writing cache file: %w", err)
154 }
155 }
156
157 return cacheData, nil
158 }