Debian Codegraph @

vertexai/genai/caching.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 "errors"
20 "fmt"
21 "time"
22
23 aiplatform "cloud.google.com/go/aiplatform/apiv1beta1"
24 pb "cloud.google.com/go/aiplatform/apiv1beta1/aiplatformpb"
25 "google.golang.org/api/iterator"
26 durationpb "google.golang.org/protobuf/types/known/durationpb"
27 fieldmaskpb "google.golang.org/protobuf/types/known/fieldmaskpb"
28 timestamppb "google.golang.org/protobuf/types/known/timestamppb"
29 )
30
31 type cacheClient = aiplatform.GenAiCacheClient
32
33 var (
34 newCacheClient = aiplatform.NewGenAiCacheClient
35 newCacheRESTClient = aiplatform.NewGenAiCacheRESTClient
36 )
37
38 // GenerativeModelFromCachedContent returns a [GenerativeModel] that uses the given [CachedContent].
39 // The argument should come from a call to [Client.CreateCachedContent] or [Client.GetCachedContent].
40 func (c *Client) GenerativeModelFromCachedContent(cc *CachedContent) *GenerativeModel {
41 return &GenerativeModel{
42 c: c,
43 name: cc.Model,
44 fullName: inferFullModelName(c.projectID, c.location, cc.Model),
45 CachedContentName: cc.Name,
46 }
47 }
48
49 // CreateCachedContent creates a new CachedContent.
50 // The argument should contain a model name and some data to be cached, which can include
51 // contents, a system instruction, tools and/or tool configuration. It can also
52 // include an expiration time or TTL. But it should not include a name; the system
53 // will generate one.
54 //
55 // The return value will contain the name, which should be used to refer to the CachedContent
56 // in other API calls. It will also hold various metadata like expiration and creation time.
57 // It will not contain any of the actual content provided as input.
58 //
59 // You can use the return value to create a model with [Client.GenerativeModelFromCachedContent].
60 // Or you can set [GenerativeModel.CachedContentName] to the name of the CachedContent, in which
61 // case you must ensure that the model provided in this call matches the name in the [GenerativeModel].
62 func (c *Client) CreateCachedContent(ctx context.Context, cc *CachedContent) (*CachedContent, error) {
63 if cc.Name != "" {
64 return nil, errors.New("genai.CreateCachedContent: do not provide a name; one will be generated")
65 }
66 pcc := cc.toProto()
67 pcc.Model = inferFullModelName(c.projectID, c.location, pcc.Model)
68 return c.cachedContentFromProto(c.cc.CreateCachedContent(ctx, &pb.CreateCachedContentRequest{
69 Parent: c.parent(),
70 CachedContent: pcc,
71 }))
72 }
73
74 // GetCachedContent retrieves the CachedContent with the given name.
75 func (c *Client) GetCachedContent(ctx context.Context, name string) (*CachedContent, error) {
76 return c.cachedContentFromProto(c.cc.GetCachedContent(ctx, &pb.GetCachedContentRequest{Name: name}))
77 }
78
79 // DeleteCachedContent deletes the CachedContent with the given name.
80 func (c *Client) DeleteCachedContent(ctx context.Context, name string) error {
81 return c.cc.DeleteCachedContent(ctx, &pb.DeleteCachedContentRequest{Name: name})
82 }
83
84 // CachedContentToUpdate specifies which fields of a CachedContent to modify in a call to
85 // [Client.UpdateCachedContent].
86 type CachedContentToUpdate struct {
87 // If non-nil, update the expire time or TTL.
88 Expiration *ExpireTimeOrTTL
89 }
90
91 // UpdateCachedContent modifies the [CachedContent] according to the values
92 // of the [CachedContentToUpdate] struct.
93 // It returns the modified CachedContent.
94 //
95 // The argument CachedContent must have its Name field populated.
96 // If its UpdateTime field is non-zero, it will be compared with the update time
97 // of the stored CachedContent and the call will fail if they differ.
98 // This avoids a race condition when two updates are attempted concurrently.
99 // All other fields of the argument CachedContent are ignored.
100 func (c *Client) UpdateCachedContent(ctx context.Context, cc *CachedContent, ccu *CachedContentToUpdate) (*CachedContent, error) {
101 if ccu == nil || ccu.Expiration == nil {
102 return nil, errors.New("cloud.google.com/go/vertexai/genai.UpdateCachedContent: no update specified")
103 }
104 cc2 := &CachedContent{
105 Name: cc.Name,
106 UpdateTime: cc.UpdateTime,
107 Expiration: *ccu.Expiration,
108 }
109 mask := "expire_time"
110 if ccu.Expiration.ExpireTime.IsZero() {
111 mask = "ttl"
112 }
113 return c.cachedContentFromProto(c.cc.UpdateCachedContent(ctx, &pb.UpdateCachedContentRequest{
114 CachedContent: cc2.toProto(),
115 UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{mask}},
116 }))
117 }
118
119 // ListCachedContents lists all the CachedContents associated with the project and location.
120 func (c *Client) ListCachedContents(ctx context.Context) *CachedContentIterator {
121 return &CachedContentIterator{
122 it: c.cc.ListCachedContents(ctx, &pb.ListCachedContentsRequest{Parent: c.parent()}),
123 }
124 }
125
126 // A CachedContentIterator iterates over CachedContents.
127 type CachedContentIterator struct {
128 it *aiplatform.CachedContentIterator
129 }
130
131 // Next returns the next result. Its second return value is iterator.Done if there are no more
132 // results. Once Next returns Done, all subsequent calls will return Done.
133 func (it *CachedContentIterator) Next() (*CachedContent, error) {
134 m, err := it.it.Next()
135 if err != nil {
136 return nil, err
137 }
138 return (CachedContent{}).fromProto(m), nil
139 }
140
141 // PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
142 func (it *CachedContentIterator) PageInfo() *iterator.PageInfo {
143 return it.it.PageInfo()
144 }
145
146 func (c *Client) cachedContentFromProto(pcc *pb.CachedContent, err error) (*CachedContent, error) {
147 if err != nil {
148 return nil, err
149 }
150 cc := (CachedContent{}).fromProto(pcc)
151 return cc, nil
152 }
153
154 // ExpireTimeOrTTL describes the time when a resource expires.
155 // If ExpireTime is non-zero, it is the expiration time.
156 // Otherwise, the expiration time is the value of TTL ("time to live") added
157 // to the current time.
158 type ExpireTimeOrTTL struct {
159 ExpireTime time.Time
160 TTL time.Duration
161 }
162
163 // populateCachedContentTo populates some fields of p from v.
164 func populateCachedContentTo(p *pb.CachedContent, v *CachedContent) {
165 exp := v.Expiration
166 if !exp.ExpireTime.IsZero() {
167 p.Expiration = &pb.CachedContent_ExpireTime{
168 ExpireTime: timestamppb.New(exp.ExpireTime),
169 }
170 } else if exp.TTL != 0 {
171 p.Expiration = &pb.CachedContent_Ttl{
172 Ttl: durationpb.New(exp.TTL),
173 }
174 }
175 // If both fields of v.Expiration are zero, leave p.Expiration unset.
176 }
177
178 // populateCachedContentFrom populates some fields of v from p.
179 func populateCachedContentFrom(v *CachedContent, p *pb.CachedContent) {
180 if p.Expiration == nil {
181 return
182 }
183 switch e := p.Expiration.(type) {
184 case *pb.CachedContent_ExpireTime:
185 v.Expiration.ExpireTime = pvTimeFromProto(e.ExpireTime)
186 case *pb.CachedContent_Ttl:
187 v.Expiration.TTL = e.Ttl.AsDuration()
188 default:
189 panic(fmt.Sprintf("unknown type of CachedContent.Expiration: %T", p.Expiration))
190 }
191 }