Skip to content

Commit 5dee860

Browse files
CadillacBurgess1Valeriy-Burlakatelpirionmsampathkumar
authored
feat(genai sdk): code samples (#5268)
* feat(genai sdk): generate text content from text prompt * feat: update genai sdk version to 0.2.0 * feat: standardize error messages * feat: text generation: generate from mute video * feat: add http params to client init * feat: text generation: generate from video w. sound * feat: text generation: generate from audio input * feat: text generation: generate an audio transcript * update test desc * wip: batch predict is unavailable in 0.2.0 * feat: text generation from YT video input * leave out wip for batch predict (not supporte by the sdk yet) * feat: text generation: generate from local video input * feat(genaisdk): text generation w. txt inputs and configs * remove phase-shifted test * add test input to index * chore(genai sdk): update sdk version * chore(genai sdk): update sdk version * chore(genai sdk): update sdk version * chore: migrate */test_data to */testdata to comply with the 'badfiles' test * chore: migrate */test_data to */testdata to comply with the 'badfiles' test * feat(genai sdk): text generation: generate using text and image inputs * feat(genai sdk): generate text using tools * feat(genai sdk): controlled text generation * feat: generate with google search * feat(genai sdk): count tokens: obtain usage metadata from model response * feat: count tokens when using text prompt * feat: count tokens with text and video inputs * feat: compute with text input * feat(genai sdk): content cache: create and update * feat(genai sdk): content caching * feat(genai sdk): text gen: batch 1 * chore: rename to match py samples naming convention * chore: rename to match py samples naming convention * chore: rename to match py samples naming convention * chore: rename to match py samples naming convention * chore: rename to match py samples naming convention * chore: update genai sdk version * update version * go tidy * update mod and sum * testing file * update testing file * update testing * update test file * update testing file * update testing * adding testing png * adding testing file * adding testing file * update header * tidy * updating testing * update test * updating files * remove old samples * removing examples * update file * update file * tidy * rerunning pipeline * update test file --------- Co-authored-by: Valeriy Burlaka <[email protected]> Co-authored-by: Eric Schmidt <[email protected]> Co-authored-by: Sampath Kumar <[email protected]>
1 parent 41f0779 commit 5dee860

33 files changed

+2315
-8
lines changed

Diff for: genai/content_cache/content_cache_test.go

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// Copyright 2025 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 content_cache
16+
17+
import (
18+
"bytes"
19+
"fmt"
20+
"strings"
21+
"testing"
22+
23+
"github.com/GoogleCloudPlatform/golang-samples/internal/testutil"
24+
)
25+
26+
func TestContentCaching(t *testing.T) {
27+
tc := testutil.SystemTest(t)
28+
29+
t.Setenv("GOOGLE_GENAI_USE_VERTEXAI", "1")
30+
t.Setenv("GOOGLE_CLOUD_LOCATION", "us-central1")
31+
t.Setenv("GOOGLE_CLOUD_PROJECT", tc.ProjectID)
32+
33+
buf := new(bytes.Buffer)
34+
35+
// 1) Create a content cache.
36+
// The name of the cache resource created in this step will be used in the next test steps.
37+
cacheName, err := createContentCache(buf)
38+
if err != nil {
39+
t.Fatalf("createContentCache: %v", err.Error())
40+
}
41+
42+
// 2) Update the expiration time of the content cache.
43+
err = updateContentCache(buf, cacheName)
44+
if err != nil {
45+
t.Errorf("updateContentCache: %v", err.Error())
46+
}
47+
48+
// 3) Use cached content with a text prompt.
49+
err = useContentCacheWithTxt(buf, cacheName)
50+
if err != nil {
51+
t.Errorf("useContentCacheWithTxt: %v", err.Error())
52+
}
53+
54+
// 4) Delete the content cache.
55+
buf.Reset()
56+
err = deleteContentCache(buf, cacheName)
57+
if err != nil {
58+
t.Errorf("deleteContentCache: %v", err.Error())
59+
}
60+
61+
exp := fmt.Sprintf("Deleted cache %q", cacheName)
62+
act := buf.String()
63+
if !strings.Contains(act, exp) {
64+
t.Errorf("deleteContentCache: got %q, want %q", act, exp)
65+
}
66+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
// Copyright 2025 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+
// https://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 content_cache shows examples of using content caching with the GenAI SDK.
16+
package content_cache
17+
18+
// [START googlegenaisdk_contentcache_create_with_txt_gcs_pdf]
19+
import (
20+
"context"
21+
"encoding/json"
22+
"fmt"
23+
"io"
24+
25+
genai "google.golang.org/genai"
26+
)
27+
28+
// createContentCache shows how to create a content cache with an expiration parameter.
29+
func createContentCache(w io.Writer) (string, error) {
30+
ctx := context.Background()
31+
32+
client, err := genai.NewClient(ctx, &genai.ClientConfig{
33+
HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta1"},
34+
})
35+
if err != nil {
36+
return "", fmt.Errorf("failed to create genai client: %w", err)
37+
}
38+
39+
modelName := "gemini-2.0-flash-001"
40+
41+
systemInstruction := "You are an expert researcher. You always stick to the facts " +
42+
"in the sources provided, and never make up new facts. " +
43+
"Now look at these research papers, and answer the following questions."
44+
45+
cacheContents := []*genai.Content{
46+
{
47+
Parts: []*genai.Part{
48+
{FileData: &genai.FileData{
49+
FileURI: "gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",
50+
MIMEType: "application/pdf",
51+
}},
52+
{FileData: &genai.FileData{
53+
FileURI: "gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",
54+
MIMEType: "application/pdf",
55+
}},
56+
},
57+
Role: "user",
58+
},
59+
}
60+
config := &genai.CreateCachedContentConfig{
61+
Contents: cacheContents,
62+
SystemInstruction: &genai.Content{
63+
Parts: []*genai.Part{
64+
{Text: systemInstruction},
65+
},
66+
},
67+
DisplayName: "example-cache",
68+
TTL: "86400s",
69+
}
70+
71+
res, err := client.Caches.Create(ctx, modelName, config)
72+
if err != nil {
73+
return "", fmt.Errorf("failed to create content cache: %w", err)
74+
}
75+
76+
cachedContent, err := json.MarshalIndent(res, "", " ")
77+
if err != nil {
78+
return "", fmt.Errorf("failed to marshal cache info: %w", err)
79+
}
80+
81+
// See the documentation: https://pkg.go.dev/google.golang.org/genai#CachedContent
82+
fmt.Fprintln(w, string(cachedContent))
83+
84+
// Example response:
85+
// {
86+
// "name": "projects/111111111111/locations/us-central1/cachedContents/1111111111111111111",
87+
// "displayName": "example-cache",
88+
// "model": "projects/111111111111/locations/us-central1/publishers/google/models/gemini-1.5-pro-002",
89+
// "createTime": "2025-02-18T15:05:08.29468Z",
90+
// "updateTime": "2025-02-18T15:05:08.29468Z",
91+
// "expireTime": "2025-02-19T15:05:08.280828Z",
92+
// "usageMetadata": {
93+
// "imageCount": 167,
94+
// "textCount": 153,
95+
// "totalTokenCount": 43125
96+
// }
97+
// }
98+
99+
return res.Name, nil
100+
}
101+
102+
// [END googlegenaisdk_contentcache_create_with_txt_gcs_pdf]

Diff for: genai/content_cache/contentcache_delete.go

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Copyright 2025 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+
// https://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 content_cache shows examples of using content caching with the GenAI SDK.
16+
package content_cache
17+
18+
// [START googlegenaisdk_contentcache_update]
19+
import (
20+
"context"
21+
"fmt"
22+
"io"
23+
24+
genai "google.golang.org/genai"
25+
)
26+
27+
// deleteContentCache shows how to delete content cache.
28+
func deleteContentCache(w io.Writer, cacheName string) error {
29+
ctx := context.Background()
30+
31+
client, err := genai.NewClient(ctx, &genai.ClientConfig{
32+
HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta1"},
33+
})
34+
if err != nil {
35+
return fmt.Errorf("failed to create genai client: %w", err)
36+
}
37+
38+
_, err = client.Caches.Delete(ctx, cacheName, &genai.DeleteCachedContentConfig{})
39+
if err != nil {
40+
return fmt.Errorf("failed to delete content cache: %w", err)
41+
}
42+
43+
fmt.Fprintf(w, "Deleted cache %q\n", cacheName)
44+
45+
// Example response:
46+
// Deleted cache "projects/111111111111/locations/us-central1/cachedContents/1111111111111111111"
47+
48+
return nil
49+
}
50+
51+
// [END googlegenaisdk_contentcache_update]

Diff for: genai/content_cache/contentcache_update.go

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// Copyright 2025 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+
// https://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 content_cache shows examples of using content caching with the GenAI SDK.
16+
package content_cache
17+
18+
// [START googlegenaisdk_contentcache_update]
19+
import (
20+
"context"
21+
"fmt"
22+
"io"
23+
"time"
24+
25+
genai "google.golang.org/genai"
26+
)
27+
28+
// updateContentCache shows how to update content cache expiration time.
29+
func updateContentCache(w io.Writer, cacheName string) error {
30+
ctx := context.Background()
31+
32+
client, err := genai.NewClient(ctx, &genai.ClientConfig{
33+
HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta1"},
34+
})
35+
if err != nil {
36+
return fmt.Errorf("failed to create genai client: %w", err)
37+
}
38+
39+
// Update expire time using TTL
40+
resp, err := client.Caches.Update(ctx, cacheName, &genai.UpdateCachedContentConfig{
41+
TTL: "36000s",
42+
})
43+
if err != nil {
44+
return fmt.Errorf("failed to update content cache exp. time with TTL: %w", err)
45+
}
46+
47+
fmt.Fprintf(w, "Cache expires in: %s\n", time.Until(*resp.ExpireTime))
48+
// Example response:
49+
// Cache expires in: 10h0m0.005875s
50+
51+
// Update expire time using specific time stamp
52+
inSevenDays := time.Now().Add(7 * 24 * time.Hour)
53+
resp, err = client.Caches.Update(ctx, cacheName, &genai.UpdateCachedContentConfig{
54+
ExpireTime: &inSevenDays,
55+
})
56+
if err != nil {
57+
return fmt.Errorf("failed to update content cache expire time: %w", err)
58+
}
59+
60+
fmt.Fprintf(w, "Cache expires in: %s\n", time.Until(*resp.ExpireTime))
61+
// Example response:
62+
// Cache expires in: 167h59m59.80327s
63+
64+
return nil
65+
}
66+
67+
// [END googlegenaisdk_contentcache_update]

Diff for: genai/content_cache/contentcache_use_with_txt.go

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// Copyright 2025 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+
// https://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 content_cache shows examples of using content caching with the GenAI SDK.
16+
package content_cache
17+
18+
// [START googlegenaisdk_contentcache_use_with_txt]
19+
import (
20+
"context"
21+
"fmt"
22+
"io"
23+
24+
genai "google.golang.org/genai"
25+
)
26+
27+
// useContentCacheWithTxt shows how to use content cache to generate text content.
28+
func useContentCacheWithTxt(w io.Writer, cacheName string) error {
29+
ctx := context.Background()
30+
31+
client, err := genai.NewClient(ctx, &genai.ClientConfig{
32+
HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta1"},
33+
})
34+
if err != nil {
35+
return fmt.Errorf("failed to create genai client: %w", err)
36+
}
37+
38+
resp, err := client.Models.GenerateContent(ctx,
39+
"gemini-2.0-flash-001",
40+
genai.Text("Summarize the pdfs"),
41+
&genai.GenerateContentConfig{
42+
CachedContent: cacheName,
43+
},
44+
)
45+
if err != nil {
46+
return fmt.Errorf("failed to use content cache to generate content: %w", err)
47+
}
48+
49+
respText, err := resp.Text()
50+
if err != nil {
51+
return fmt.Errorf("failed to convert model response to text: %w", err)
52+
}
53+
fmt.Fprintln(w, respText)
54+
55+
// Example response:
56+
// The provided research paper introduces Gemini 1.5 Pro, a multimodal model capable of recalling
57+
// and reasoning over information from very long contexts (up to 10 million tokens). Key findings include:
58+
//
59+
// * **Long Context Performance:**
60+
// ...
61+
62+
return nil
63+
}
64+
65+
// [END googlegenaisdk_contentcache_use_with_txt]

0 commit comments

Comments
 (0)