-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat(genai): Add samples for img and thinking generation+sdk update #5390
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
Open
cfloress
wants to merge
5
commits into
GoogleCloudPlatform:main
Choose a base branch
from
cfloress:genai-img-think-generation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+496
−3
Open
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
a56f344
genai: added img and thinking generation samples
cfloress 6b118f0
genai: PR comments
cfloress 2f31648
Merge branch 'main' into genai-img-think-generation
cfloress 750c71b
Merge branch 'main' into genai-img-think-generation
msampathkumar 21accc9
genai: model update
cfloress File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
// 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 image_generation | ||
|
||
import ( | ||
"bytes" | ||
"testing" | ||
|
||
"github.com/GoogleCloudPlatform/golang-samples/internal/testutil" | ||
) | ||
|
||
func TestImageGeneration(t *testing.T) { | ||
tc := testutil.SystemTest(t) | ||
|
||
t.Setenv("GOOGLE_GENAI_USE_VERTEXAI", "1") | ||
t.Setenv("GOOGLE_CLOUD_LOCATION", "global") | ||
t.Setenv("GOOGLE_CLOUD_PROJECT", tc.ProjectID) | ||
|
||
buf := new(bytes.Buffer) | ||
|
||
t.Run("generate mmflash locale aware image content with text", func(t *testing.T) { | ||
buf.Reset() | ||
err := generateMMFlashLocaleAwareWithText(buf) | ||
if err != nil { | ||
t.Fatalf("generateMMFlashLocaleAwareWithText failed: %v", err) | ||
} | ||
|
||
output := buf.String() | ||
if output == "" { | ||
t.Error("expected non-empty output, got empty") | ||
} | ||
}) | ||
|
||
t.Run("generate mmflash multiple images with text", func(t *testing.T) { | ||
buf.Reset() | ||
err := generateMMFlashMultipleImgsWithText(buf) | ||
if err != nil { | ||
t.Fatalf("generateMMFlashMultipleImgsWithText failed: %v", err) | ||
} | ||
|
||
output := buf.String() | ||
if output == "" { | ||
t.Error("expected non-empty output, got empty") | ||
} | ||
}) | ||
|
||
t.Run("virtual try-on generation", func(t *testing.T) { | ||
buf.Reset() | ||
err := generateImgVirtualTryOnWithTextImg(buf) | ||
if err != nil { | ||
t.Fatalf("generateImgVirtualTryOnWithTextImg failed: %v", err) | ||
} | ||
|
||
output := buf.String() | ||
if output == "" { | ||
t.Error("expected non-empty output, got empty") | ||
} | ||
}) | ||
} |
85 changes: 85 additions & 0 deletions
85
genai/image_generation/imggen_mmflash_locale_aware_with_txt.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
// 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 image_generation shows how to use the GenAI SDK to generate images and text. | ||
package image_generation | ||
|
||
// [START googlegenaisdk_imggen_mmflash_locale_aware_with_txt] | ||
import ( | ||
"context" | ||
"fmt" | ||
"io" | ||
"os" | ||
"path/filepath" | ||
|
||
"google.golang.org/genai" | ||
) | ||
|
||
// generateMMFlashLocaleAwareWithText demonstrates how to generate an image with locale awareness. | ||
func generateMMFlashLocaleAwareWithText(w io.Writer) error { | ||
ctx := context.Background() | ||
|
||
client, err := genai.NewClient(ctx, &genai.ClientConfig{ | ||
HTTPOptions: genai.HTTPOptions{APIVersion: "v1"}, | ||
}) | ||
if err != nil { | ||
return fmt.Errorf("failed to create genai client: %w", err) | ||
} | ||
|
||
modelName := "gemini-2.5-flash-image-preview" | ||
prompt := "Generate a photo of a breakfast meal." | ||
contents := []*genai.Content{ | ||
{ | ||
Parts: []*genai.Part{ | ||
{Text: prompt}, | ||
}, | ||
Role: "user", | ||
}, | ||
} | ||
|
||
resp, err := client.Models.GenerateContent(ctx, | ||
modelName, | ||
contents, | ||
&genai.GenerateContentConfig{ | ||
ResponseModalities: []string{ | ||
string(genai.ModalityText), | ||
string(genai.ModalityImage), | ||
}, | ||
}, | ||
) | ||
if err != nil { | ||
return fmt.Errorf("generate content failed: %w", err) | ||
} | ||
|
||
outputPath := filepath.Join("testdata", "example-breakfast-meal.png") | ||
|
||
for _, part := range resp.Candidates[0].Content.Parts { | ||
switch { | ||
case part.Text != "": | ||
fmt.Fprintln(w, part.Text) | ||
case part.InlineData != nil: | ||
if err := os.WriteFile(outputPath, part.InlineData.Data, 0o644); err != nil { | ||
return fmt.Errorf("failed to save generated image: %w", err) | ||
} | ||
} | ||
} | ||
fmt.Fprintln(w, outputPath) | ||
|
||
// Example response: | ||
// Here is a photo of a delicious breakfast meal for you! ... | ||
|
||
return nil | ||
} | ||
|
||
// [END googlegenaisdk_imggen_mmflash_locale_aware_with_txt] |
98 changes: 98 additions & 0 deletions
98
genai/image_generation/imggen_mmflash_multiple_imgs_with_txt.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
// 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 image_generation shows how to use the GenAI SDK to generate images and text. | ||
package image_generation | ||
|
||
// [START googlegenaisdk_imggen_mmflash_multiple_imgs_with_txt] | ||
import ( | ||
"context" | ||
"fmt" | ||
"io" | ||
"os" | ||
"path/filepath" | ||
|
||
"google.golang.org/genai" | ||
) | ||
|
||
// generateMMFlashMultipleImgsWithText demonstrates how to generate multiple images with text. | ||
func generateMMFlashMultipleImgsWithText(w io.Writer) error { | ||
ctx := context.Background() | ||
|
||
client, err := genai.NewClient(ctx, &genai.ClientConfig{ | ||
HTTPOptions: genai.HTTPOptions{APIVersion: "v1"}, | ||
}) | ||
if err != nil { | ||
return fmt.Errorf("failed to create genai client: %w", err) | ||
} | ||
|
||
modelName := "gemini-2.5-flash-image-preview" | ||
prompt := "Generate 3 images a cat sitting on a chair." | ||
contents := []*genai.Content{ | ||
{ | ||
Parts: []*genai.Part{ | ||
{Text: prompt}, | ||
}, | ||
Role: "user", | ||
}, | ||
} | ||
|
||
resp, err := client.Models.GenerateContent(ctx, | ||
modelName, | ||
contents, | ||
&genai.GenerateContentConfig{ | ||
ResponseModalities: []string{ | ||
string(genai.ModalityText), | ||
string(genai.ModalityImage), | ||
}, | ||
}, | ||
) | ||
if err != nil { | ||
return fmt.Errorf("generate content failed: %w", err) | ||
} | ||
|
||
outputDir := filepath.Join("testdata") | ||
|
||
imageCounter := 1 | ||
for _, part := range resp.Candidates[0].Content.Parts { | ||
switch { | ||
case part.Text != "": | ||
fmt.Fprintln(w, part.Text) | ||
case part.InlineData != nil: | ||
filename := filepath.Join(outputDir, fmt.Sprintf("example-cats-0%d.png", imageCounter)) | ||
if err := os.WriteFile(filename, part.InlineData.Data, 0o644); err != nil { | ||
return fmt.Errorf("failed to save generated image: %w", err) | ||
} | ||
fmt.Fprintln(w, filename) | ||
imageCounter++ | ||
} | ||
} | ||
cfloress marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// Example response: | ||
// Image 1: A fluffy calico cat with striking green eyes is perched elegantly on a vintage wooden | ||
// chair with a woven seat. Sunlight streams through a nearby window, casting soft shadows and | ||
// highlighting the cat's fur. | ||
// # | ||
// Image 2: A sleek black cat with intense yellow eyes is sitting upright on a modern, minimalist | ||
// white chair. The background is a plain grey wall, putting the focus entirely on the feline's | ||
// graceful posture. | ||
// # | ||
// Image 3: A ginger tabby cat with playful amber eyes is comfortably curled up asleep on a plush, | ||
// oversized armchair upholstered in a soft, floral fabric. A corner of a cozy living room with a | ||
// warm lamp in the background can be seen. | ||
|
||
return nil | ||
} | ||
|
||
// [END googlegenaisdk_imggen_mmflash_multiple_imgs_with_txt] |
100 changes: 100 additions & 0 deletions
100
genai/image_generation/imggen_virtual_try_on_with_txt_img.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
// 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 image_generation shows how to use the GenAI SDK to generate images and text. | ||
package image_generation | ||
|
||
// [START googlegenaisdk_imggen_virtual_try_on_with_txt_img] | ||
import ( | ||
"context" | ||
"fmt" | ||
"io" | ||
"os" | ||
"path/filepath" | ||
|
||
"google.golang.org/genai" | ||
) | ||
|
||
// generateImgVirtualTryOnWithTextImg demonstrates how to apply a product image to a person image. | ||
func generateImgVirtualTryOnWithTextImg(w io.Writer) error { | ||
ctx := context.Background() | ||
|
||
client, err := genai.NewClient(ctx, &genai.ClientConfig{ | ||
HTTPOptions: genai.HTTPOptions{APIVersion: "v1"}, | ||
}) | ||
if err != nil { | ||
return fmt.Errorf("failed to create genai client: %w", err) | ||
} | ||
|
||
modelName := "virtual-try-on-preview-08-04" | ||
|
||
// Load local person image | ||
personBytes, err := os.ReadFile("testdata/man.png") | ||
if err != nil { | ||
return fmt.Errorf("failed to read person image: %w", err) | ||
} | ||
personImage := &genai.Image{ | ||
ImageBytes: personBytes, | ||
MIMEType: "image/png", | ||
} | ||
|
||
// Load local product image | ||
productBytes, err := os.ReadFile("testdata/sweater.jpg") | ||
if err != nil { | ||
return fmt.Errorf("failed to read product image: %w", err) | ||
} | ||
productImage := &genai.ProductImage{ | ||
ProductImage: &genai.Image{ | ||
ImageBytes: productBytes, | ||
MIMEType: "image/jpeg", | ||
}, | ||
} | ||
|
||
resp, err := client.Models.RecontextImage(ctx, | ||
modelName, | ||
&genai.RecontextImageSource{ | ||
PersonImage: personImage, | ||
ProductImages: []*genai.ProductImage{productImage}, | ||
}, nil, | ||
) | ||
if err != nil { | ||
return fmt.Errorf("recontext image failed: %w", err) | ||
} | ||
|
||
// Ensure we have a generated image and save it | ||
if len(resp.GeneratedImages) == 0 || resp.GeneratedImages[0].Image == nil { | ||
return fmt.Errorf("no image was generated") | ||
} | ||
|
||
// TODO(developer): Update below lines | ||
path := "testdata" | ||
outputFile := "man_in_sweater.png" | ||
|
||
// Save output | ||
outputPath := filepath.Join(path, outputFile) | ||
cfloress marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
if err := os.WriteFile(outputPath, resp.GeneratedImages[0].Image.ImageBytes, 0o644); err != nil { | ||
return fmt.Errorf("failed to save generated image: %w", err) | ||
} | ||
|
||
fmt.Fprintf(w, "Created output image using %d bytes\n", len(resp.GeneratedImages[0].Image.ImageBytes)) | ||
fmt.Fprintln(w, outputPath) | ||
|
||
// Example response: | ||
// Created output image using 1636301 bytes ... | ||
|
||
return nil | ||
} | ||
|
||
// [END googlegenaisdk_imggen_virtual_try_on_with_txt_img] |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.