Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(genai sdk): code samples #5178

Open
wants to merge 67 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
67 commits
Select commit Hold shift + click to select a range
52c8510
feat(genai sdk): generate text content from text prompt
Valeriy-Burlaka Feb 5, 2025
c0f7370
feat: update genai sdk version to 0.2.0
Valeriy-Burlaka Feb 6, 2025
2a80e13
feat: standardize error messages
Valeriy-Burlaka Feb 6, 2025
a8e5b52
feat: text generation: generate from mute video
Valeriy-Burlaka Feb 6, 2025
35b0f4e
feat: add http params to client init
Valeriy-Burlaka Feb 6, 2025
9b1521d
feat: text generation: generate from video w. sound
Valeriy-Burlaka Feb 6, 2025
be6270d
feat: text generation: generate from audio input
Valeriy-Burlaka Feb 6, 2025
9fa6588
feat: text generation: generate an audio transcript
Valeriy-Burlaka Feb 6, 2025
479f60b
Merge branch 'main' into vb/genaisdk-samples-1.0
Valeriy-Burlaka Feb 6, 2025
b0e8e48
Merge branch 'main' into vb/genaisdk-textgen-batch4
Valeriy-Burlaka Feb 6, 2025
3611ef9
update test desc
Valeriy-Burlaka Feb 6, 2025
8cf2bc1
wip: batch predict is unavailable in 0.2.0
Valeriy-Burlaka Feb 7, 2025
2bf288c
feat: text generation from YT video input
Valeriy-Burlaka Feb 10, 2025
73d5ba1
leave out wip for batch predict (not supporte by the sdk yet)
Valeriy-Burlaka Feb 10, 2025
753d081
feat: text generation: generate from local video input
Valeriy-Burlaka Feb 11, 2025
71816aa
Merge branch 'main' into vb/genaisdk-samples-1.0
Valeriy-Burlaka Feb 11, 2025
ed9cac4
feat(genaisdk): text generation w. txt inputs and configs
Valeriy-Burlaka Feb 11, 2025
5a3cc5c
Merge branch 'main' into vb/genaisdk-textgen-batch4
Valeriy-Burlaka Feb 11, 2025
6aa28a1
remove phase-shifted test
Valeriy-Burlaka Feb 11, 2025
b8ec2b2
add test input to index
Valeriy-Burlaka Feb 11, 2025
b1acec1
merge main into vb/genaisdk-textgen-batch2
Valeriy-Burlaka Feb 13, 2025
2879a62
chore(genai sdk): update sdk version
Valeriy-Burlaka Feb 13, 2025
b3b047f
merge main into vb/genaisdk-textgen-batch4
Valeriy-Burlaka Feb 13, 2025
92b906c
chore(genai sdk): update sdk version
Valeriy-Burlaka Feb 13, 2025
649bb42
merge main into vb/genaisdk-textgen-batch5
Valeriy-Burlaka Feb 13, 2025
ff57f83
chore(genai sdk): update sdk version
Valeriy-Burlaka Feb 13, 2025
efba59d
chore: migrate */test_data to */testdata to comply with the 'badfiles…
Valeriy-Burlaka Feb 13, 2025
1268be7
chore: migrate */test_data to */testdata to comply with the 'badfiles…
Valeriy-Burlaka Feb 13, 2025
ed9bfb7
feat(genai sdk): text generation: generate using text and image inputs
Valeriy-Burlaka Feb 14, 2025
95b7f07
feat(genai sdk): generate text using tools
Valeriy-Burlaka Feb 14, 2025
038aa5c
feat(genai sdk): controlled text generation
Valeriy-Burlaka Feb 14, 2025
e18f849
merge main into vb/genaisdk-textgen-batch2
Valeriy-Burlaka Feb 17, 2025
f71dd5d
merge main into vb/genaisdk-textgen-batch3
Valeriy-Burlaka Feb 17, 2025
c733f15
merge main into vb/genaisdk-textgen-batch4
Valeriy-Burlaka Feb 17, 2025
46f43d0
merge main into vb/genaisdk-textgen-batch5
Valeriy-Burlaka Feb 17, 2025
c91b8b1
merge main into vb/genaisdk-textgen-batch6
Valeriy-Burlaka Feb 17, 2025
519e0f3
merge main into vb/genaisdk-textgen-batch7
Valeriy-Burlaka Feb 17, 2025
b8e91b4
feat: generate with google search
Valeriy-Burlaka Feb 17, 2025
b283893
feat(genai sdk): count tokens: obtain usage metadata from model response
Valeriy-Burlaka Feb 17, 2025
ecf52f9
feat: count tokens when using text prompt
Valeriy-Burlaka Feb 17, 2025
7ec09d3
feat: count tokens with text and video inputs
Valeriy-Burlaka Feb 17, 2025
656840a
feat: compute with text input
Valeriy-Burlaka Feb 17, 2025
780a6b2
feat(genai sdk): content cache: create and update
Valeriy-Burlaka Feb 18, 2025
d2ad6d4
feat(genai sdk): content caching
Valeriy-Burlaka Feb 21, 2025
243e41f
merge main into vb/genaisdk-textgen-batch2
Valeriy-Burlaka Feb 21, 2025
537b686
merge main into vb/genaisdk-textgen-batch3
Valeriy-Burlaka Feb 21, 2025
6a5ad18
merge main into vb/genaisdk-textgen-batch4
Valeriy-Burlaka Feb 21, 2025
2a03259
merge main into vb/genaisdk-textgen-batch5
Valeriy-Burlaka Feb 21, 2025
1c1aed2
merge main into vb/genaisdk-textgen-batch6
Valeriy-Burlaka Feb 21, 2025
7c7f50b
merge main into vb/genaisdk-textgen-batch7
Valeriy-Burlaka Feb 21, 2025
2d210c0
merge main into vb/genaisdk-textgen-batch8
Valeriy-Burlaka Feb 21, 2025
2590f57
merge main into vb/genaisdk-textgen-batch9
Valeriy-Burlaka Feb 21, 2025
ea42343
feat(genai sdk): text gen: batch 1
Valeriy-Burlaka Feb 25, 2025
387bcb4
feat(genai sdk): text gen: batch 2
Valeriy-Burlaka Feb 25, 2025
a069229
feat(genai sdk): text gen: batch 3
Valeriy-Burlaka Feb 25, 2025
0d51e6a
feat(genai sdk): text gen: batch 4
Valeriy-Burlaka Feb 25, 2025
a14983b
feat(genai sdk): text gen: batch 5
Valeriy-Burlaka Feb 25, 2025
f81e849
chore: rename to match py samples naming convention
Valeriy-Burlaka Feb 25, 2025
6413348
Merge branch 'vb/genaisdk-textgen-batch6' into vb/genaisdk-all-samples
Valeriy-Burlaka Feb 25, 2025
864b60d
chore: rename to match py samples naming convention
Valeriy-Burlaka Feb 25, 2025
43fc1c0
Merge branch 'vb/genaisdk-textgen-batch7' into vb/genaisdk-all-samples
Valeriy-Burlaka Feb 25, 2025
2a7573a
chore: rename to match py samples naming convention
Valeriy-Burlaka Feb 25, 2025
52cbe2e
Merge branch 'vb/genaisdk-textgen-batch8' into vb/genaisdk-all-samples
Valeriy-Burlaka Feb 25, 2025
1249c05
chore: rename to match py samples naming convention
Valeriy-Burlaka Feb 25, 2025
ddb013e
Merge branch 'vb/genaisdk-textgen-batch9' into vb/genaisdk-all-samples
Valeriy-Burlaka Feb 25, 2025
b406517
chore: rename to match py samples naming convention
Valeriy-Burlaka Feb 25, 2025
0b9fc18
chore: update genai sdk version
Valeriy-Burlaka Feb 25, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions genai/content_cache/content_cache_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package content_cache

