diff --git a/genai/snippets/resources/640px-Monty_open_door.svg.png b/genai/snippets/resources/640px-Monty_open_door.svg.png new file mode 100644 index 00000000000..90f83375e36 Binary files /dev/null and b/genai/snippets/resources/640px-Monty_open_door.svg.png differ diff --git a/genai/snippets/src/main/java/genai/tools/ToolsCodeExecWithText.java b/genai/snippets/src/main/java/genai/tools/ToolsCodeExecWithText.java new file mode 100644 index 00000000000..ce6d106c13c --- /dev/null +++ b/genai/snippets/src/main/java/genai/tools/ToolsCodeExecWithText.java @@ -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] \ No newline at end of file diff --git a/genai/snippets/src/main/java/genai/tools/ToolsCodeExecWithTextLocalImage.java b/genai/snippets/src/main/java/genai/tools/ToolsCodeExecWithTextLocalImage.java new file mode 100644 index 00000000000..6647889888a --- /dev/null +++ b/genai/snippets/src/main/java/genai/tools/ToolsCodeExecWithTextLocalImage.java @@ -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"; + generateContent(modelId); + } + + // Generates text using the Code Execution tool with text and image input + public static String generateContent(String modelId) 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 + // Image source: https://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/Monty_open_door.svg/640px-Monty_open_door.svg.png + byte[] imageData = Files.readAllBytes(Paths.get("resources/640px-Monty_open_door.svg.png")); + + // 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] \ No newline at end of file diff --git a/genai/snippets/src/main/java/genai/tools/ToolsGoogleSearchWithText.java b/genai/snippets/src/main/java/genai/tools/ToolsGoogleSearchWithText.java new file mode 100644 index 00000000000..7c053dbd1e7 --- /dev/null +++ b/genai/snippets/src/main/java/genai/tools/ToolsGoogleSearchWithText.java @@ -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] \ No newline at end of file diff --git a/genai/snippets/src/test/java/genai/tools/ToolsIT.java b/genai/snippets/src/test/java/genai/tools/ToolsIT.java index b18fb4a9bc1..dbe421694f1 100644 --- a/genai/snippets/src/test/java/genai/tools/ToolsIT.java +++ b/genai/snippets/src/test/java/genai/tools/ToolsIT.java @@ -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; @@ -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; @@ -57,6 +59,7 @@ public void setUp() { @After public void tearDown() { System.setOut(null); + bout.reset(); } @Test @@ -79,4 +82,27 @@ 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 response = ToolsCodeExecWithTextLocalImage.generateContent(GEMINI_FLASH); + 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(); + } + +} \ No newline at end of file