| 1 |
// Copyright 2023 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 |
// To get the protoveneer tool: |
| 16 |
// go install golang.org/x/exp/protoveneer/cmd/protoveneer@latest |
| 17 |
|
| 18 |
//go:generate protoveneer -license license.txt config.yaml ../../aiplatform/apiv1beta1/aiplatformpb |
| 19 |
|
| 20 |
package genai |
| 21 |
|
| 22 |
import ( |
| 23 |
"context" |
| 24 |
"fmt" |
| 25 |
"io" |
| 26 |
"log" |
| 27 |
"os" |
| 28 |
"strings" |
| 29 |
|
| 30 |
aiplatform "cloud.google.com/go/aiplatform/apiv1beta1" |
| 31 |
pb "cloud.google.com/go/aiplatform/apiv1beta1/aiplatformpb" |
| 32 |
"cloud.google.com/go/vertexai/internal" |
| 33 |
"google.golang.org/api/iterator" |
| 34 |
"google.golang.org/api/option" |
| 35 |
) |
| 36 |
|
| 37 |
// A Client is a Google Vertex AI client. |
| 38 |
type Client struct { |
| 39 |
pc *aiplatform.PredictionClient |
| 40 |
cc *cacheClient |
| 41 |
projectID string |
| 42 |
location string |
| 43 |
} |
| 44 |
|
| 45 |
// NewClient creates a new Google Vertex AI client. |
| 46 |
// |
| 47 |
// Clients should be reused instead of created as needed. The methods of Client |
| 48 |
// are safe for concurrent use by multiple goroutines. |
| 49 |
// projectID is your GCP project; location is GCP region/location per |
| 50 |
// https://cloud.google.com/vertex-ai/docs/general/locations |
| 51 |
// If location is empty, this function attempts to infer it from environment |
| 52 |
// variables and falls back to a default location if unsuccessful. |
| 53 |
// |
| 54 |
// You may configure the client by passing in options from the |
| 55 |
// [google.golang.org/api/option] package. You may also use options defined in |
| 56 |
// this package, such as [WithREST]. |
| 57 |
func NewClient(ctx context.Context, projectID, location string, opts ...option.ClientOption) (*Client, error) { |
| 58 |
log.Println(`WARNING: Starting on June 24, 2025, the cloud.google.com/go/vertexai/genai package is deprecated and will be removed on June 24, 2026, except cloud.google.com/go/vertexai/genai/tokenizer. |
| 59 |
New users are encouraged to use the Google GenAI Go SDK available at [google.golang.org/genai](http://pkg.go.dev/google.golang.org/genai). |
| 60 |
For information about migrating to the Google Gen AI SDK, see [Vertex AI SDK migration guide](https://cloud.google.com/vertex-ai/generative-ai/docs/deprecations/genai-vertexai-sdk)`) |
| 61 |
location = inferLocation(location) |
| 62 |
endpoint := fmt.Sprintf("%s-aiplatform.googleapis.com:443", location) |
| 63 |
if location == "global" { |
| 64 |
endpoint = "aiplatform.googleapis.com:443" |
| 65 |
} |
| 66 |
conf := newConfig(opts...) |
| 67 |
return newClient(ctx, projectID, location, endpoint, conf, opts) |
| 68 |
} |
| 69 |
|
| 70 |
func newClient(ctx context.Context, projectID, location, endpoint string, conf config, opts []option.ClientOption) (*Client, error) { |
| 71 |
opts = append([]option.ClientOption{option.WithEndpoint(endpoint)}, opts...) |
| 72 |
c := &Client{projectID: projectID, location: location} |
| 73 |
|
| 74 |
if err := setGAPICClient(ctx, &c.pc, conf, |
| 75 |
aiplatform.NewPredictionRESTClient, aiplatform.NewPredictionClient, opts); err != nil { |
| 76 |
return nil, err |
| 77 |
} |
| 78 |
if err := setGAPICClient(ctx, &c.cc, conf, newCacheRESTClient, newCacheClient, opts); err != nil { |
| 79 |
return nil, err |
| 80 |
} |
| 81 |
return c, nil |
| 82 |
} |
| 83 |
|
| 84 |
type sgci interface{ SetGoogleClientInfo(...string) } |
| 85 |
|
| 86 |
func setGAPICClient[ClientType sgci](ctx context.Context, pf *ClientType, conf config, newREST, newGRPC func(context.Context, ...option.ClientOption) (ClientType, error), opts []option.ClientOption) error { |
| 87 |
var c ClientType |
| 88 |
var err error |
| 89 |
if conf.withREST { |
| 90 |
c, err = newREST(ctx, opts...) |
| 91 |
} else { |
| 92 |
c, err = newGRPC(ctx, opts...) |
| 93 |
} |
| 94 |
if err != nil { |
| 95 |
return err |
| 96 |
} |
| 97 |
kvs := []string{"gccl", internal.Version} |
| 98 |
if conf.ciKey != "" && conf.ciValue != "" { |
| 99 |
kvs = append(kvs, conf.ciKey, conf.ciValue) |
| 100 |
} |
| 101 |
c.SetGoogleClientInfo(kvs...) |
| 102 |
*pf = c |
| 103 |
return nil |
| 104 |
} |
| 105 |
|
| 106 |
// Close closes the client. |
| 107 |
func (c *Client) Close() error { |
| 108 |
pcErr := c.pc.Close() |
| 109 |
ccErr := c.cc.Close() |
| 110 |
|
| 111 |
switch { |
| 112 |
case pcErr != nil: |
| 113 |
return pcErr |
| 114 |
case ccErr != nil: |
| 115 |
return ccErr |
| 116 |
default: |
| 117 |
return nil |
| 118 |
} |
| 119 |
} |
| 120 |
|
| 121 |
const defaultLocation = "us-central1" |
| 122 |
|
| 123 |
// inferLocation infers the GCP location from its parameter, env vars or |
| 124 |
// a default location. |
| 125 |
func inferLocation(location string) string { |
| 126 |
if location != "" { |
| 127 |
return location |
| 128 |
} |
| 129 |
if location = os.Getenv("GOOGLE_CLOUD_REGION"); location != "" { |
| 130 |
return location |
| 131 |
} |
| 132 |
if location = os.Getenv("CLOUD_ML_REGION"); location != "" { |
| 133 |
return location |
| 134 |
} |
| 135 |
|
| 136 |
return defaultLocation |
| 137 |
} |
| 138 |
|
| 139 |
// parent returns a Google Cloud reference to the project and location |
| 140 |
// for this client. |
| 141 |
func (c *Client) parent() string { |
| 142 |
return fmt.Sprintf("projects/%s/locations/%s", c.projectID, c.location) |
| 143 |
} |
| 144 |
|
| 145 |
// GenerativeModel is a model that can generate text. |
| 146 |
// Create one with [Client.GenerativeModel], then configure |
| 147 |
// it by setting the exported fields. |
| 148 |
// |
| 149 |
// The model holds all the config for a GenerateContentRequest, so the GenerateContent method |
| 150 |
// can use a vararg for the content. |
| 151 |
type GenerativeModel struct { |
| 152 |
c *Client |
| 153 |
name string |
| 154 |
fullName string |
| 155 |
|
| 156 |
GenerationConfig |
| 157 |
SafetySettings []*SafetySetting |
| 158 |
Tools []*Tool |
| 159 |
ToolConfig *ToolConfig // configuration for tools |
| 160 |
SystemInstruction *Content |
| 161 |
// The name of the CachedContent to use. |
| 162 |
// Must have already been created with [Client.CreateCachedContent]. |
| 163 |
CachedContentName string |
| 164 |
} |
| 165 |
|
| 166 |
const defaultMaxOutputTokens = 2048 |
| 167 |
|
| 168 |
// GenerativeModel creates a new instance of the named model. |
| 169 |
// name is a string model name like "gemini-1.0-pro" or "models/gemini-1.0-pro" |
| 170 |
// for Google-published models. |
| 171 |
// See https://cloud.google.com/vertex-ai/generative-ai/docs/learn/model-versioning |
| 172 |
// for details on model naming and versioning, and |
| 173 |
// https://cloud.google.com/vertex-ai/generative-ai/docs/model-garden/explore-models |
| 174 |
// for providing model garden names. The SDK isn't familiar with custom model |
| 175 |
// garden models, and will pass your model name to the backend API server. |
| 176 |
func (c *Client) GenerativeModel(name string) *GenerativeModel { |
| 177 |
return &GenerativeModel{ |
| 178 |
c: c, |
| 179 |
name: name, |
| 180 |
fullName: inferFullModelName(c.projectID, c.location, name), |
| 181 |
} |
| 182 |
} |
| 183 |
|
| 184 |
// inferFullModelName infers the full model name (with all the required prefixes) |
| 185 |
func inferFullModelName(project, location, name string) string { |
| 186 |
pubName := name |
| 187 |
if !strings.Contains(name, "/") { |
| 188 |
pubName = "publishers/google/models/" + name |
| 189 |
} else if strings.HasPrefix(name, "models/") { |
| 190 |
pubName = "publishers/google/" + name |
| 191 |
} |
| 192 |
|
| 193 |
if !strings.HasPrefix(pubName, "publishers/") { |
| 194 |
return pubName |
| 195 |
} |
| 196 |
return fmt.Sprintf("projects/%s/locations/%s/%s", project, location, pubName) |
| 197 |
} |
| 198 |
|
| 199 |
// Name returns the name of the model. |
| 200 |
func (m *GenerativeModel) Name() string { |
| 201 |
return m.name |
| 202 |
} |
| 203 |
|
| 204 |
// GenerateContent produces a single request and response. |
| 205 |
func (m *GenerativeModel) GenerateContent(ctx context.Context, parts ...Part) (*GenerateContentResponse, error) { |
| 206 |
return m.generateContent(ctx, m.newGenerateContentRequest(NewUserContent(parts...))) |
| 207 |
} |
| 208 |
|
| 209 |
// GenerateContentStream returns an iterator that enumerates responses. |
| 210 |
func (m *GenerativeModel) GenerateContentStream(ctx context.Context, parts ...Part) *GenerateContentResponseIterator { |
| 211 |
streamClient, err := m.c.pc.StreamGenerateContent(ctx, m.newGenerateContentRequest(NewUserContent(parts...))) |
| 212 |
return &GenerateContentResponseIterator{ |
| 213 |
sc: streamClient, |
| 214 |
err: err, |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
func (m *GenerativeModel) generateContent(ctx context.Context, req *pb.GenerateContentRequest) (*GenerateContentResponse, error) { |
| 219 |
res, err := m.c.pc.GenerateContent(ctx, req) |
| 220 |
|
| 221 |
if err != nil { |
| 222 |
return nil, err |
| 223 |
} |
| 224 |
return protoToResponse(res) |
| 225 |
} |
| 226 |
|
| 227 |
func (m *GenerativeModel) newGenerateContentRequest(contents ...*Content) *pb.GenerateContentRequest { |
| 228 |
return &pb.GenerateContentRequest{ |
| 229 |
Model: m.fullName, |
| 230 |
Contents: pvTransformSlice(contents, (*Content).toProto), |
| 231 |
SafetySettings: pvTransformSlice(m.SafetySettings, (*SafetySetting).toProto), |
| 232 |
Tools: pvTransformSlice(m.Tools, (*Tool).toProto), |
| 233 |
ToolConfig: m.ToolConfig.toProto(), |
| 234 |
GenerationConfig: m.GenerationConfig.toProto(), |
| 235 |
SystemInstruction: m.SystemInstruction.toProto(), |
| 236 |
CachedContent: m.CachedContentName, |
| 237 |
} |
| 238 |
} |
| 239 |
|
| 240 |
// GenerateContentResponseIterator is an iterator over GnerateContentResponse. |
| 241 |
type GenerateContentResponseIterator struct { |
| 242 |
sc pb.PredictionService_StreamGenerateContentClient |
| 243 |
err error |
| 244 |
merged *GenerateContentResponse |
| 245 |
cs *ChatSession |
| 246 |
} |
| 247 |
|
| 248 |
// Next returns the next response. |
| 249 |
func (iter *GenerateContentResponseIterator) Next() (*GenerateContentResponse, error) { |
| 250 |
if iter.err != nil { |
| 251 |
return nil, iter.err |
| 252 |
} |
| 253 |
resp, err := iter.sc.Recv() |
| 254 |
iter.err = err |
| 255 |
if err == io.EOF { |
| 256 |
if iter.cs != nil && iter.merged != nil { |
| 257 |
iter.cs.addToHistory(iter.merged.Candidates) |
| 258 |
} |
| 259 |
return nil, iterator.Done |
| 260 |
} |
| 261 |
if err != nil { |
| 262 |
return nil, err |
| 263 |
} |
| 264 |
gcp, err := protoToResponse(resp) |
| 265 |
if err != nil { |
| 266 |
iter.err = err |
| 267 |
return nil, err |
| 268 |
} |
| 269 |
// Merge this response in with the ones we've already seen. |
| 270 |
iter.merged = joinResponses(iter.merged, gcp) |
| 271 |
// If this is part of a ChatSession, remember the response for the history. |
| 272 |
return gcp, nil |
| 273 |
} |
| 274 |
|
| 275 |
// MergedResponse returns the result of combining all the streamed responses seen so far. |
| 276 |
// After iteration completes, the merged response should match the response obtained without streaming |
| 277 |
// (that is, if [GenerativeModel.GenerateContent] were called). |
| 278 |
func (iter *GenerateContentResponseIterator) MergedResponse() *GenerateContentResponse { |
| 279 |
return iter.merged |
| 280 |
} |
| 281 |
|
| 282 |
func protoToResponse(resp *pb.GenerateContentResponse) (*GenerateContentResponse, error) { |
| 283 |
gcp := (GenerateContentResponse{}).fromProto(resp) |
| 284 |
// Assume a non-nil PromptFeedback is an error. |
| 285 |
// TODO: confirm. |
| 286 |
if gcp.PromptFeedback != nil { |
| 287 |
return nil, &BlockedError{PromptFeedback: gcp.PromptFeedback} |
| 288 |
} |
| 289 |
// If any candidate is blocked, error. |
| 290 |
// TODO: is this too harsh? |
| 291 |
for _, c := range gcp.Candidates { |
| 292 |
if c.FinishReason == FinishReasonSafety { |
| 293 |
return nil, &BlockedError{Candidate: c} |
| 294 |
} |
| 295 |
} |
| 296 |
return gcp, nil |
| 297 |
} |
| 298 |
|
| 299 |
// CountTokens counts the number of tokens in the content. |
| 300 |
func (m *GenerativeModel) CountTokens(ctx context.Context, parts ...Part) (*CountTokensResponse, error) { |
| 301 |
req := m.newCountTokensRequest(NewUserContent(parts...)) |
| 302 |
res, err := m.c.pc.CountTokens(ctx, req) |
| 303 |
if err != nil { |
| 304 |
return nil, err |
| 305 |
} |
| 306 |
|
| 307 |
return (CountTokensResponse{}).fromProto(res), nil |
| 308 |
} |
| 309 |
|
| 310 |
func (m *GenerativeModel) newCountTokensRequest(contents ...*Content) *pb.CountTokensRequest { |
| 311 |
return &pb.CountTokensRequest{ |
| 312 |
Endpoint: m.fullName, |
| 313 |
Model: m.fullName, |
| 314 |
Contents: pvTransformSlice(contents, (*Content).toProto), |
| 315 |
} |
| 316 |
} |
| 317 |
|
| 318 |
// A BlockedError indicates that the model's response was blocked. |
| 319 |
// There can be two underlying causes: the prompt or a candidate response. |
| 320 |
type BlockedError struct { |
| 321 |
// If non-nil, the model's response was blocked. |
| 322 |
// Consult the Candidate and SafetyRatings fields for details. |
| 323 |
Candidate *Candidate |
| 324 |
|
| 325 |
// If non-nil, there was a problem with the prompt. |
| 326 |
PromptFeedback *PromptFeedback |
| 327 |
} |
| 328 |
|
| 329 |
func (e *BlockedError) Error() string { |
| 330 |
var b strings.Builder |
| 331 |
fmt.Fprintf(&b, "blocked: ") |
| 332 |
if e.Candidate != nil { |
| 333 |
fmt.Fprintf(&b, "candidate: %s", e.Candidate.FinishReason) |
| 334 |
} |
| 335 |
if e.PromptFeedback != nil { |
| 336 |
if e.Candidate != nil { |
| 337 |
fmt.Fprintf(&b, ", ") |
| 338 |
} |
| 339 |
fmt.Fprintf(&b, "prompt: %v (%s)", e.PromptFeedback.BlockReason, e.PromptFeedback.BlockReasonMessage) |
| 340 |
} |
| 341 |
return b.String() |
| 342 |
} |
| 343 |
|
| 344 |
// joinResponses merges the two responses, which should be the result of a streaming call. |
| 345 |
// The first argument is modified. |
| 346 |
func joinResponses(dest, src *GenerateContentResponse) *GenerateContentResponse { |
| 347 |
if dest == nil { |
| 348 |
return src |
| 349 |
} |
| 350 |
dest.Candidates = joinCandidateLists(dest.Candidates, src.Candidates) |
| 351 |
// Keep dest.PromptFeedback. |
| 352 |
// TODO: Take the last UsageMetadata. |
| 353 |
return dest |
| 354 |
} |
| 355 |
|
| 356 |
func joinCandidateLists(dest, src []*Candidate) []*Candidate { |
| 357 |
indexToSrcCandidate := map[int32]*Candidate{} |
| 358 |
for _, s := range src { |
| 359 |
indexToSrcCandidate[s.Index] = s |
| 360 |
} |
| 361 |
for _, d := range dest { |
| 362 |
s := indexToSrcCandidate[d.Index] |
| 363 |
if s != nil { |
| 364 |
d.Content = joinContent(d.Content, s.Content) |
| 365 |
// Take the last of these. |
| 366 |
d.FinishReason = s.FinishReason |
| 367 |
d.FinishMessage = s.FinishMessage |
| 368 |
d.SafetyRatings = s.SafetyRatings |
| 369 |
d.CitationMetadata = joinCitationMetadata(d.CitationMetadata, s.CitationMetadata) |
| 370 |
} |
| 371 |
} |
| 372 |
return dest |
| 373 |
} |
| 374 |
|
| 375 |
func joinCitationMetadata(dest, src *CitationMetadata) *CitationMetadata { |
| 376 |
if dest == nil { |
| 377 |
return src |
| 378 |
} |
| 379 |
if src == nil { |
| 380 |
return dest |
| 381 |
} |
| 382 |
dest.Citations = append(dest.Citations, src.Citations...) |
| 383 |
return dest |
| 384 |
} |
| 385 |
|
| 386 |
func joinContent(dest, src *Content) *Content { |
| 387 |
if dest == nil { |
| 388 |
return src |
| 389 |
} |
| 390 |
if src == nil { |
| 391 |
return dest |
| 392 |
} |
| 393 |
// Assume roles are the same. |
| 394 |
dest.Parts = joinParts(dest.Parts, src.Parts) |
| 395 |
return dest |
| 396 |
} |
| 397 |
|
| 398 |
func joinParts(dest, src []Part) []Part { |
| 399 |
return mergeTexts(append(dest, src...)) |
| 400 |
} |
| 401 |
|
| 402 |
func mergeTexts(in []Part) []Part { |
| 403 |
var out []Part |
| 404 |
i := 0 |
| 405 |
for i < len(in) { |
| 406 |
if t, ok := in[i].(Text); ok { |
| 407 |
texts := []string{string(t)} |
| 408 |
var j int |
| 409 |
for j = i + 1; j < len(in); j++ { |
| 410 |
if t, ok := in[j].(Text); ok { |
| 411 |
texts = append(texts, string(t)) |
| 412 |
} else { |
| 413 |
break |
| 414 |
} |
| 415 |
} |
| 416 |
// j is just after the last Text. |
| 417 |
out = append(out, Text(strings.Join(texts, ""))) |
| 418 |
i = j |
| 419 |
} else { |
| 420 |
out = append(out, in[i]) |
| 421 |
i++ |
| 422 |
} |
| 423 |
} |
| 424 |
return out |
| 425 |
} |
| 426 |
|
| 427 |
func int32pToFloat32p(x *int32) *float32 { |
| 428 |
if x == nil { |
| 429 |
return nil |
| 430 |
} |
| 431 |
f := float32(*x) |
| 432 |
return &f |
| 433 |
} |
| 434 |
|
| 435 |
func float32pToInt32p(x *float32) *int32 { |
| 436 |
if x == nil { |
| 437 |
return nil |
| 438 |
} |
| 439 |
i := int32(*x) |
| 440 |
return &i |
| 441 |
} |