| 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 |
package genai |
| 16 |
|
| 17 |
import ( |
| 18 |
"context" |
| 19 |
"errors" |
| 20 |
"fmt" |
| 21 |
"io" |
| 22 |
"log" |
| 23 |
"os" |
| 24 |
"path/filepath" |
| 25 |
"reflect" |
| 26 |
"regexp" |
| 27 |
"strings" |
| 28 |
"testing" |
| 29 |
|
| 30 |
"google.golang.org/api/iterator" |
| 31 |
) |
| 32 |
|
| 33 |
const defaultModel = "gemini-1.0-pro" |
| 34 |
const imageFile = "personWorkingOnComputer.jpg" |
| 35 |
|
| 36 |
func TestLive(t *testing.T) { |
| 37 |
projectID := os.Getenv("VERTEX_PROJECT_ID") |
| 38 |
if testing.Short() { |
| 39 |
t.Skip("skipping live test in -short mode") |
| 40 |
} |
| 41 |
|
| 42 |
if projectID == "" { |
| 43 |
t.Skip("set a VERTEX_PROJECT_ID env var to run live tests") |
| 44 |
} |
| 45 |
|
| 46 |
ctx := context.Background() |
| 47 |
client, err := NewClient(ctx, projectID, defaultLocation) |
| 48 |
if err != nil { |
| 49 |
t.Fatal(err) |
| 50 |
} |
| 51 |
defer client.Close() |
| 52 |
model := client.GenerativeModel(defaultModel) |
| 53 |
model.Temperature = Ptr[float32](0) |
| 54 |
|
| 55 |
t.Run("GenerateContent", func(t *testing.T) { |
| 56 |
resp, err := model.GenerateContent(ctx, Text("What is the average size of a swallow?")) |
| 57 |
if err != nil { |
| 58 |
t.Fatal(err) |
| 59 |
} |
| 60 |
got := responseString(resp) |
| 61 |
checkMatch(t, got, `15.* cm|[1-9].* inches`) |
| 62 |
}) |
| 63 |
t.Run("system-instructions", func(t *testing.T) { |
| 64 |
model := client.GenerativeModel(defaultModel) |
| 65 |
model.Temperature = Ptr[float32](0) |
| 66 |
model.SystemInstruction = NewUserContent(Text("You are Yoda from Star Wars.")) |
| 67 |
resp, err := model.GenerateContent(ctx, Text("What is the average size of a swallow?")) |
| 68 |
if err != nil { |
| 69 |
t.Fatal(err) |
| 70 |
} |
| 71 |
got := responseString(resp) |
| 72 |
checkMatch(t, got, `[1-9][0-9].* (cm|centimeters)|[1-9].* inches`) |
| 73 |
}) |
| 74 |
|
| 75 |
t.Run("streaming", func(t *testing.T) { |
| 76 |
iter := model.GenerateContentStream(ctx, Text("Are you hungry?")) |
| 77 |
got := responsesString(t, iter) |
| 78 |
checkMatch(t, got, `(capable.+experienc.+hunger)|(capacity.+feel)|((don't|do\s+not) (have|possess) .*(a .* body|the ability))`) |
| 79 |
}) |
| 80 |
|
| 81 |
t.Run("chat", func(t *testing.T) { |
| 82 |
session := model.StartChat() |
| 83 |
|
| 84 |
send := func(msg string, streaming bool) string { |
| 85 |
t.Helper() |
| 86 |
t.Logf("sending %q", msg) |
| 87 |
nh := len(session.History) |
| 88 |
if streaming { |
| 89 |
iter := session.SendMessageStream(ctx, Text(msg)) |
| 90 |
for { |
| 91 |
_, err := iter.Next() |
| 92 |
if err == iterator.Done { |
| 93 |
break |
| 94 |
} |
| 95 |
if err != nil { |
| 96 |
t.Fatal(err) |
| 97 |
} |
| 98 |
} |
| 99 |
} else { |
| 100 |
if _, err := session.SendMessage(ctx, Text(msg)); err != nil { |
| 101 |
t.Fatal(err) |
| 102 |
} |
| 103 |
} |
| 104 |
// Check that two items, the sent message and the response) were |
| 105 |
// added to the history. |
| 106 |
if g, w := len(session.History), nh+2; g != w { |
| 107 |
t.Errorf("history length: got %d, want %d", g, w) |
| 108 |
} |
| 109 |
// Last history item is the one we just got from the model. |
| 110 |
return contentString(session.History[len(session.History)-1]) |
| 111 |
} |
| 112 |
|
| 113 |
checkMatch(t, |
| 114 |
send("Name air fryer brands.", false), |
| 115 |
"Philips", "Cuisinart") |
| 116 |
|
| 117 |
checkMatch(t, |
| 118 |
send("Which is best?", true), |
| 119 |
"best", "air fryer", "Philips", "([Cc]onsider|research|compare|preference)", "factors|features") |
| 120 |
|
| 121 |
checkMatch(t, |
| 122 |
send("Say that again.", false), |
| 123 |
"best", "air fryer", "Philips", "([Cc]onsider|research|compare|preference)", "factors|features") |
| 124 |
}) |
| 125 |
|
| 126 |
t.Run("image", func(t *testing.T) { |
| 127 |
vmodel := client.GenerativeModel(defaultModel + "-vision") |
| 128 |
vmodel.Temperature = Ptr[float32](0) |
| 129 |
|
| 130 |
data, err := os.ReadFile(filepath.Join("testdata", imageFile)) |
| 131 |
if err != nil { |
| 132 |
t.Fatal(err) |
| 133 |
} |
| 134 |
resp, err := vmodel.GenerateContent(ctx, |
| 135 |
Text("What is in this picture?"), |
| 136 |
ImageData("jpeg", data)) |
| 137 |
if err != nil { |
| 138 |
t.Fatal(err) |
| 139 |
} |
| 140 |
got := responseString(resp) |
| 141 |
checkMatch(t, got, "picture", "person", "computer|laptop") |
| 142 |
}) |
| 143 |
|
| 144 |
t.Run("blocked", func(t *testing.T) { |
| 145 |
// Blocking semantics have changed; skip these tests for now. |
| 146 |
t.Skip() |
| 147 |
|
| 148 |
iter := model.GenerateContentStream(ctx, Text("How do I make a weapon?")) |
| 149 |
resps, err := all(iter) |
| 150 |
if err == nil { |
| 151 |
t.Fatal("got nil, want error") |
| 152 |
} |
| 153 |
var berr *BlockedError |
| 154 |
if !errors.As(err, &berr) { |
| 155 |
t.Fatalf("got %v (%[1]T), want BlockedError", err) |
| 156 |
} |
| 157 |
if resps != nil { |
| 158 |
t.Errorf("got responses %v, want nil", resps) |
| 159 |
} |
| 160 |
if berr.PromptFeedback != nil { |
| 161 |
t.Errorf("got PromptFeedback %v, want nil", berr.PromptFeedback) |
| 162 |
} |
| 163 |
if berr.Candidate == nil { |
| 164 |
t.Fatal("got nil candidate, expected one") |
| 165 |
} |
| 166 |
if berr.Candidate.FinishReason != FinishReasonSafety { |
| 167 |
t.Errorf("got FinishReason %s, want ContentFilter", berr.Candidate.FinishReason) |
| 168 |
} |
| 169 |
saw := false |
| 170 |
for _, sr := range berr.Candidate.SafetyRatings { |
| 171 |
if sr.Category != HarmCategoryDangerousContent { |
| 172 |
continue |
| 173 |
} |
| 174 |
saw = true |
| 175 |
if !sr.Blocked { |
| 176 |
t.Error("not blocked for dangerous content") |
| 177 |
} |
| 178 |
} |
| 179 |
if !saw { |
| 180 |
t.Error("did not see HarmCategoryDangerousContent") |
| 181 |
} |
| 182 |
}) |
| 183 |
t.Run("max-tokens", func(t *testing.T) { |
| 184 |
maxModel := client.GenerativeModel(defaultModel) |
| 185 |
maxModel.Temperature = Ptr(float32(0)) |
| 186 |
maxModel.SetMaxOutputTokens(10) |
| 187 |
res, err := maxModel.GenerateContent(ctx, Text("What is a dog?")) |
| 188 |
if err != nil { |
| 189 |
t.Fatal(err) |
| 190 |
} |
| 191 |
got := res.Candidates[0].FinishReason |
| 192 |
want := FinishReasonMaxTokens |
| 193 |
if got != want && got != FinishReasonOther { // TODO: should not need FinishReasonOther |
| 194 |
t.Errorf("got %s, want %s", got, want) |
| 195 |
} |
| 196 |
}) |
| 197 |
t.Run("max-tokens-streaming", func(t *testing.T) { |
| 198 |
maxModel := client.GenerativeModel(defaultModel) |
| 199 |
maxModel.Temperature = Ptr[float32](0) |
| 200 |
maxModel.MaxOutputTokens = Ptr[int32](10) |
| 201 |
iter := maxModel.GenerateContentStream(ctx, Text("What is a dog?")) |
| 202 |
var merged *GenerateContentResponse |
| 203 |
for { |
| 204 |
res, err := iter.Next() |
| 205 |
if err == iterator.Done { |
| 206 |
break |
| 207 |
} |
| 208 |
if err != nil { |
| 209 |
t.Fatal(err) |
| 210 |
} |
| 211 |
merged = joinResponses(merged, res) |
| 212 |
} |
| 213 |
want := FinishReasonMaxTokens |
| 214 |
if got := merged.Candidates[0].FinishReason; got != want && got != FinishReasonOther { // TODO: see above |
| 215 |
t.Errorf("got %s, want %s", got, want) |
| 216 |
} |
| 217 |
}) |
| 218 |
t.Run("count-tokens", func(t *testing.T) { |
| 219 |
res, err := model.CountTokens(ctx, Text("The rain in Spain falls mainly on the plain.")) |
| 220 |
if err != nil { |
| 221 |
t.Fatal(err) |
| 222 |
} |
| 223 |
if g, w := res.TotalTokens, int32(10); g != w { |
| 224 |
t.Errorf("got %d, want %d", g, w) |
| 225 |
} |
| 226 |
}) |
| 227 |
t.Run("tools", func(t *testing.T) { |
| 228 |
weatherTool := &Tool{ |
| 229 |
FunctionDeclarations: []*FunctionDeclaration{{ |
| 230 |
Name: "CurrentWeather", |
| 231 |
Description: "Get the current weather in a given location", |
| 232 |
Parameters: &Schema{ |
| 233 |
Type: TypeObject, |
| 234 |
Properties: map[string]*Schema{ |
| 235 |
"location": { |
| 236 |
Type: TypeString, |
| 237 |
Description: "The city and state, e.g. San Francisco, CA", |
| 238 |
}, |
| 239 |
"unit": { |
| 240 |
Type: TypeString, |
| 241 |
Enum: []string{"celsius", "fahrenheit"}, |
| 242 |
}, |
| 243 |
}, |
| 244 |
Required: []string{"location"}, |
| 245 |
}, |
| 246 |
}}, |
| 247 |
} |
| 248 |
model := client.GenerativeModel(defaultModel) |
| 249 |
model.SetTemperature(0) |
| 250 |
model.Tools = []*Tool{weatherTool} |
| 251 |
t.Run("funcall", func(t *testing.T) { |
| 252 |
session := model.StartChat() |
| 253 |
res, err := session.SendMessage(ctx, Text("What is the weather like in New York?")) |
| 254 |
if err != nil { |
| 255 |
t.Fatal(err) |
| 256 |
} |
| 257 |
part := res.Candidates[0].Content.Parts[0] |
| 258 |
funcalls := res.Candidates[0].FunctionCalls() |
| 259 |
if len(funcalls) != 1 { |
| 260 |
t.Fatalf("got %d FunctionCalls, want 1", len(funcalls)) |
| 261 |
} |
| 262 |
funcall, ok := part.(FunctionCall) |
| 263 |
if !ok { |
| 264 |
t.Fatalf("want FunctionCall, got %T", part) |
| 265 |
} |
| 266 |
if g, w := funcall.Name, weatherTool.FunctionDeclarations[0].Name; g != w { |
| 267 |
t.Errorf("FunctionCall.Name: got %q, want %q", g, w) |
| 268 |
} |
| 269 |
if g, c := funcall.Args["location"], "New York"; !strings.Contains(g.(string), c) { |
| 270 |
t.Errorf(`FunctionCall.Args["location"]: got %q, want string containing %q`, g, c) |
| 271 |
} |
| 272 |
res, err = session.SendMessage(ctx, FunctionResponse{ |
| 273 |
Name: weatherTool.FunctionDeclarations[0].Name, |
| 274 |
Response: map[string]any{ |
| 275 |
"weather_there": "cold", |
| 276 |
}, |
| 277 |
}) |
| 278 |
if err != nil { |
| 279 |
t.Fatal(err) |
| 280 |
} |
| 281 |
checkMatch(t, responseString(res), "(it's|it is|weather) .*cold") |
| 282 |
}) |
| 283 |
t.Run("funcall-stream", func(t *testing.T) { |
| 284 |
session := model.StartChat() |
| 285 |
iter := session.SendMessageStream(ctx, Text("What is the weather like in New York?")) |
| 286 |
|
| 287 |
for { |
| 288 |
_, err := iter.Next() |
| 289 |
if err == iterator.Done { |
| 290 |
break |
| 291 |
} |
| 292 |
if err != nil { |
| 293 |
t.Fatal(err) |
| 294 |
} |
| 295 |
} |
| 296 |
res, err := session.SendMessage(ctx, FunctionResponse{ |
| 297 |
Name: weatherTool.FunctionDeclarations[0].Name, |
| 298 |
Response: map[string]any{ |
| 299 |
"weather_there": "cold", |
| 300 |
}, |
| 301 |
}) |
| 302 |
if err != nil { |
| 303 |
t.Fatal(err) |
| 304 |
} |
| 305 |
checkMatch(t, responseString(res), "(it's|it is|weather) .*cold") |
| 306 |
}) |
| 307 |
t.Run("funcall-none", func(t *testing.T) { |
| 308 |
model.ToolConfig = &ToolConfig{ |
| 309 |
FunctionCallingConfig: &FunctionCallingConfig{ |
| 310 |
Mode: FunctionCallingNone, // never return a FunctionCall part |
| 311 |
}, |
| 312 |
} |
| 313 |
session := model.StartChat() |
| 314 |
res, err := session.SendMessage(ctx, Text("What is the weather like in New York?")) |
| 315 |
if err != nil { |
| 316 |
t.Fatal(err) |
| 317 |
} |
| 318 |
// We should not find a FunctionCall part. |
| 319 |
for _, p := range res.Candidates[0].Content.Parts { |
| 320 |
if _, ok := p.(FunctionCall); ok { |
| 321 |
t.Fatal("saw FunctionCall") |
| 322 |
} |
| 323 |
} |
| 324 |
}) |
| 325 |
}) |
| 326 |
t.Run("caching", func(t *testing.T) { testCaching(t, client) }) |
| 327 |
} |
| 328 |
|
| 329 |
func TestLiveDefaultLocation(t *testing.T) { |
| 330 |
projectID := os.Getenv("VERTEX_PROJECT_ID") |
| 331 |
if testing.Short() { |
| 332 |
t.Skip("skipping live test in -short mode") |
| 333 |
} |
| 334 |
|
| 335 |
if projectID == "" { |
| 336 |
t.Skip("set a VERTEX_PROJECT_ID env var to run live tests") |
| 337 |
} |
| 338 |
|
| 339 |
ctx := context.Background() |
| 340 |
// No location is passed explicitly: default is used |
| 341 |
client, err := NewClient(ctx, projectID, "") |
| 342 |
if err != nil { |
| 343 |
t.Fatal(err) |
| 344 |
} |
| 345 |
defer client.Close() |
| 346 |
model := client.GenerativeModel(defaultModel) |
| 347 |
model.Temperature = Ptr[float32](0) |
| 348 |
|
| 349 |
resp, err := model.GenerateContent(ctx, Text("Name the planets in the solar system")) |
| 350 |
if err != nil { |
| 351 |
t.Fatal(err) |
| 352 |
} |
| 353 |
got := responseString(resp) |
| 354 |
checkMatch(t, got, `venus|mars`) |
| 355 |
} |
| 356 |
|
| 357 |
func TestLiveREST(t *testing.T) { |
| 358 |
projectID := os.Getenv("VERTEX_PROJECT_ID") |
| 359 |
if testing.Short() { |
| 360 |
t.Skip("skipping live test in -short mode") |
| 361 |
} |
| 362 |
|
| 363 |
if projectID == "" { |
| 364 |
t.Skip("set a VERTEX_PROJECT_ID env var to run live tests") |
| 365 |
} |
| 366 |
|
| 367 |
ctx := context.Background() |
| 368 |
client, err := NewClient(ctx, projectID, defaultLocation, WithREST()) |
| 369 |
if err != nil { |
| 370 |
t.Fatal(err) |
| 371 |
} |
| 372 |
defer client.Close() |
| 373 |
model := client.GenerativeModel(defaultModel) |
| 374 |
model.SetTemperature(0.0) |
| 375 |
|
| 376 |
resp, err := model.GenerateContent(ctx, Text("What is the average size of a swallow?")) |
| 377 |
if err != nil { |
| 378 |
t.Fatal(err) |
| 379 |
} |
| 380 |
got := responseString(resp) |
| 381 |
checkMatch(t, got, `15.* cm|[1-9].* inches`) |
| 382 |
} |
| 383 |
|
| 384 |
func TestLiveGlobalEndpoint(t *testing.T) { |
| 385 |
projectID := os.Getenv("VERTEX_PROJECT_ID") |
| 386 |
if testing.Short() { |
| 387 |
t.Skip("skipping live test in -short mode") |
| 388 |
} |
| 389 |
|
| 390 |
if projectID == "" { |
| 391 |
t.Skip("set a VERTEX_PROJECT_ID env var to run live tests") |
| 392 |
} |
| 393 |
|
| 394 |
ctx := context.Background() |
| 395 |
client, err := NewClient(ctx, projectID, "global") |
| 396 |
if err != nil { |
| 397 |
t.Fatal(err) |
| 398 |
} |
| 399 |
defer client.Close() |
| 400 |
model := client.GenerativeModel(defaultModel) |
| 401 |
model.SetTemperature(0.0) |
| 402 |
|
| 403 |
resp, err := model.GenerateContent(ctx, Text("What is the average size of a swallow?")) |
| 404 |
if err != nil { |
| 405 |
t.Fatal(err) |
| 406 |
} |
| 407 |
got := responseString(resp) |
| 408 |
checkMatch(t, got, `15.* cm|[1-9].* inches`) |
| 409 |
} |
| 410 |
|
| 411 |
func TestLiveGlobalEndpointREST(t *testing.T) { |
| 412 |
projectID := os.Getenv("VERTEX_PROJECT_ID") |
| 413 |
if testing.Short() { |
| 414 |
t.Skip("skipping live test in -short mode") |
| 415 |
} |
| 416 |
|
| 417 |
if projectID == "" { |
| 418 |
t.Skip("set a VERTEX_PROJECT_ID env var to run live tests") |
| 419 |
} |
| 420 |
|
| 421 |
ctx := context.Background() |
| 422 |
client, err := NewClient(ctx, projectID, "global", WithREST()) |
| 423 |
if err != nil { |
| 424 |
t.Fatal(err) |
| 425 |
} |
| 426 |
defer client.Close() |
| 427 |
model := client.GenerativeModel(defaultModel) |
| 428 |
model.SetTemperature(0.0) |
| 429 |
|
| 430 |
resp, err := model.GenerateContent(ctx, Text("What is the average size of a swallow?")) |
| 431 |
if err != nil { |
| 432 |
t.Fatal(err) |
| 433 |
} |
| 434 |
got := responseString(resp) |
| 435 |
checkMatch(t, got, `15.* cm|[1-9].* inches`) |
| 436 |
} |
| 437 |
|
| 438 |
func TestJoinResponses(t *testing.T) { |
| 439 |
r1 := &GenerateContentResponse{ |
| 440 |
Candidates: []*Candidate{ |
| 441 |
{ |
| 442 |
Index: 2, |
| 443 |
Content: &Content{Role: roleModel, Parts: []Part{Text("r1 i2")}}, |
| 444 |
FinishReason: FinishReason(1), |
| 445 |
}, |
| 446 |
{ |
| 447 |
Index: 0, |
| 448 |
Content: &Content{Role: roleModel, Parts: []Part{Text("r1 i0")}}, |
| 449 |
FinishReason: FinishReason(2), |
| 450 |
}, |
| 451 |
}, |
| 452 |
PromptFeedback: &PromptFeedback{BlockReasonMessage: "br1"}, |
| 453 |
} |
| 454 |
r2 := &GenerateContentResponse{ |
| 455 |
Candidates: []*Candidate{ |
| 456 |
{ |
| 457 |
Index: 0, |
| 458 |
Content: &Content{Role: roleModel, Parts: []Part{Text(";r2 i0")}}, |
| 459 |
FinishReason: FinishReason(3), |
| 460 |
}, |
| 461 |
{ |
| 462 |
// ignored |
| 463 |
Index: 1, |
| 464 |
Content: &Content{Role: roleModel, Parts: []Part{Text(";r2 i1")}}, |
| 465 |
FinishReason: FinishReason(4), |
| 466 |
}, |
| 467 |
}, |
| 468 |
|
| 469 |
PromptFeedback: &PromptFeedback{BlockReasonMessage: "br2"}, |
| 470 |
} |
| 471 |
got := joinResponses(r1, r2) |
| 472 |
want := &GenerateContentResponse{ |
| 473 |
Candidates: []*Candidate{ |
| 474 |
{ |
| 475 |
Index: 2, |
| 476 |
Content: &Content{Role: roleModel, Parts: []Part{Text("r1 i2")}}, |
| 477 |
FinishReason: FinishReason(1), |
| 478 |
}, |
| 479 |
{ |
| 480 |
Index: 0, |
| 481 |
Content: &Content{Role: roleModel, Parts: []Part{Text("r1 i0;r2 i0")}}, |
| 482 |
FinishReason: FinishReason(3), |
| 483 |
}, |
| 484 |
}, |
| 485 |
PromptFeedback: &PromptFeedback{BlockReasonMessage: "br1"}, |
| 486 |
} |
| 487 |
if !reflect.DeepEqual(got, want) { |
| 488 |
t.Errorf("\ngot %+v\nwant %+v", got, want) |
| 489 |
} |
| 490 |
} |
| 491 |
|
| 492 |
func TestMergeTexts(t *testing.T) { |
| 493 |
for _, test := range []struct { |
| 494 |
in []Part |
| 495 |
want []Part |
| 496 |
}{ |
| 497 |
{ |
| 498 |
in: []Part{Text("a")}, |
| 499 |
want: []Part{Text("a")}, |
| 500 |
}, |
| 501 |
{ |
| 502 |
in: []Part{Text("a"), Text("b"), Text("c")}, |
| 503 |
want: []Part{Text("abc")}, |
| 504 |
}, |
| 505 |
{ |
| 506 |
in: []Part{Blob{"b1", nil}, Text("a"), Text("b"), Blob{"b2", nil}, Text("c")}, |
| 507 |
want: []Part{Blob{"b1", nil}, Text("ab"), Blob{"b2", nil}, Text("c")}, |
| 508 |
}, |
| 509 |
{ |
| 510 |
in: []Part{Text("a"), Text("b"), Blob{"b1", nil}, Text("c"), Text("d"), Blob{"b2", nil}}, |
| 511 |
want: []Part{Text("ab"), Blob{"b1", nil}, Text("cd"), Blob{"b2", nil}}, |
| 512 |
}, |
| 513 |
} { |
| 514 |
got := mergeTexts(test.in) |
| 515 |
if !reflect.DeepEqual(got, test.want) { |
| 516 |
t.Errorf("%+v:\ngot %+v\nwant %+v", test.in, got, test.want) |
| 517 |
} |
| 518 |
} |
| 519 |
} |
| 520 |
|
| 521 |
func checkMatch(t *testing.T, got string, wants ...string) { |
| 522 |
t.Helper() |
| 523 |
for _, want := range wants { |
| 524 |
re, err := regexp.Compile("(?i:" + want + ")") |
| 525 |
if err != nil { |
| 526 |
t.Fatal(err) |
| 527 |
} |
| 528 |
if !re.MatchString(got) { |
| 529 |
t.Errorf("\ngot %q\nwanted to match %q", got, want) |
| 530 |
} |
| 531 |
} |
| 532 |
} |
| 533 |
|
| 534 |
func responseString(resp *GenerateContentResponse) string { |
| 535 |
var b strings.Builder |
| 536 |
for i, cand := range resp.Candidates { |
| 537 |
if len(resp.Candidates) > 1 { |
| 538 |
fmt.Fprintf(&b, "%d:", i+1) |
| 539 |
} |
| 540 |
if cand.Content != nil { |
| 541 |
b.WriteString(contentString(cand.Content)) |
| 542 |
} |
| 543 |
} |
| 544 |
return b.String() |
| 545 |
} |
| 546 |
|
| 547 |
func contentString(c *Content) string { |
| 548 |
var b strings.Builder |
| 549 |
for i, part := range c.Parts { |
| 550 |
if i > 0 { |
| 551 |
fmt.Fprintf(&b, ";") |
| 552 |
} |
| 553 |
fmt.Fprintf(&b, "%v", part) |
| 554 |
} |
| 555 |
return strings.ReplaceAll(b.String(), "\n", " ") |
| 556 |
} |
| 557 |
|
| 558 |
func responsesString(t *testing.T, iter *GenerateContentResponseIterator) string { |
| 559 |
var lines []string |
| 560 |
for { |
| 561 |
resp, err := iter.Next() |
| 562 |
if err == iterator.Done { |
| 563 |
break |
| 564 |
} |
| 565 |
if err != nil { |
| 566 |
t.Fatal(err) |
| 567 |
} |
| 568 |
lines = append(lines, responseString(resp)) |
| 569 |
} |
| 570 |
return strings.Join(lines, "\n") |
| 571 |
} |
| 572 |
|
| 573 |
func all(iter *GenerateContentResponseIterator) ([]*GenerateContentResponse, error) { |
| 574 |
var rs []*GenerateContentResponse |
| 575 |
for { |
| 576 |
r, err := iter.Next() |
| 577 |
if err == iterator.Done { |
| 578 |
return rs, nil |
| 579 |
} |
| 580 |
if err != nil { |
| 581 |
return nil, err |
| 582 |
} |
| 583 |
rs = append(rs, r) |
| 584 |
} |
| 585 |
} |
| 586 |
|
| 587 |
func dump(w io.Writer, x any) { |
| 588 |
var err error |
| 589 |
printf := func(format string, args ...any) { |
| 590 |
if err == nil { |
| 591 |
_, err = fmt.Fprintf(w, format, args...) |
| 592 |
} |
| 593 |
} |
| 594 |
printValue(reflect.ValueOf(x), "", "", printf) |
| 595 |
if err != nil { |
| 596 |
log.Fatal(err) |
| 597 |
} |
| 598 |
} |
| 599 |
|
| 600 |
func printValue(v reflect.Value, indent, first string, printf func(string, ...any)) { |
| 601 |
switch v.Kind() { |
| 602 |
case reflect.Slice, reflect.Array, reflect.Map, reflect.Struct: |
| 603 |
printf("%s%s%s{\n", indent, first, v.Type()) |
| 604 |
indent1 := indent + " " |
| 605 |
switch v.Kind() { |
| 606 |
case reflect.Slice, reflect.Array: |
| 607 |
for i := 0; i < v.Len(); i++ { |
| 608 |
printValue(v.Index(i), indent1, fmt.Sprintf("[%d]: ", i), printf) |
| 609 |
} |
| 610 |
case reflect.Map: |
| 611 |
iter := v.MapRange() |
| 612 |
for iter.Next() { |
| 613 |
printValue(iter.Value(), indent1, fmt.Sprintf("%q: ", iter.Key()), printf) |
| 614 |
} |
| 615 |
case reflect.Struct: |
| 616 |
for _, sf := range reflect.VisibleFields(v.Type()) { |
| 617 |
vf := v.FieldByName(sf.Name) |
| 618 |
if !vf.IsZero() { |
| 619 |
printValue(vf, indent1, sf.Name+": ", printf) |
| 620 |
} |
| 621 |
} |
| 622 |
} |
| 623 |
printf("%s}\n", indent) |
| 624 |
case reflect.Pointer, reflect.Interface: |
| 625 |
printValue(v.Elem(), indent, first, printf) |
| 626 |
case reflect.String: |
| 627 |
printf("%s%s%q\n", indent, first, v) |
| 628 |
default: |
| 629 |
printf("%s%s%v\n", indent, first, v) |
| 630 |
} |
| 631 |
} |
| 632 |
|
| 633 |
func TestMatchString(t *testing.T) { |
| 634 |
for _, test := range []struct { |
| 635 |
re, in string |
| 636 |
}{ |
| 637 |
{"do not", "I do not have"}, |
| 638 |
{"(don't|do not) have", "I do not have"}, |
| 639 |
{"(don't|do not) have", "As an AI language model, I do not have physical needs"}, |
| 640 |
} { |
| 641 |
re := regexp.MustCompile(test.re) |
| 642 |
if !re.MatchString(test.in) { |
| 643 |
t.Errorf("%q doesn't match %q", test.re, test.in) |
| 644 |
} |
| 645 |
} |
| 646 |
} |
| 647 |
|
| 648 |
func TestTemperature(t *testing.T) { |
| 649 |
m := &GenerativeModel{} |
| 650 |
got := m.GenerationConfig.toProto().Temperature |
| 651 |
if got != nil { |
| 652 |
t.Errorf("got %v, want nil", got) |
| 653 |
} |
| 654 |
m.SetTemperature(0) |
| 655 |
got = m.GenerationConfig.toProto().Temperature |
| 656 |
if got == nil { |
| 657 |
t.Fatal("got nil") |
| 658 |
} |
| 659 |
if g := *got; g != 0 { |
| 660 |
t.Errorf("got %v, want 0", g) |
| 661 |
} |
| 662 |
} |
| 663 |
|
| 664 |
func TestIntFloatConversions(t *testing.T) { |
| 665 |
for n, test := range []struct { |
| 666 |
i *int32 |
| 667 |
f *float32 |
| 668 |
}{ |
| 669 |
{nil, nil}, |
| 670 |
{Ptr[int32](1), Ptr[float32](1)}, |
| 671 |
} { |
| 672 |
t.Run(fmt.Sprintf("int-to-float-%d", n), func(t *testing.T) { |
| 673 |
gotf := int32pToFloat32p(test.i) |
| 674 |
if !reflect.DeepEqual(gotf, test.f) { |
| 675 |
t.Errorf("got %v, want %v", gotf, test.f) |
| 676 |
} |
| 677 |
}) |
| 678 |
t.Run(fmt.Sprintf("float-to-int-%d", n), func(t *testing.T) { |
| 679 |
goti := float32pToInt32p(test.f) |
| 680 |
if !reflect.DeepEqual(goti, test.i) { |
| 681 |
t.Errorf("got %v, want %v", goti, test.i) |
| 682 |
} |
| 683 |
}) |
| 684 |
} |
| 685 |
goti := float32pToInt32p(Ptr[float32](1.5)) |
| 686 |
if !reflect.DeepEqual(goti, Ptr[int32](1)) { |
| 687 |
t.Errorf("got %v, want *1", goti) |
| 688 |
} |
| 689 |
} |
| 690 |
|
| 691 |
func TestInferFullModelName(t *testing.T) { |
| 692 |
for _, test := range []struct { |
| 693 |
name string |
| 694 |
want string |
| 695 |
}{ |
| 696 |
{"xyz", "projects/proj/locations/loc/publishers/google/models/xyz"}, |
| 697 |
{"models/abc", "projects/proj/locations/loc/publishers/google/models/abc"}, |
| 698 |
{"publishers/foo/xyz", "projects/proj/locations/loc/publishers/foo/xyz"}, |
| 699 |
{"x/y/z", "x/y/z"}, |
| 700 |
} { |
| 701 |
t.Run(test.name, func(t *testing.T) { |
| 702 |
got := inferFullModelName("proj", "loc", test.name) |
| 703 |
if got != test.want { |
| 704 |
t.Errorf("got %q, want %q", got, test.want) |
| 705 |
} |
| 706 |
}) |
| 707 |
} |
| 708 |
} |
| 709 |
|
| 710 |
func TestInferLocation(t *testing.T) { |
| 711 |
for _, test := range []struct { |
| 712 |
name string |
| 713 |
arg string |
| 714 |
cloudRegionEnv, cloudMlRegionEnv string |
| 715 |
want string |
| 716 |
}{ |
| 717 |
{"arg passed", "us-west4", "abc", "def", "us-west4"}, |
| 718 |
{"first env", "", "abc", "", "abc"}, |
| 719 |
{"second env", "", "", "klm", "klm"}, |
| 720 |
{"default", "", "", "", defaultLocation}, |
| 721 |
{"first env precedence", "", "101", "klm", "101"}, |
| 722 |
} { |
| 723 |
t.Run(test.name, func(t *testing.T) { |
| 724 |
t.Setenv("GOOGLE_CLOUD_REGION", test.cloudRegionEnv) |
| 725 |
t.Setenv("CLOUD_ML_REGION", test.cloudMlRegionEnv) |
| 726 |
got := inferLocation(test.arg) |
| 727 |
if got != test.want { |
| 728 |
t.Errorf("got %q, want %q", got, test.want) |
| 729 |
} |
| 730 |
}) |
| 731 |
} |
| 732 |
} |
| 733 |
|
| 734 |
func printResponse(resp *GenerateContentResponse) { |
| 735 |
for _, cand := range resp.Candidates { |
| 736 |
for _, part := range cand.Content.Parts { |
| 737 |
fmt.Println(part) |
| 738 |
} |
| 739 |
} |
| 740 |
fmt.Println("---") |
| 741 |
} |