-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat(genai): Add samples for image generation #5386
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
14
commits into
GoogleCloudPlatform:main
Choose a base branch
from
cfloress:genai-image-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.
Open
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
d8a7b3f
genai: added image generation samples
cfloress 34e18a5
Merge branch 'main' of github.com:GoogleCloudPlatform/golang-samples …
cfloress 1dfd291
genai: added imggen_mmflash_txt_and_img_with_txt sample
cfloress 65254ce
genai: PR comments
cfloress 00d3175
Merge branch 'main' into genai-image-generation
cfloress 8370f8d
Merge branch 'main' of github.com:GoogleCloudPlatform/golang-samples …
cfloress b6c6108
genai: PR test fixed, changed us-central1 to globan in gc location
cfloress 843623a
Merge branch 'genai-image-generation' of github.com:cfloress/golang-s…
cfloress 6716a92
Merge branch 'main' into genai-image-generation
msampathkumar 0cbbf79
Merge branch 'main' into genai-image-generation
msampathkumar f7d35a5
Merge branch 'main' into genai-image-generation
cfloress 551f9bc
Merge branch 'main' into genai-image-generation
cfloress 748e9a1
Merge branch 'main' into genai-image-generation
cfloress 10ac765
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
// 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 multimodal flash content with text and image", func(t *testing.T) { | ||
buf.Reset() | ||
err := generateMMFlashWithText(buf) | ||
if err != nil { | ||
t.Fatalf("generateMMFlashWithText failed: %v", err) | ||
} | ||
|
||
output := buf.String() | ||
if output == "" { | ||
t.Error("expected non-empty output, got empty") | ||
} | ||
}) | ||
|
||
t.Run("generate mmflash text and image recipe", func(t *testing.T) { | ||
buf.Reset() | ||
err := generateMMFlashTxtImgWithText(buf) | ||
if err != nil { | ||
t.Fatalf("generateMMFlashTxtImgWithText failed: %v", err) | ||
} | ||
|
||
output := buf.String() | ||
if output == "" { | ||
t.Error("expected non-empty output, got empty") | ||
} | ||
}) | ||
} |
105 changes: 105 additions & 0 deletions
105
genai/image_generation/imggen_mmflash_txt_img_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,105 @@ | ||
// 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_txt_and_img_with_txt] | ||
import ( | ||
"context" | ||
"fmt" | ||
"io" | ||
"os" | ||
"path/filepath" | ||
|
||
"google.golang.org/genai" | ||
) | ||
|
||
// generateMMFlashTxtImgWithText demonstrates how to generate an illustrated recipe | ||
// combining text and image outputs into a markdown file. | ||
func generateMMFlashTxtImgWithText(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" | ||
contents := []*genai.Content{ | ||
{ | ||
Parts: []*genai.Part{ | ||
{Text: "Generate an illustrated recipe for a paella. " + | ||
"Create images to go alongside the text as you generate the recipe."}, | ||
}, | ||
Role: "user", | ||
}, | ||
} | ||
|
||
resp, err := client.Models.GenerateContent(ctx, | ||
modelName, | ||
contents, | ||
&genai.GenerateContentConfig{ | ||
ResponseModalities: []string{ | ||
string(genai.ModalityText), | ||
string(genai.ModalityImage), | ||
}, | ||
CandidateCount: int32(1), | ||
}, | ||
) | ||
if err != nil { | ||
return fmt.Errorf("failed to generate content: %w", err) | ||
} | ||
|
||
if len(resp.Candidates) == 0 || resp.Candidates[0].Content == nil { | ||
return fmt.Errorf("no candidates returned") | ||
} | ||
|
||
outputFolder := "testdata" | ||
|
||
// Create the markdown file | ||
mdFile := filepath.Join(outputFolder, "paella-recipe.md") | ||
fp, err := os.Create(mdFile) | ||
if err != nil { | ||
return fmt.Errorf("failed to create markdown file: %w", err) | ||
} | ||
defer fp.Close() | ||
|
||
for i, part := range resp.Candidates[0].Content.Parts { | ||
if part.Text != "" { | ||
if _, err := fp.WriteString(part.Text); err != nil { | ||
return fmt.Errorf("failed to write text: %w", err) | ||
} | ||
} else if part.InlineData != nil { | ||
imgFile := filepath.Join(outputFolder, fmt.Sprintf("example-image-%d.png", i+1)) | ||
if err := os.WriteFile(imgFile, part.InlineData.Data, 0644); err != nil { | ||
return fmt.Errorf("failed to save image: %w", err) | ||
} | ||
if _, err := fp.WriteString(fmt.Sprintf("", filepath.Base(imgFile))); err != nil { | ||
return fmt.Errorf("failed to write image reference: %w", err) | ||
} | ||
} | ||
} | ||
|
||
fmt.Fprintln(w, mdFile) | ||
|
||
// Example response: | ||
// A markdown page for a Paella recipe (`paella-recipe.md`) has been generated. | ||
// It includes detailed steps and several images illustrating the cooking process. | ||
return nil | ||
} | ||
|
||
// [END googlegenaisdk_imggen_mmflash_txt_and_img_with_txt] |
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,92 @@ | ||
// 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_with_txt] | ||
import ( | ||
"context" | ||
"fmt" | ||
"io" | ||
"os" | ||
|
||
"google.golang.org/genai" | ||
) | ||
|
||
// generateMMFlashWithText demonstrates how to generate both text and image outputs. | ||
func generateMMFlashWithText(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" | ||
contents := []*genai.Content{ | ||
{ | ||
Parts: []*genai.Part{ | ||
{Text: "Generate an image of the Eiffel tower with fireworks in the background."}, | ||
}, | ||
Role: "user", | ||
}, | ||
} | ||
|
||
resp, err := client.Models.GenerateContent(ctx, | ||
modelName, | ||
contents, | ||
&genai.GenerateContentConfig{ | ||
ResponseModalities: []string{ | ||
string(genai.ModalityText), | ||
string(genai.ModalityImage), | ||
}, | ||
CandidateCount: int32(1), | ||
SafetySettings: []*genai.SafetySetting{ | ||
{Method: genai.HarmBlockMethodProbability}, | ||
{Category: genai.HarmCategoryDangerousContent}, | ||
{Threshold: genai.HarmBlockThresholdBlockMediumAndAbove}, | ||
}, | ||
}, | ||
) | ||
if err != nil { | ||
return fmt.Errorf("failed to generate content: %w", err) | ||
} | ||
|
||
if len(resp.Candidates) == 0 || resp.Candidates[0].Content == nil { | ||
return fmt.Errorf("no candidates returned") | ||
} | ||
var fileName string | ||
for _, part := range resp.Candidates[0].Content.Parts { | ||
if part.Text != "" { | ||
fmt.Fprintln(w, part.Text) | ||
} else if part.InlineData != nil { | ||
fileName = "testdata/example-image-eiffel-tower.png" | ||
if err := os.WriteFile(fileName, part.InlineData.Data, 0o644); err != nil { | ||
return fmt.Errorf("failed to save image: %w", err) | ||
} | ||
cfloress marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} | ||
fmt.Fprintln(w, fileName) | ||
|
||
// Example response: | ||
// I will generate an image of the Eiffel Tower at night, with a vibrant display of | ||
// colorful fireworks exploding in the dark sky behind it. | ||
// .... | ||
return nil | ||
} | ||
|
||
// [END googlegenaisdk_imggen_mmflash_with_txt] |
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.
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.
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,44 @@ | ||
Let's get cooking! Here's an illustrated recipe for a delicious paella: | ||
|
||
## Traditional Spanish Paella | ||
|
||
Paella is a classic Spanish dish, known for its vibrant colors and rich flavors. While there are many variations, this recipe will guide you through making a traditional chicken and seafood paella. | ||
|
||
### Ingredients: | ||
|
||
* 2 tablespoons olive oil | ||
* 1 lb boneless, skinless chicken thighs, cut into 1-inch pieces | ||
* 1 lb shrimp, peeled and deveined | ||
* 1 cup chopped chorizo (optional) | ||
* 1 large onion, chopped | ||
* 2 cloves garlic, minced | ||
* 1 red bell pepper, chopped | ||
* 1 (14.5 ounce) can diced tomatoes, undrained | ||
* 1 teaspoon smoked paprika | ||
* 1/2 teaspoon saffron threads, crushed and steeped in 1/4 cup warm water | ||
* 2 cups Bomba rice (or other short-grain rice) | ||
* 4 cups chicken broth, warmed | ||
* 1/2 cup frozen peas | ||
* 1/4 cup chopped fresh parsley | ||
* Lemon wedges, for serving | ||
* Salt and freshly ground black pepper to taste | ||
|
||
### Equipment: | ||
|
||
* Large paella pan (or a large, shallow, oven-safe pan) | ||
* Wooden spoon | ||
|
||
### Instructions: | ||
|
||
**Step 1: Prepare Your Ingredients** | ||
|
||
Before you start cooking, it's helpful to have all your ingredients prepped and ready to go. Chop your chicken, onion, bell pepper, and mince your garlic. Don't forget to steep your saffron threads! | ||
**Step 2: Sauté the Chicken and Chorizo** | ||
|
||
Heat the olive oil in your paella pan over medium-high heat. Add the chicken pieces and cook until browned on all sides. If using, add the chorizo and cook until lightly crisped. Remove the chicken and chorizo from the pan and set aside, leaving any drippings in the pan. | ||
|
||
**Step 3: Cook the Aromatics** | ||
|
||
Add the chopped onion and bell pepper to the pan and cook until softened, about 5-7 minutes. Stir in the minced garlic and cook for another minute until fragrant. | ||
|
||
 |
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.