-
Notifications
You must be signed in to change notification settings - Fork 2.9k
feat(genai): add tools samples #10147
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
Merged
msampathkumar
merged 8 commits into
GoogleCloudPlatform:main
from
jdomingr:genai-sdk-tool-samples
Sep 16, 2025
Merged
Changes from 2 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
8b75990
feat: add new GenAI tools samples
57d0cce
refactor: change some print statement in samples
65d28ef
refactor: introduce minor changes to improve consistency
dba9041
Improve comments in toolVais samples
42a6175
delete unnecessary line break
638f19a
refactor: change inputs order and improve comments in some samples
a5270d6
delete Vertex AI tool sample to take it to a new PR
96081ee
refactor(genai): use image directly in CodeExecWithTextLocalImages sa…
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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
85 changes: 85 additions & 0 deletions
85
genai/snippets/src/main/java/genai/tools/ToolsCodeExecWithText.java
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 | ||
| * | ||
| * 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 genai.tools; | ||
|
|
||
| // [START googlegenaisdk_tools_code_exec_with_txt] | ||
|
|
||
| import com.google.genai.Client; | ||
| import com.google.genai.types.GenerateContentConfig; | ||
| import com.google.genai.types.GenerateContentResponse; | ||
| import com.google.genai.types.HttpOptions; | ||
| import com.google.genai.types.Tool; | ||
| import com.google.genai.types.ToolCodeExecution; | ||
|
|
||
| public class ToolsCodeExecWithText { | ||
|
|
||
| public static void main(String[] args) { | ||
| // TODO(developer): Replace these variables before running the sample. | ||
| String modelId = "gemini-2.5-flash"; | ||
| generateContent(modelId); | ||
| } | ||
|
|
||
| // Generates text using the Code Execution tool | ||
| public static String generateContent(String modelId) { | ||
| // Initialize client that will be used to send requests. This client only needs to be created | ||
| // once, and can be reused for multiple requests. | ||
| try (Client client = | ||
| Client.builder() | ||
| .location("global") | ||
| .vertexAI(true) | ||
| .httpOptions(HttpOptions.builder().apiVersion("v1").build()) | ||
| .build()) { | ||
|
|
||
| // Create a config and set codeExecution tool | ||
| GenerateContentConfig contentConfig = | ||
| GenerateContentConfig.builder() | ||
| .tools(Tool.builder().codeExecution(ToolCodeExecution.builder().build()).build()) | ||
| .temperature(0.0F) | ||
| .build(); | ||
|
|
||
| GenerateContentResponse response = | ||
| client.models.generateContent( | ||
| modelId, | ||
| "Calculate 20th fibonacci number. Then find the nearest palindrome to it.", | ||
| contentConfig); | ||
|
|
||
| System.out.println("Code: \n" + response.executableCode()); | ||
| System.out.println("Outcome: \n" + response.codeExecutionResult()); | ||
| // Example response | ||
| // Code: | ||
| // def fibonacci(n): | ||
| // if n <= 0: | ||
| // return 0 | ||
| // elif n == 1: | ||
| // return 1 | ||
| // else: | ||
| // a, b = 1, 1 | ||
| // for _ in range(2, n): | ||
| // a, b = b, a + b | ||
| // return b | ||
| // | ||
| // fib_20 = fibonacci(20) | ||
| // print(f'{fib_20=}') | ||
| // | ||
| // Outcome: | ||
| // fib_20=6765 | ||
| return response.executableCode(); | ||
| } | ||
| } | ||
| } | ||
| // [END googlegenaisdk_tools_code_exec_with_txt] |
101 changes: 101 additions & 0 deletions
101
genai/snippets/src/main/java/genai/tools/ToolsCodeExecWithTextLocalImage.java
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,101 @@ | ||
| /* | ||
| * 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 genai.tools; | ||
|
|
||
| // [START googlegenaisdk_tools_code_exec_with_txt_local_img] | ||
|
|
||
| import com.google.genai.Client; | ||
| import com.google.genai.types.Content; | ||
| import com.google.genai.types.GenerateContentConfig; | ||
| import com.google.genai.types.GenerateContentResponse; | ||
| import com.google.genai.types.HttpOptions; | ||
| import com.google.genai.types.Part; | ||
| import com.google.genai.types.Tool; | ||
| import com.google.genai.types.ToolCodeExecution; | ||
| import java.io.IOException; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Paths; | ||
|
|
||
| public class ToolsCodeExecWithTextLocalImage { | ||
|
|
||
| public static void main(String[] args) throws IOException { | ||
| // TODO(developer): Replace these variables before running the sample. | ||
| String modelId = "gemini-2.5-flash"; | ||
| String localImagePath = "your-local-image.png"; | ||
| generateContent(modelId, localImagePath); | ||
| } | ||
|
|
||
| // Generates text using the Code Execution tool with text and image input | ||
| public static String generateContent(String modelId, String localImagePath) throws IOException { | ||
| // Initialize client that will be used to send requests. This client only needs to be created | ||
| // once, and can be reused for multiple requests. | ||
| try (Client client = | ||
| Client.builder() | ||
| .location("global") | ||
| .vertexAI(true) | ||
| .httpOptions(HttpOptions.builder().apiVersion("v1").build()) | ||
| .build()) { | ||
|
|
||
| String prompt = | ||
| "Run a simulation of the Monty Hall Problem with 1,000 trials.\n" | ||
| + "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?\n" | ||
| + " 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.\n" | ||
| + " Thank you!"; | ||
|
|
||
| // Read content from a local image | ||
| byte[] imageData = Files.readAllBytes(Paths.get(localImagePath)); | ||
|
|
||
| // Create a config and set codeExecution tool | ||
| GenerateContentConfig contentConfig = | ||
| GenerateContentConfig.builder() | ||
| .tools(Tool.builder().codeExecution(ToolCodeExecution.builder().build()).build()) | ||
| .temperature(0.0F) | ||
| .build(); | ||
|
|
||
| GenerateContentResponse response = | ||
| client.models.generateContent( | ||
| modelId, | ||
| Content.fromParts(Part.fromText(prompt), Part.fromBytes(imageData, "image/png")), | ||
| contentConfig); | ||
|
|
||
| System.out.println("Code: \n" + response.executableCode()); | ||
| System.out.println("Outcome: \n" + response.codeExecutionResult()); | ||
| // Example response | ||
| // Code: | ||
| // import random | ||
| // | ||
| // def run_monty_hall_trial(): | ||
| // doors = [0, 1, 2] # Represent doors as indices 0, 1, 2 | ||
| // | ||
| // # 1. Randomly place the car behind one door | ||
| // car_door = random.choice(doors) | ||
| // ... | ||
| // | ||
| // Outcome: | ||
| // Number of trials: 1000 | ||
| // Stick strategy wins: 327 (32.70%) | ||
| // Switch strategy wins: 673 (67.30%) | ||
| return response.executableCode(); | ||
| } | ||
| } | ||
| } | ||
| // [END googlegenaisdk_tools_code_exec_with_txt_local_img] |
63 changes: 63 additions & 0 deletions
63
genai/snippets/src/main/java/genai/tools/ToolsGoogleSearchWithText.java
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,63 @@ | ||
| /* | ||
| * 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 genai.tools; | ||
|
|
||
| // [START googlegenaisdk_tools_google_search_with_txt] | ||
|
|
||
| import com.google.genai.Client; | ||
| import com.google.genai.types.GenerateContentConfig; | ||
| import com.google.genai.types.GenerateContentResponse; | ||
| import com.google.genai.types.GoogleSearch; | ||
| import com.google.genai.types.HttpOptions; | ||
| import com.google.genai.types.Tool; | ||
|
|
||
| public class ToolsGoogleSearchWithText { | ||
|
|
||
| public static void main(String[] args) { | ||
| // TODO(developer): Replace these variables before running the sample. | ||
| String modelId = "gemini-2.5-flash"; | ||
| generateContent(modelId); | ||
| } | ||
|
|
||
| // Generates text with Google Search tool | ||
| public static String generateContent(String modelId) { | ||
| // Initialize client that will be used to send requests. This client only needs to be created | ||
| // once, and can be reused for multiple requests. | ||
| try (Client client = | ||
| Client.builder() | ||
| .location("global") | ||
| .vertexAI(true) | ||
| .httpOptions(HttpOptions.builder().apiVersion("v1").build()) | ||
| .build()) { | ||
|
|
||
| GenerateContentResponse response = | ||
| client.models.generateContent( | ||
| modelId, | ||
| "When is the next total solar eclipse in the United States?", | ||
| GenerateContentConfig.builder() | ||
| // set Google Search tool | ||
| .tools(Tool.builder().googleSearch(GoogleSearch.builder().build()).build()) | ||
| .build()); | ||
|
|
||
| System.out.print(response.text()); | ||
| // Example response: | ||
| // The next total solar eclipse in the United States will occur on... | ||
| return response.text(); | ||
| } | ||
| } | ||
| } | ||
| // [END googlegenaisdk_tools_google_search_with_txt] | ||
76 changes: 76 additions & 0 deletions
76
genai/snippets/src/main/java/genai/tools/ToolsVaisWithText.java
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,76 @@ | ||
| /* | ||
| * 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 genai.tools; | ||
|
|
||
| // [START googlegenaisdk_tools_vais_with_txt] | ||
|
|
||
| import com.google.genai.Client; | ||
| import com.google.genai.types.GenerateContentConfig; | ||
| import com.google.genai.types.GenerateContentResponse; | ||
| import com.google.genai.types.HttpOptions; | ||
| import com.google.genai.types.Retrieval; | ||
| import com.google.genai.types.Tool; | ||
| import com.google.genai.types.VertexAISearch; | ||
|
|
||
| public class ToolsVaisWithText { | ||
|
|
||
| public static void main(String[] args) { | ||
| // TODO(developer): Replace these variables before running the sample. | ||
| String modelId = "gemini-2.5-flash"; | ||
| // Load Data Store ID from Vertex AI Search | ||
| // E.g datastore = | ||
| // "projects/11111111/locations/global/collections/default_collection/dataStores/data-store-id" | ||
| String datastoreId = "your-datastore"; | ||
| generateContent(modelId, datastoreId); | ||
| } | ||
|
|
||
| // Generates text with Vertex AI Search tool | ||
| public static String generateContent(String modelId, String datastoreId) { | ||
| // Initialize client that will be used to send requests. This client only needs to be created | ||
| // once, and can be reused for multiple requests. | ||
| try (Client client = | ||
| Client.builder() | ||
| .location("global") | ||
| .vertexAI(true) | ||
| .httpOptions(HttpOptions.builder().apiVersion("v1").build()) | ||
| .build()) { | ||
|
|
||
| // Set the VertexAI Search tool and the datastore that the model can use to retrieve data from | ||
| Tool vaisSearchTool = | ||
| Tool.builder() | ||
| .retrieval( | ||
| Retrieval.builder() | ||
| .vertexAiSearch(VertexAISearch.builder().datastore(datastoreId).build()) | ||
| .build()) | ||
| .build(); | ||
|
|
||
| GenerateContentConfig config = | ||
| GenerateContentConfig.builder().tools(vaisSearchTool).build(); | ||
|
|
||
| GenerateContentResponse response = | ||
| client.models.generateContent( | ||
| modelId, "How do I make an appointment to renew my driver's license?", config); | ||
jdomingr marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| System.out.print(response.text()); | ||
| // Example response: | ||
| // The process for making an appointment to renew your driver's license varies depending | ||
| // on your location. To provide you with the most accurate instructions... | ||
| return response.text(); | ||
| } | ||
| } | ||
| } | ||
| // [END googlegenaisdk_tools_vais_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
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.