import (
"bytes"
"fmt"
"strings"
"testing"

"github.com/GoogleCloudPlatform/golang-samples/internal/testutil"
)

func TestContentCaching(t *testing.T) {
tc := testutil.SystemTest(t)

t.Setenv("GOOGLE_GENAI_USE_VERTEXAI", "1")
t.Setenv("GOOGLE_CLOUD_LOCATION", "us-central1")
t.Setenv("GOOGLE_CLOUD_PROJECT", tc.ProjectID)

buf := new(bytes.Buffer)

// 1) Create a content cache.
// The name of the cache resource created in this step will be used in the next test steps.
cacheName, err := createContentCache(buf)
if err != nil {
t.Fatalf("createContentCache: %v", err.Error())
}

// 2) Update the expiration time of the content cache.
err = updateContentCache(buf, cacheName)
if err != nil {
t.Errorf("updateContentCache: %v", err.Error())
}

// 3) Use cached content with a text prompt.
err = useContentCacheWithTxt(buf, cacheName)
if err != nil {
t.Errorf("useContentCacheWithTxt: %v", err.Error())
}

// 4) Delete the content cache.
buf.Reset()
err = deleteContentCache(buf, cacheName)
if err != nil {
t.Errorf("deleteContentCache: %v", err.Error())
}

exp := fmt.Sprintf("Deleted cache %q", cacheName)
act := buf.String()
if !strings.Contains(act, exp) {
t.Errorf("deleteContentCache: got %q, want %q", act, exp)
}
}
102 changes: 102 additions & 0 deletions genai/content_cache/contentcache_create_with_txt_gcs_pdf.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package content_cache shows examples of using content caching with the GenAI SDK.
package content_cache

