Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* 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 GenerateContentConfig 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]
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 the local image
byte[] imageData = Files.readAllBytes(Paths.get(localImagePath));

// Create a GenerateContentConfig 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.fromBytes(imageData, "image/png"), Part.fromText(prompt)),
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]
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* 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()) {

// Create a GenerateContentConfig and set Google Search tool
GenerateContentConfig contentConfig =
GenerateContentConfig.builder()
.tools(Tool.builder().googleSearch(GoogleSearch.builder().build()).build())
.build();

GenerateContentResponse response =
client.models.generateContent(
modelId, "When is the next total solar eclipse in the United States?", contentConfig);

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]
27 changes: 27 additions & 0 deletions genai/snippets/src/test/java/genai/tools/ToolsIT.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import static com.google.common.truth.Truth.assertWithMessage;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import org.junit.After;
import org.junit.Before;
Expand All @@ -32,6 +33,7 @@
public class ToolsIT {

private static final String GEMINI_FLASH = "gemini-2.5-flash";
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
private ByteArrayOutputStream bout;
private PrintStream out;

Expand All @@ -57,6 +59,7 @@ public void setUp() {
@After
public void tearDown() {
System.setOut(null);
bout.reset();
}

@Test
Expand All @@ -79,4 +82,28 @@ public void testGenerateContentWithFunctionDescription() {
assertThat(response).contains("copies_sold=350000");
assertThat(response).contains("album_name=Echoes of the Night");
}

@Test
public void testToolsCodeExecWithText() {
String response = ToolsCodeExecWithText.generateContent(GEMINI_FLASH);
assertThat(response).isNotEmpty();
assertThat(bout.toString()).contains("Code:");
assertThat(bout.toString()).contains("Outcome:");
}

@Test
public void testToolsCodeExecWithTextLocalImage() throws IOException {
String localImagePath = "resources/640px-Monty_open_door.svg.png";
String response = ToolsCodeExecWithTextLocalImage.generateContent(GEMINI_FLASH, localImagePath);
assertThat(response).isNotEmpty();
assertThat(bout.toString()).contains("Code:");
assertThat(bout.toString()).contains("Outcome:");
}

@Test
public void testToolsGoogleSearchWithText() {
String response = ToolsGoogleSearchWithText.generateContent(GEMINI_FLASH);
assertThat(response).isNotEmpty();
}

}