-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat(genai): Add samples for Tools and Text-generation local images and video #5378
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
20
commits into
GoogleCloudPlatform:main
Choose a base branch
from
cfloress:genai-local-media-content-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.
+319
−0
Open
Changes from 1 commit
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
3768857
genai: Add samples for Tools and Text-generation local images and video
cfloress 90d0887
genai: PR comments
cfloress 6f27726
genai: fix conflict
cfloress bb71db6
Merge branch 'main' into genai-local-media-content-generation
cfloress d4ca468
Merge branch 'main' into genai-local-media-content-generation
cfloress 40f3d80
Merge branch 'main' into genai-local-media-content-generation
cfloress 9bf4d51
Merge branch 'main' of github.com:GoogleCloudPlatform/golang-samples …
cfloress 3035ce2
Merge branch 'genai-local-media-content-generation' of github.com:cfl…
cfloress b8771d4
Merge branch 'main' into genai-local-media-content-generation
msampathkumar 1f617e4
Merge branch 'main' into genai-local-media-content-generation
cfloress 84c1652
Merge branch 'main' into genai-local-media-content-generation
msampathkumar 62549cd
Merge branch 'main' into genai-local-media-content-generation
cfloress 429f280
Merge branch 'genai-local-media-content-generation' of github.com:cfl…
cfloress a3e92f1
genai: PR comments
cfloress 445507d
Merge branch 'main' into genai-local-media-content-generation
msampathkumar ad878cd
Merge branch 'main' into genai-local-media-content-generation
msampathkumar 506d424
Merge branch 'main' into genai-local-media-content-generation
msampathkumar 3fa3440
Merge branch 'main' into genai-local-media-content-generation
msampathkumar cd35a7b
Merge branch 'main' into genai-local-media-content-generation
cfloress f7c2928
Merge branch 'main' into genai-local-media-content-generation
msampathkumar 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
Binary file not shown.
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
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,88 @@ | ||
// 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 text_generation shows examples of generating text using the GenAI SDK. | ||
package text_generation | ||
|
||
// [START googlegenaisdk_textgen_with_local_video] | ||
import ( | ||
"context" | ||
"fmt" | ||
"io" | ||
"os" | ||
|
||
genai "google.golang.org/genai" | ||
) | ||
|
||
// generateWithLocalVideo shows how to generate text using a local video input. | ||
func generateWithLocalVideo(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) | ||
} | ||
|
||
// Read local video file content | ||
data, err := os.ReadFile("testdata/describe_video_content.mp4") | ||
if err != nil { | ||
return fmt.Errorf("failed to read local video: %w", err) | ||
} | ||
|
||
modelName := "gemini-2.5-flash" | ||
contents := []*genai.Content{ | ||
{ | ||
Role: "user", | ||
Parts: []*genai.Part{ | ||
{Text: `Analyze the provided local video file, including its audio. | ||
Summarize the main points of the video concisely. | ||
Create a chapter breakdown with timestamps for key sections or topics discussed.`}, | ||
{InlineData: &genai.Blob{ | ||
MIMEType: "video/mp4", | ||
Data: data, | ||
}}, | ||
}, | ||
}, | ||
} | ||
|
||
resp, err := client.Models.GenerateContent(ctx, modelName, contents, nil) | ||
if err != nil { | ||
return fmt.Errorf("failed to generate content: %w", err) | ||
} | ||
|
||
respText := resp.Text() | ||
fmt.Fprintln(w, respText) | ||
|
||
// Example response: | ||
// The video features a male climber engaged in lead rock climbing at an indoor gym. He is shown ascending a vertical wall adorned with various colored holds, demonstrating fluid movements and proper technique. During his ascent, he clips his rope into a quickdraw for safety and manages the rope for continued climbing. The video is silent. | ||
// | ||
// **Summary of Main Points:** | ||
// | ||
// The video shows an indoor rock climber, equipped with a harness and chalk bag, efficiently ascending a climbing wall. He skillfully clips... | ||
// | ||
// **Chapter Breakdown** | ||
// | ||
// * **0:00 - Beginning of Ascent:** The climber starts his ascent, moving gracefully between holds. | ||
//* **0:01 - Clipping the Rope into a Quickdraw:** The climber pauses to clip his safety rope into a quickdraw, securing his position. | ||
//* **0:03 - Continued Climbing and Technique Display:** The climber resumes his upward movement, demonstrating his climbing technique and body control. | ||
//* **0:08 - Rope Management / Preparing for Next Moves:** The climber adjusts the rope, taking up slack, and surveys the next section of the climb. | ||
//* **0:13 - Video End:** The video concludes with the climber still in the process of ascending the wall. | ||
// ... | ||
|
||
return nil | ||
} | ||
|
||
// [END googlegenaisdk_textgen_with_local_video] |
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,95 @@ | ||
// 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 text_generation shows examples of generating text using the GenAI SDK. | ||
package text_generation | ||
|
||
// [START googlegenaisdk_textgen_with_multi_local_img] | ||
import ( | ||
"context" | ||
"fmt" | ||
"io" | ||
"os" | ||
|
||
genai "google.golang.org/genai" | ||
) | ||
|
||
// generateWithMultiLocalImages shows how to generate text using multiple local image inputs. | ||
func generateWithMultiLocalImages(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) | ||
} | ||
|
||
// Read local image files | ||
image1, err := os.ReadFile("testdata/latte.jpg") | ||
if err != nil { | ||
return fmt.Errorf("failed to read image1: %w", err) | ||
} | ||
image2, err := os.ReadFile("testdata/scones.jpg") | ||
if err != nil { | ||
return fmt.Errorf("failed to read image2: %w", err) | ||
} | ||
|
||
modelName := "gemini-2.5-flash" | ||
contents := []*genai.Content{ | ||
{ | ||
Role: "user", | ||
Parts: []*genai.Part{ | ||
{Text: "Generate a list of all the objects contained in both images."}, | ||
{InlineData: &genai.Blob{ | ||
MIMEType: "image/jpeg", | ||
Data: image1, | ||
}}, | ||
{InlineData: &genai.Blob{ | ||
MIMEType: "image/jpeg", | ||
Data: image2, | ||
}}, | ||
}, | ||
}, | ||
} | ||
|
||
// Call the model | ||
resp, err := client.Models.GenerateContent(ctx, modelName, contents, nil) | ||
if err != nil { | ||
return fmt.Errorf("failed to generate content: %w", err) | ||
} | ||
|
||
fmt.Fprintln(w, resp.Text()) | ||
|
||
// Example response: | ||
// Here is a list of all the distinct objects found in both images: | ||
// 1. **Coffee** (in mugs/cups; one is clearly a latte with heart art, others are also coffee/latte) | ||
// 2. **Mug(s)/Cup(s)** (yellow in the top image, white in the bottom image) | ||
// 3. **Cake** (sliced, in the top image) | ||
// 4. **Plate** (white, under the cake slice in the top image) | ||
// 5. **Fork** (partially visible on the plate in the top image) | ||
// 6. **Scones/Biscuits** (blueberry, in the bottom image) | ||
// 7. **Blueberries** (scattered and in a bowl in the bottom image) | ||
// 8. **Bowl** (small, dark, holding blueberries in the bottom image) | ||
// 9. **Spoon** (silver, with "LET'S JAM" inscription, in the bottom image) | ||
// 10. **Flowers** (peonies, in the bottom image) | ||
// 11. **Leaves** (green, possibly mint, in the bottom image) | ||
// 12. **Paper** (parchment or wax paper, in the bottom image) | ||
// 13. **Table/Surface** (wooden in the top image, textured/painted in the bottom image) | ||
// ... | ||
|
||
return nil | ||
} | ||
|
||
// [END googlegenaisdk_textgen_with_multi_local_img] |
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,107 @@ | ||
// 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 tools shows examples of various tools that Gemini model can use to generate text. | ||
package tools | ||
|
||
// [START googlegenaisdk_tools_code_exec_with_txt_local_img] | ||
import ( | ||
"context" | ||
"fmt" | ||
"io" | ||
"os" | ||
|
||
genai "google.golang.org/genai" | ||
) | ||
|
||
// generateWithLocalImgAndCodeExec shows how to combine a local image, a text prompt, | ||
// and enable the code execution tool in a request. | ||
func generateWithLocalImgAndCodeExec(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) | ||
} | ||
|
||
// Read local image | ||
imgBytes, err := os.ReadFile("testdata/640px-Monty_open_door.svg.png") | ||
if err != nil { | ||
return fmt.Errorf("failed to read image: %w", err) | ||
} | ||
|
||
// Define the prompt | ||
prompt := ` | ||
Run a simulation of the Monty Hall Problem with 1,000 trials. | ||
Here's how this works as a reminder. In the Monty Hall Problem, you're on a game | ||
show with three doors. Behind one is a car, and behind the others are goats. You | ||
pick a door. The host, who knows what's behind the doors, opens a different door | ||
to reveal a goat. Should you switch to the remaining unopened door? | ||
The answer has always been a little difficult for me to understand when people | ||
solve it with math - so please run a simulation with Python to show me what the | ||
best strategy is. | ||
Thank you! | ||
` | ||
cfloress marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
// Enable the code execution tool | ||
tools := []*genai.Tool{ | ||
{CodeExecution: &genai.ToolCodeExecution{}}, | ||
} | ||
|
||
// Build contents with image + text | ||
contents := []*genai.Content{ | ||
{ | ||
Role: "user", | ||
Parts: []*genai.Part{ | ||
{InlineData: &genai.Blob{ | ||
MIMEType: "image/png", | ||
Data: imgBytes, | ||
}}, | ||
{Text: prompt}, | ||
}, | ||
}, | ||
} | ||
|
||
// Call the model | ||
resp, err := client.Models.GenerateContent(ctx, "gemini-2.5-flash", contents, &genai.GenerateContentConfig{ | ||
Tools: tools, | ||
Temperature: genai.Ptr(float32(0.0)), | ||
}) | ||
if err != nil { | ||
return fmt.Errorf("failed to generate content: %w", err) | ||
} | ||
|
||
// Print result | ||
fmt.Fprintln(w, "# Code:") | ||
fmt.Fprintln(w, resp.ExecutableCode()) | ||
fmt.Fprintln(w, "# Outcome:") | ||
fmt.Fprintln(w, resp.CodeExecutionResult()) | ||
|
||
// Example output: | ||
// # Code: | ||
// import random | ||
// | ||
// def run_monty_hall_trial(strategy): | ||
// """ | ||
// Runs a single trial of the Monty Hall problem. | ||
// | ||
// Args: | ||
// strategy (str): 'stick' or 'switch' | ||
|
||
return nil | ||
} | ||
|
||
// [END googlegenaisdk_tools_code_exec_with_txt_local_img] |
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
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.