Skip to content

Commit 04386c1

Browse files
jdomingrJuan Dominguez
andauthored
Add new GenAI SDK samples (#10138)
* feat: add new GenAI controlled generation sample * feat: add new GenAI text generation samples * feat: add new GenAI count tokens samples * feat: add new GenAI tools sample * chore: update dependencies * chore: update dependencies * refactor: update samples * feat: add Gen AI sample directory * refactor: update some samples to pass in text directly instead of Content * refactor: change client init in samples --------- Co-authored-by: Juan Dominguez <[email protected]>
1 parent 9800eb7 commit 04386c1

17 files changed

+1142
-0
lines changed

.github/CODEOWNERS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@
7474
/dialogflow-cx @GoogleCloudPlatform/java-samples-reviewers @yoshi-approver @GoogleCloudPlatform/cloud-samples-reviewers
7575
/discoveryengine @GoogleCloudPlatform/java-samples-reviewers @yoshi-approver @GoogleCloudPlatform/cloud-samples-reviewers
7676
/document-ai @GoogleCloudPlatform/java-samples-reviewers @yoshi-approver @GoogleCloudPlatform/cloud-samples-reviewers
77+
/genai @GoogleCloudPlatform/java-samples-reviewers @yoshi-approver @GoogleCloudPlatform/cloud-samples-reviewers
7778
/jobs @GoogleCloudPlatform/java-samples-reviewers @yoshi-approver @GoogleCloudPlatform/cloud-samples-reviewers
7879
/language @GoogleCloudPlatform/java-samples-reviewers @yoshi-approver @GoogleCloudPlatform/cloud-samples-reviewers
7980
/mediatranslation @GoogleCloudPlatform/java-samples-reviewers @yoshi-approver @GoogleCloudPlatform/cloud-samples-reviewers

genai/snippets/pom.xml

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
Copyright 2025 Google LLC
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+
http://www.apache.org/licenses/LICENSE-2.0
8+
Unless required by applicable law or agreed to in writing, software
9+
distributed under the License is distributed on an "AS IS" BASIS,
10+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
See the License for the specific language governing permissions and
12+
limitations under the License.
13+
-->
14+
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
15+
xmlns="http://maven.apache.org/POM/4.0.0"
16+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
17+
<modelVersion>4.0.0</modelVersion>
18+
<groupId>com.example.genai</groupId>
19+
<artifactId>genai-snippets</artifactId>
20+
<packaging>jar</packaging>
21+
<name>Google Gen AI SDK Snippets</name>
22+
<!--
23+
The parent pom defines common style checks and testing strategies for our samples.
24+
Removing or replacing it should not affect the execution of the samples in any way.
25+
-->
26+
<parent>
27+
<artifactId>shared-configuration</artifactId>
28+
<groupId>com.google.cloud.samples</groupId>
29+
<version>1.2.0</version>
30+
</parent>
31+
32+
<properties>
33+
<maven.compiler.source>11</maven.compiler.source>
34+
<maven.compiler.target>11</maven.compiler.target>
35+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
36+
</properties>
37+
38+
<dependencyManagement>
39+
<dependencies>
40+
<dependency>
41+
<artifactId>libraries-bom</artifactId>
42+
<groupId>com.google.cloud</groupId>
43+
<scope>import</scope>
44+
<type>pom</type>
45+
<version>26.64.0</version>
46+
</dependency>
47+
</dependencies>
48+
</dependencyManagement>
49+
50+
<dependencies>
51+
<dependency>
52+
<groupId>com.google.genai</groupId>
53+
<artifactId>google-genai</artifactId>
54+
<version>1.10.0</version>
55+
</dependency>
56+
<dependency>
57+
<artifactId>junit</artifactId>
58+
<groupId>junit</groupId>
59+
<scope>test</scope>
60+
<version>4.13.2</version>
61+
</dependency>
62+
<dependency>
63+
<groupId>com.google.truth</groupId>
64+
<artifactId>truth</artifactId>
65+
<version>1.4.4</version>
66+
<scope>test</scope>
67+
</dependency>
68+
</dependencies>
69+
</project>

genai/snippets/resources/latte.jpg

52 KB
Loading
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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.controlledgeneration;
18+
19+
// [START googlegenaisdk_ctrlgen_with_enum_schema]
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.Schema;
26+
import com.google.genai.types.Type;
27+
import java.util.List;
28+
29+
public class ControlledGenerationWithEnumSchema {
30+
31+
public static void main(String[] args) {
32+
// TODO(developer): Replace these variables before running the sample.
33+
String contents = "What type of instrument is an oboe?";
34+
String modelId = "gemini-2.5-flash";
35+
generateContent(modelId, contents);
36+
}
37+
38+
// Generates content with an enum response schema
39+
public static String generateContent(String modelId, String contents) {
40+
// Initialize client that will be used to send requests. This client only needs to be created
41+
// once, and can be reused for multiple requests.
42+
try (Client client =
43+
Client.builder()
44+
.location("global")
45+
.vertexAI(true)
46+
.httpOptions(HttpOptions.builder().apiVersion("v1").build())
47+
.build()) {
48+
49+
// Define the response schema with an enum.
50+
Schema responseSchema =
51+
Schema.builder()
52+
.type(Type.Known.STRING)
53+
.enum_(List.of("Percussion", "String", "Woodwind", "Brass", "Keyboard"))
54+
.build();
55+
56+
GenerateContentConfig config =
57+
GenerateContentConfig.builder()
58+
.responseMimeType("text/x.enum")
59+
.responseSchema(responseSchema)
60+
.build();
61+
62+
GenerateContentResponse response = client.models.generateContent(modelId, contents, config);
63+
64+
System.out.print(response.text());
65+
// Example response:
66+
// Woodwind
67+
return response.text();
68+
}
69+
}
70+
}
71+
// [END googlegenaisdk_ctrlgen_with_enum_schema]
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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.counttokens;
18+
19+
// [START googlegenaisdk_counttoken_with_txt]
20+
21+
import com.google.genai.Client;
22+
import com.google.genai.types.Content;
23+
import com.google.genai.types.CountTokensResponse;
24+
import com.google.genai.types.HttpOptions;
25+
import com.google.genai.types.Part;
26+
import java.util.List;
27+
import java.util.Optional;
28+
29+
public class CountTokensWithText {
30+
31+
public static void main(String[] args) {
32+
// TODO(developer): Replace these variables before running the sample.
33+
String modelId = "gemini-2.5-flash";
34+
countTokens(modelId);
35+
}
36+
37+
// Counts tokens with text input
38+
public static Optional<Integer> countTokens(String modelId) {
39+
// Initialize client that will be used to send requests. This client only needs to be created
40+
// once, and can be reused for multiple requests.
41+
try (Client client =
42+
Client.builder()
43+
.location("global")
44+
.vertexAI(true)
45+
.httpOptions(HttpOptions.builder().apiVersion("v1").build())
46+
.build()) {
47+
48+
CountTokensResponse response =
49+
client.models.countTokens(modelId, "What's the highest mountain in Africa?", null);
50+
51+
System.out.print(response);
52+
// Example response:
53+
// CountTokensResponse{totalTokens=Optional[9], cachedContentTokenCount=Optional.empty}
54+
return response.totalTokens();
55+
}
56+
}
57+
}
58+
// [END googlegenaisdk_counttoken_with_txt]
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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.counttokens;
18+
19+
// [START googlegenaisdk_counttoken_with_txt_vid]
20+
21+
import com.google.genai.Client;
22+
import com.google.genai.types.Content;
23+
import com.google.genai.types.CountTokensResponse;
24+
import com.google.genai.types.HttpOptions;
25+
import com.google.genai.types.Part;
26+
import java.util.List;
27+
import java.util.Optional;
28+
29+
public class CountTokensWithTextAndVideo {
30+
31+
public static void main(String[] args) {
32+
// TODO(developer): Replace these variables before running the sample.
33+
String modelId = "gemini-2.5-flash";
34+
countTokens(modelId);
35+
}
36+
37+
// Counts tokens with text and video inputs
38+
public static Optional<Integer> countTokens(String modelId) {
39+
// Initialize client that will be used to send requests. This client only needs to be created
40+
// once, and can be reused for multiple requests.
41+
try (Client client =
42+
Client.builder()
43+
.location("global")
44+
.vertexAI(true)
45+
.httpOptions(HttpOptions.builder().apiVersion("v1").build())
46+
.build()) {
47+
48+
Content content =
49+
Content.fromParts(
50+
Part.fromText("Provide a description of this video"),
51+
Part.fromUri("gs://cloud-samples-data/generative-ai/video/pixel8.mp4", "video/mp4"));
52+
53+
CountTokensResponse response = client.models.countTokens(modelId, List.of(content), null);
54+
55+
System.out.print(response);
56+
// Example response:
57+
// CountTokensResponse{totalTokens=Optional[16707], cachedContentTokenCount=Optional.empty}
58+
return response.totalTokens();
59+
}
60+
}
61+
}
62+
// [END googlegenaisdk_counttoken_with_txt_vid]
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
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.textgeneration;
18+
19+
// [START googlegenaisdk_textgen_with_multi_img]
20+
21+
import com.google.genai.Client;
22+
import com.google.genai.types.Content;
23+
import com.google.genai.types.GenerateContentResponse;
24+
import com.google.genai.types.HttpOptions;
25+
import com.google.genai.types.Part;
26+
import java.io.IOException;
27+
import java.nio.file.Files;
28+
import java.nio.file.Paths;
29+
30+
public class TextGenerationWithMultiImage {
31+
32+
public static void main(String[] args) throws IOException {
33+
// TODO(developer): Replace these variables before running the sample.
34+
String modelId = "gemini-2.5-flash";
35+
// Content from Google Cloud Storage
36+
String gcsFileImagePath = "gs://cloud-samples-data/generative-ai/image/scones.jpg";
37+
String localImageFilePath = "resources/latte.jpg";
38+
generateContent(modelId, gcsFileImagePath, localImageFilePath);
39+
}
40+
41+
// Generates text with multiple images
42+
public static String generateContent(
43+
String modelId, String gcsFileImagePath, String localImageFilePath) throws IOException {
44+
// Initialize client that will be used to send requests. This client only needs to be created
45+
// once, and can be reused for multiple requests.
46+
try (Client client =
47+
Client.builder()
48+
.location("global")
49+
.vertexAI(true)
50+
.httpOptions(HttpOptions.builder().apiVersion("v1").build())
51+
.build()) {
52+
53+
// Read content from a local file.
54+
byte[] localFileImgBytes = Files.readAllBytes(Paths.get(localImageFilePath));
55+
56+
GenerateContentResponse response =
57+
client.models.generateContent(
58+
modelId,
59+
Content.fromParts(
60+
Part.fromText("Generate a list of all the objects contained in both images"),
61+
Part.fromBytes(localFileImgBytes, "image/jpeg"),
62+
Part.fromUri(gcsFileImagePath, "image/jpeg")),
63+
null);
64+
65+
System.out.print(response.text());
66+
// Example response:
67+
// Okay, here's the list of objects present in both images:
68+
//
69+
// **Image 1 (Scones):**
70+
//
71+
// * Scones
72+
// * Plate
73+
// * Jam/Preserve
74+
// * Cream/Butter
75+
// * Table/Surface
76+
// * Napkin/Cloth (possibly)
77+
//
78+
// **Image 2 (Latte):**
79+
//
80+
// * Latte/Coffee cup
81+
// * Saucer
82+
// * Spoon
83+
// * Table/Surface
84+
// * Foam/Latte art
85+
//
86+
// **Objects potentially in both (depending on interpretation and specific items):**
87+
//
88+
// * Plate/Saucer (both are serving dishes)
89+
// * Table/Surface
90+
return response.text();
91+
}
92+
}
93+
}
94+
// [END googlegenaisdk_textgen_with_multi_img]

0 commit comments

Comments
 (0)