Debian Codegraph @

vertexai/genai/caching_test.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 genai
16
17 import (
18 "context"
19 "fmt"
20 "os"
21 "strings"
22 "testing"
23 "time"
24
25 pb "cloud.google.com/go/aiplatform/apiv1beta1/aiplatformpb"
26 "github.com/google/go-cmp/cmp"
27 "github.com/google/go-cmp/cmp/cmpopts"
28 "google.golang.org/api/iterator"
29 durationpb "google.golang.org/protobuf/types/known/durationpb"
30 timestamppb "google.golang.org/protobuf/types/known/timestamppb"
31 )
32
33 func TestPopulateCachedContent(t *testing.T) {
34 tm := time.Date(2030, 1, 1, 0, 0, 0, 0, time.UTC)
35 cmpOpt := cmpopts.IgnoreUnexported(
36 timestamppb.Timestamp{},
37 durationpb.Duration{},
38 )
39 for _, test := range []struct {
40 proto *pb.CachedContent
41 veneer *CachedContent
42 }{
43 {&pb.CachedContent{}, &CachedContent{}},
44 {
45 &pb.CachedContent{Expiration: &pb.CachedContent_ExpireTime{ExpireTime: timestamppb.New(tm)}},
46 &CachedContent{Expiration: ExpireTimeOrTTL{ExpireTime: tm}},
47 },
48 {
49 &pb.CachedContent{Expiration: &pb.CachedContent_Ttl{durationpb.New(time.Hour)}},
50 &CachedContent{Expiration: ExpireTimeOrTTL{TTL: time.Hour}},
51 },
52 } {
53 var gotp pb.CachedContent
54 populateCachedContentTo(&gotp, test.veneer)
55 if g, w := gotp.Expiration, test.proto.Expiration; !cmp.Equal(g, w, cmpOpt) {
56 t.Errorf("from %v to proto: got %v, want %v", test.veneer.Expiration, g, w)
57 }
58
59 var gotv CachedContent
60 populateCachedContentFrom(&gotv, test.proto)
61 if g, w := gotv.Expiration, test.veneer.Expiration; !cmp.Equal(g, w) {
62 t.Errorf("from %v to veneer: got %v, want %v", test.proto.Expiration, g, w)
63 }
64 }
65 }
66
67 func testCaching(t *testing.T, client *Client) {
68 ctx := context.Background()
69 const model = "gemini-1.5-pro-001"
70
71 t.Run("CRUD", func(t *testing.T) {
72 must := func(cc *CachedContent, err error) *CachedContent {
73 t.Helper()
74 if err != nil {
75 t.Fatal(err)
76 }
77 return cc
78 }
79
80 vertexProject := os.Getenv("VERTEX_PROJECT_ID")
81
82 want := &CachedContent{
83 Model: "projects/" + vertexProject +
84 "/locations/us-central1/publishers/google/models/" + model,
85 CreateTime: time.Now().UTC(),
86 UpdateTime: time.Now().UTC(),
87 }
88
89 compare := func(got *CachedContent, expireTime time.Time) {
90 t.Helper()
91 want.Expiration.ExpireTime = expireTime
92 if diff := cmp.Diff(want, got,
93 cmpopts.EquateApproxTime(10*time.Second),
94 cmpopts.IgnoreFields(CachedContent{}, "Name", "UpdateTime")); diff != "" {
95 t.Errorf("mismatch (-want, +got):\n%s", diff)
96 }
97 }
98
99 gcsFilePath := fmt.Sprintf("gs://0002-test-multimodal-%s/embeddings/xray-embedding.json", vertexProject)
100
101 ttl := 30 * time.Minute
102 wantExpireTime := time.Now().Add(ttl)
103 argcc := &CachedContent{
104 Model: model,
105 Expiration: ExpireTimeOrTTL{TTL: ttl},
106 Contents: []*Content{NewUserContent(FileData{
107 MIMEType: "text/plain",
108 FileURI: gcsFilePath})},
109 }
110 cc := must(client.CreateCachedContent(ctx, argcc))
111 compare(cc, wantExpireTime)
112 name := cc.Name
113 cc2 := must(client.GetCachedContent(ctx, name))
114 compare(cc2, wantExpireTime)
115 gotList := listAll(t, client.ListCachedContents(ctx))
116 var cc3 *CachedContent
117 for _, cc := range gotList {
118 if cc.Name == name {
119 cc3 = cc
120 break
121 }
122 }
123 if cc3 == nil {
124 t.Fatal("did not find created in list")
125 }
126 compare(cc3, wantExpireTime)
127
128 // Update using expire time.
129 newExpireTime := cc3.Expiration.ExpireTime.Add(15 * time.Minute)
130 cc4 := must(client.UpdateCachedContent(ctx, cc3, &CachedContentToUpdate{
131 Expiration: &ExpireTimeOrTTL{ExpireTime: newExpireTime},
132 }))
133 compare(cc4, newExpireTime)
134
135 t.Run("update-ttl", func(t *testing.T) {
136 // Update using TTL.
137 cc5 := must(client.UpdateCachedContent(ctx, cc4, &CachedContentToUpdate{
138 Expiration: &ExpireTimeOrTTL{TTL: ttl},
139 }))
140 compare(cc5, time.Now().Add(ttl))
141 })
142
143 if err := client.DeleteCachedContent(ctx, name); err != nil {
144 t.Fatal(err)
145 }
146
147 if err := client.DeleteCachedContent(ctx, "bad name"); err == nil {
148 t.Fatal("want error, got nil")
149 }
150 })
151 t.Run("generation", func(t *testing.T) {
152 txt := strings.Repeat("George Washington was the first president of the United States. ", 3000)
153 argcc := &CachedContent{
154 Model: model,
155 Contents: []*Content{{Role: "user", Parts: []Part{Text(txt)}}},
156 }
157 cc, err := client.CreateCachedContent(ctx, argcc)
158 if err != nil {
159 t.Fatal(err)
160 }
161 defer client.DeleteCachedContent(ctx, cc.Name)
162 m := client.GenerativeModelFromCachedContent(cc)
163 res, err := m.GenerateContent(ctx, Text("Who was the first US president?"))
164 if err != nil {
165 t.Fatal(err)
166 }
167 got := responseString(res)
168 const want = "Washington"
169 if !strings.Contains(got, want) {
170 t.Errorf("got %q, want string containing %q", got, want)
171 }
172 })
173 }
174
175 func listAll(t *testing.T, iter *CachedContentIterator) []*CachedContent {
176 var ccs []*CachedContent
177 for {
178 cc, err := iter.Next()
179 if err == iterator.Done {
180 break
181 }
182 if err != nil {
183 t.Fatal(err)
184 }
185 ccs = append(ccs, cc)
186 }
187 return ccs
188 }