// [START googlegenaisdk_contentcache_create_with_txt_gcs_pdf]
import (
"context"
"encoding/json"
"fmt"
"io"

genai "google.golang.org/genai"
)

// createContentCache shows how to create a content cache with an expiration parameter.
func createContentCache(w io.Writer) (string, error) {
ctx := context.Background()

client, err := genai.NewClient(ctx, &genai.ClientConfig{
HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta1"},
})
if err != nil {
return "", fmt.Errorf("failed to create genai client: %w", err)
}

modelName := "gemini-1.5-pro-002"

systemInstruction := "You are an expert researcher. You always stick to the facts " +
"in the sources provided, and never make up new facts. " +
"Now look at these research papers, and answer the following questions."

cacheContents := []*genai.Content{
{
Parts: []*genai.Part{
{FileData: &genai.FileData{
FileURI: "gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",
MIMEType: "application/pdf",
}},
{FileData: &genai.FileData{
FileURI: "gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",
MIMEType: "application/pdf",
}},
},
Role: "user",
},
}
config := &genai.CreateCachedContentConfig{
Contents: cacheContents,
SystemInstruction: &genai.Content{
Parts: []*genai.Part{
{Text: systemInstruction},
},
},
DisplayName: "example-cache",
TTL: "86400s",
}

res, err := client.Caches.Create(ctx, modelName, config)
if err != nil {
return "", fmt.Errorf("failed to create content cache: %w", err)
}

cachedContent, err := json.MarshalIndent(res, "", " ")
if err != nil {
return "", fmt.Errorf("failed to marshal cache info: %w", err)
}

// See the documentation: https://pkg.go.dev/google.golang.org/genai#CachedContent
fmt.Fprintln(w, string(cachedContent))

// Example response:
// {
// "name": "projects/111111111111/locations/us-central1/cachedContents/1111111111111111111",
// "displayName": "example-cache",
// "model": "projects/111111111111/locations/us-central1/publishers/google/models/gemini-1.5-pro-002",
// "createTime": "2025-02-18T15:05:08.29468Z",
// "updateTime": "2025-02-18T15:05:08.29468Z",
// "expireTime": "2025-02-19T15:05:08.280828Z",
// "usageMetadata": {
// "imageCount": 167,
// "textCount": 153,
// "totalTokenCount": 43125
// }
// }

return res.Name, nil
}

// [END googlegenaisdk_contentcache_create_with_txt_gcs_pdf]
51 changes: 51 additions & 0 deletions genai/content_cache/contentcache_delete.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package content_cache shows examples of using content caching with the GenAI SDK.
package content_cache

