Skip to content

Commit 0a127da

Browse files
jdomingrJuan Dominguez
andauthored
feat(genai): add tools samples (#10147)
* feat: add new GenAI tools samples * refactor: change some print statement in samples * refactor: introduce minor changes to improve consistency * Improve comments in toolVais samples * delete unnecessary line break * refactor: change inputs order and improve comments in some samples * delete Vertex AI tool sample to take it to a new PR * refactor(genai): use image directly in CodeExecWithTextLocalImages sample and add image source --------- Co-authored-by: Juan Dominguez <jdomin@softserveinc.com>
1 parent 2a77e77 commit 0a127da

File tree

5 files changed

+276
-1
lines changed

5 files changed

+276
-1
lines changed
24.1 KB
Loading
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/*
2+
* Copyright 2025 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package genai.tools;
18+
19+
// [START googlegenaisdk_tools_code_exec_with_txt]
20+
21+
import com.google.genai.Client;
22+
import com.google.genai.types.GenerateContentConfig;
23+
import com.google.genai.types.GenerateContentResponse;
24+
import com.google.genai.types.HttpOptions;
25+
import com.google.genai.types.Tool;
26+
import com.google.genai.types.ToolCodeExecution;
27+
28+
public class ToolsCodeExecWithText {
29+
30+
public static void main(String[] args) {
31+
// TODO(developer): Replace these variables before running the sample.
32+
String modelId = "gemini-2.5-flash";
33+
generateContent(modelId);
34+
}
35+
36+
// Generates text using the Code Execution tool
37+
public static String generateContent(String modelId) {
38+
// Initialize client that will be used to send requests. This client only needs to be created
39+
// once, and can be reused for multiple requests.
40+
try (Client client =
41+
Client.builder()
42+
.location("global")
43+
.vertexAI(true)
44+
.httpOptions(HttpOptions.builder().apiVersion("v1").build())
45+
.build()) {
46+
47+
// Create a GenerateContentConfig and set codeExecution tool
48+
GenerateContentConfig contentConfig =
49+
GenerateContentConfig.builder()
50+
.tools(Tool.builder().codeExecution(ToolCodeExecution.builder().build()).build())
51+
.temperature(0.0F)
52+
.build();
53+
54+
GenerateContentResponse response =
55+
client.models.generateContent(
56+
modelId,
57+
"Calculate 20th fibonacci number. Then find the nearest palindrome to it.",
58+
contentConfig);
59+
60+
System.out.println("Code: \n" + response.executableCode());
61+
System.out.println("Outcome: \n" + response.codeExecutionResult());
62+
// Example response
63+
// Code:
64+
// def fibonacci(n):
65+
// if n <= 0:
66+
// return 0
67+
// elif n == 1:
68+
// return 1
69+
// else:
70+
// a, b = 1, 1
71+
// for _ in range(2, n):
72+
// a, b = b, a + b
73+
// return b
74+
//
75+
// fib_20 = fibonacci(20)
76+
// print(f'{fib_20=}')
77+
//
78+
// Outcome:
79+
// fib_20=6765
80+
return response.executableCode();
81+
}
82+
}
83+
}
84+
// [END googlegenaisdk_tools_code_exec_with_txt]
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/*
2+
* Copyright 2025 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package genai.tools;
18+
19+
// [START googlegenaisdk_tools_code_exec_with_txt_local_img]
20+
21+
import com.google.genai.Client;
22+
import com.google.genai.types.Content;
23+
import com.google.genai.types.GenerateContentConfig;
24+
import com.google.genai.types.GenerateContentResponse;
25+
import com.google.genai.types.HttpOptions;
26+
import com.google.genai.types.Part;
27+
import com.google.genai.types.Tool;
28+
import com.google.genai.types.ToolCodeExecution;
29+
import java.io.IOException;
30+
import java.nio.file.Files;
31+
import java.nio.file.Paths;
32+
33+
public class ToolsCodeExecWithTextLocalImage {
34+
35+
public static void main(String[] args) throws IOException {
36+
// TODO(developer): Replace these variables before running the sample.
37+
String modelId = "gemini-2.5-flash";
38+
generateContent(modelId);
39+
}
40+
41+
// Generates text using the Code Execution tool with text and image input
42+
public static String generateContent(String modelId) throws IOException {
43+
// Initialize client that will be used to send requests. This client only needs to be created
44+
// once, and can be reused for multiple requests.
45+
try (Client client =
46+
Client.builder()
47+
.location("global")
48+
.vertexAI(true)
49+
.httpOptions(HttpOptions.builder().apiVersion("v1").build())
50+
.build()) {
51+
52+
String prompt =
53+
"Run a simulation of the Monty Hall Problem with 1,000 trials.\n"
54+
+ "Here's how this works as a reminder. In the Monty Hall Problem, you're on a game"
55+
+ " show with three doors. Behind one is a car, and behind the others are goats. You"
56+
+ " pick a door. The host, who knows what's behind the doors, opens a different door"
57+
+ " to reveal a goat. Should you switch to the remaining unopened door?\n"
58+
+ " The answer has always been a little difficult for me to understand when people"
59+
+ " solve it with math - so please run a simulation with Python to show me what the"
60+
+ " best strategy is.\n"
61+
+ " Thank you!";
62+
63+
// Read content from the local image
64+
// Image source: https://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/Monty_open_door.svg/640px-Monty_open_door.svg.png
65+
byte[] imageData = Files.readAllBytes(Paths.get("resources/640px-Monty_open_door.svg.png"));
66+
67+
// Create a GenerateContentConfig and set codeExecution tool
68+
GenerateContentConfig contentConfig =
69+
GenerateContentConfig.builder()
70+
.tools(Tool.builder().codeExecution(ToolCodeExecution.builder().build()).build())
71+
.temperature(0.0F)
72+
.build();
73+
74+
GenerateContentResponse response =
75+
client.models.generateContent(
76+
modelId,
77+
Content.fromParts(Part.fromBytes(imageData, "image/png"), Part.fromText(prompt)),
78+
contentConfig);
79+
80+
System.out.println("Code: \n" + response.executableCode());
81+
System.out.println("Outcome: \n" + response.codeExecutionResult());
82+
// Example response
83+
// Code:
84+
// import random
85+
//
86+
// def run_monty_hall_trial():
87+
// doors = [0, 1, 2] # Represent doors as indices 0, 1, 2
88+
//
89+
// # 1. Randomly place the car behind one door
90+
// car_door = random.choice(doors)
91+
// ...
92+
//
93+
// Outcome:
94+
// Number of trials: 1000
95+
// Stick strategy wins: 327 (32.70%)
96+
// Switch strategy wins: 673 (67.30%)
97+
return response.executableCode();
98+
}
99+
}
100+
}
101+
// [END googlegenaisdk_tools_code_exec_with_txt_local_img]
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
* Copyright 2025 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package genai.tools;
18+
19+
// [START googlegenaisdk_tools_google_search_with_txt]
20+
21+
import com.google.genai.Client;
22+
import com.google.genai.types.GenerateContentConfig;
23+
import com.google.genai.types.GenerateContentResponse;
24+
import com.google.genai.types.GoogleSearch;
25+
import com.google.genai.types.HttpOptions;
26+
import com.google.genai.types.Tool;
27+
28+
public class ToolsGoogleSearchWithText {
29+
30+
public static void main(String[] args) {
31+
// TODO(developer): Replace these variables before running the sample.
32+
String modelId = "gemini-2.5-flash";
33+
generateContent(modelId);
34+
}
35+
36+
// Generates text with Google Search tool
37+
public static String generateContent(String modelId) {
38+
// Initialize client that will be used to send requests. This client only needs to be created
39+
// once, and can be reused for multiple requests.
40+
try (Client client =
41+
Client.builder()
42+
.location("global")
43+
.vertexAI(true)
44+
.httpOptions(HttpOptions.builder().apiVersion("v1").build())
45+
.build()) {
46+
47+
// Create a GenerateContentConfig and set Google Search tool
48+
GenerateContentConfig contentConfig =
49+
GenerateContentConfig.builder()
50+
.tools(Tool.builder().googleSearch(GoogleSearch.builder().build()).build())
51+
.build();
52+
53+
GenerateContentResponse response =
54+
client.models.generateContent(
55+
modelId, "When is the next total solar eclipse in the United States?", contentConfig);
56+
57+
System.out.print(response.text());
58+
// Example response:
59+
// The next total solar eclipse in the United States will occur on...
60+
return response.text();
61+
}
62+
}
63+
}
64+
// [END googlegenaisdk_tools_google_search_with_txt]

genai/snippets/src/test/java/genai/tools/ToolsIT.java

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import static com.google.common.truth.Truth.assertWithMessage;
2121

2222
import java.io.ByteArrayOutputStream;
23+
import java.io.IOException;
2324
import java.io.PrintStream;
2425
import org.junit.After;
2526
import org.junit.Before;
@@ -32,6 +33,7 @@
3233
public class ToolsIT {
3334

3435
private static final String GEMINI_FLASH = "gemini-2.5-flash";
36+
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
3537
private ByteArrayOutputStream bout;
3638
private PrintStream out;
3739

@@ -57,6 +59,7 @@ public void setUp() {
5759
@After
5860
public void tearDown() {
5961
System.setOut(null);
62+
bout.reset();
6063
}
6164

6265
@Test
@@ -79,4 +82,27 @@ public void testGenerateContentWithFunctionDescription() {
7982
assertThat(response).contains("copies_sold=350000");
8083
assertThat(response).contains("album_name=Echoes of the Night");
8184
}
82-
}
85+
86+
@Test
87+
public void testToolsCodeExecWithText() {
88+
String response = ToolsCodeExecWithText.generateContent(GEMINI_FLASH);
89+
assertThat(response).isNotEmpty();
90+
assertThat(bout.toString()).contains("Code:");
91+
assertThat(bout.toString()).contains("Outcome:");
92+
}
93+
94+
@Test
95+
public void testToolsCodeExecWithTextLocalImage() throws IOException {
96+
String response = ToolsCodeExecWithTextLocalImage.generateContent(GEMINI_FLASH);
97+
assertThat(response).isNotEmpty();
98+
assertThat(bout.toString()).contains("Code:");
99+
assertThat(bout.toString()).contains("Outcome:");
100+
}
101+
102+
@Test
103+
public void testToolsGoogleSearchWithText() {
104+
String response = ToolsGoogleSearchWithText.generateContent(GEMINI_FLASH);
105+
assertThat(response).isNotEmpty();
106+
}
107+
108+
}

0 commit comments

Comments
 (0)