// [START googlegenaisdk_contentcache_update]
import (
"context"
"fmt"
"io"

genai "google.golang.org/genai"
)

// deleteContentCache shows how to delete content cache.
func deleteContentCache(w io.Writer, cacheName string) error {
ctx := context.Background()

client, err := genai.NewClient(ctx, &genai.ClientConfig{
HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta1"},
})
if err != nil {
return fmt.Errorf("failed to create genai client: %w", err)
}

_, err = client.Caches.Delete(ctx, cacheName, &genai.DeleteCachedContentConfig{})
if err != nil {
return fmt.Errorf("failed to delete content cache: %w", err)
}

fmt.Fprintf(w, "Deleted cache %q\n", cacheName)

// Example response:
// Deleted cache "projects/111111111111/locations/us-central1/cachedContents/1111111111111111111"

return nil
}

// [END googlegenaisdk_contentcache_update]
67 changes: 67 additions & 0 deletions genai/content_cache/contentcache_update.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package content_cache shows examples of using content caching with the GenAI SDK.
package content_cache

// [START googlegenaisdk_contentcache_update]
import (
"context"
"fmt"
"io"
"time"

genai "google.golang.org/genai"
)

// updateContentCache shows how to update content cache expiration time.
func updateContentCache(w io.Writer, cacheName string) error {
ctx := context.Background()

client, err := genai.NewClient(ctx, &genai.ClientConfig{
HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta1"},
})
if err != nil {
return fmt.Errorf("failed to create genai client: %w", err)
}

// Update expire time using TTL
resp, err := client.Caches.Update(ctx, cacheName, &genai.UpdateCachedContentConfig{
TTL: "36000s",
})
if err != nil {
return fmt.Errorf("failed to update content cache exp. time with TTL: %w", err)
}

fmt.Fprintf(w, "Cache expires in: %s\n", time.Until(*resp.ExpireTime))
// Example response:
// Cache expires in: 10h0m0.005875s

// Update expire time using specific time stamp
inSevenDays := time.Now().Add(7 * 24 * time.Hour)
resp, err = client.Caches.Update(ctx, cacheName, &genai.UpdateCachedContentConfig{
ExpireTime: &inSevenDays,
})
if err != nil {
return fmt.Errorf("failed to update content cache expire time: %w", err)
}

fmt.Fprintf(w, "Cache expires in: %s\n", time.Until(*resp.ExpireTime))
// Example response:
// Cache expires in: 167h59m59.80327s

return nil
}

// [END googlegenaisdk_contentcache_update]
65 changes: 65 additions & 0 deletions genai/content_cache/contentcache_use_with_txt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package content_cache shows examples of using content caching with the GenAI SDK.
package content_cache

// [START googlegenaisdk_contentcache_use_with_txt]
import (
"context"
"fmt"
"io"

genai "google.golang.org/genai"
)

// useContentCacheWithTxt shows how to use content cache to generate text content.
func useContentCacheWithTxt(w io.Writer, cacheName string) error {
ctx := context.Background()

client, err := genai.NewClient(ctx, &genai.ClientConfig{
HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta1"},
})
if err != nil {
return fmt.Errorf("failed to create genai client: %w", err)
}

resp, err := client.Models.GenerateContent(ctx,
"gemini-1.5-pro-002",
genai.Text("Summarize the pdfs"),
&genai.GenerateContentConfig{
CachedContent: cacheName,
},
)
if err != nil {
return fmt.Errorf("failed to use content cache to generate content: %w", err)
}

respText, err := resp.Text()
if err != nil {
return fmt.Errorf("failed to convert model response to text: %w", err)
}
fmt.Fprintln(w, respText)

// Example response:
// The provided research paper introduces Gemini 1.5 Pro, a multimodal model capable of recalling
// and reasoning over information from very long contexts (up to 10 million tokens). Key findings include:
//
// * **Long Context Performance:**
// ...

return nil
}

// [END googlegenaisdk_contentcache_use_with_txt]
Loading
Loading