Skip to content

Commit 1af49a4

Browse files
jdomingrJuan Dominguez
andauthored
feat(genai): add text generation samples - part 3 (#10156)
* feat: add new genAI text gen audio transcription sample * feat: add new genAI textgen chat with text sample * feat: add new GenAI textgen chat with stream sample * feat(genai): add new text generation samples * feat(genai): add new text generation samples * fix textgen chat sample * fix some comments * make some comments simpler * fix license header comment --------- Co-authored-by: Juan Dominguez <[email protected]>
1 parent 8ddf269 commit 1af49a4

File tree

4 files changed

+250
-39
lines changed

4 files changed

+250
-39
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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_chat_stream_with_txt]
20+
21+
import com.google.genai.Chat;
22+
import com.google.genai.Client;
23+
import com.google.genai.ResponseStream;
24+
import com.google.genai.types.GenerateContentResponse;
25+
import com.google.genai.types.HttpOptions;
26+
27+
public class TextGenerationChatStreamWithText {
28+
29+
public static void main(String[] args) {
30+
// TODO(developer): Replace these variables before running the sample.
31+
String modelId = "gemini-2.5-flash";
32+
generateContent(modelId);
33+
}
34+
35+
// Shows how to create a new chat session stream
36+
public static String generateContent(String modelId) {
37+
// Client Initialization. Once created, it can be reused for multiple requests.
38+
try (Client client =
39+
Client.builder()
40+
.location("global")
41+
.vertexAI(true)
42+
.httpOptions(HttpOptions.builder().apiVersion("v1").build())
43+
.build()) {
44+
45+
Chat chatSession = client.chats.create(modelId);
46+
StringBuilder responseTextBuilder = new StringBuilder();
47+
48+
try (ResponseStream<GenerateContentResponse> response =
49+
chatSession.sendMessageStream("Why is the sky blue?")) {
50+
51+
for (GenerateContentResponse chunk : response) {
52+
System.out.println(chunk.text());
53+
responseTextBuilder.append(chunk.text());
54+
}
55+
56+
}
57+
// Example response:
58+
//
59+
// The sky is blue primarily due to a phenomenon called **Rayleigh scattering**,
60+
// named after the British physicist Lord Rayleigh. Here's a breakdown of how...
61+
return responseTextBuilder.toString();
62+
}
63+
}
64+
}
65+
// [END googlegenaisdk_textgen_chat_stream_with_txt]
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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_chat_with_txt]
20+
21+
import com.google.genai.Chat;
22+
import com.google.genai.Client;
23+
import com.google.genai.types.Content;
24+
import com.google.genai.types.GenerateContentConfig;
25+
import com.google.genai.types.GenerateContentResponse;
26+
import com.google.genai.types.HttpOptions;
27+
import com.google.genai.types.Part;
28+
29+
public class TextGenerationChatWithText {
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+
generateContent(modelId);
35+
}
36+
37+
// Shows how to create a chat session
38+
public static String generateContent(String modelId) {
39+
// Client Initialization. Once created, it 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 new chat session
48+
Chat chatSession = client.chats.create(modelId);
49+
50+
GenerateContentResponse response = chatSession.sendMessage("Tell me a story");
51+
System.out.print(response.text());
52+
// Example response:
53+
//
54+
// In the heart of the Whispering Peaks lay the Valley of Silent Echoes, a place perpetually
55+
// shrouded in a twilight mist. No birds sang there, no rivers flowed, and the few trees that
56+
// clung to its edges were gnarled and bare...
57+
return response.text();
58+
}
59+
}
60+
}
61+
// [END googlegenaisdk_textgen_chat_with_txt]
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
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_transcript_with_gcs_audio]
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+
28+
public class TextGenerationTranscriptWithGcsAudio {
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 transcript with audio input
37+
public static String generateContent(String modelId) {
38+
// Client Initialization. Once created, it can be reused for multiple requests.
39+
try (Client client =
40+
Client.builder()
41+
.location("global")
42+
.vertexAI(true)
43+
.httpOptions(HttpOptions.builder().apiVersion("v1").build())
44+
.build()) {
45+
46+
String prompt =
47+
"Transcribe the interview, in the format of timecode, speaker, caption.\n"
48+
+ "Use speaker A, speaker B, etc. to identify speakers.";
49+
50+
// Enable audioTimestamp to generate timestamps for audio-only files.
51+
GenerateContentConfig contentConfig =
52+
GenerateContentConfig.builder().audioTimestamp(true).build();
53+
54+
GenerateContentResponse response =
55+
client.models.generateContent(
56+
modelId,
57+
Content.fromParts(
58+
Part.fromUri(
59+
"gs://cloud-samples-data/generative-ai/audio/pixel.mp3", "audio/mpeg"),
60+
Part.fromText(prompt)),
61+
contentConfig);
62+
63+
System.out.print(response.text());
64+
// Example response:
65+
// 00:00 - Speaker A: your devices are getting better over time. And so we think about it...
66+
// 00:14 - Speaker B: Welcome to the Made by Google Podcast, where we meet the people who...
67+
// 00:41 - Speaker A: So many features. I am a singer, so I actually think recorder...
68+
return response.text();
69+
}
70+
}
71+
}
72+
// [END googlegenaisdk_textgen_transcript_with_gcs_audio]

genai/snippets/src/test/java/genai/textgeneration/TextGenerationIT.java

Lines changed: 52 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -63,60 +63,59 @@ public void tearDown() {
6363
}
6464

6565
@Test
66-
public void testTextGenerationWithTextStream() {
67-
String prompt = "Why is the sky blue?";
68-
String response = TextGenerationWithTextStream.generateContent(GEMINI_FLASH, prompt);
66+
public void testTextGenerationAsyncWithText() {
67+
String response = TextGenerationAsyncWithText.generateContent(GEMINI_FLASH);
6968
assertThat(response).isNotEmpty();
7069
}
7170

7271
@Test
73-
public void testTextGenerationWithSystemInstruction() {
74-
String response = TextGenerationWithSystemInstruction.generateContent(GEMINI_FLASH);
72+
public void testTextGenerationChatStreamWithText() {
73+
String response = TextGenerationChatStreamWithText.generateContent(GEMINI_FLASH);
7574
assertThat(response).isNotEmpty();
7675
}
7776

7877
@Test
79-
public void testTextGenerationWithText() {
80-
String response = TextGenerationWithText.generateContent(GEMINI_FLASH);
78+
public void testTextGenerationChatWithText() {
79+
String response = TextGenerationChatWithText.generateContent(GEMINI_FLASH);
8180
assertThat(response).isNotEmpty();
8281
}
8382

8483
@Test
85-
public void testTextGenerationWithTextAndImage() {
86-
String response = TextGenerationWithTextAndImage.generateContent(GEMINI_FLASH);
84+
public void testTextGenerationCodeWithPdf() {
85+
String response = TextGenerationCodeWithPdf.generateContent(GEMINI_FLASH);
8786
assertThat(response).isNotEmpty();
8887
}
8988

9089
@Test
91-
public void testTextGenerationWithVideo() {
92-
93-
String prompt =
94-
" Analyze the provided video file, including its audio.\n"
95-
+ " Summarize the main points of the video concisely.\n"
96-
+ " Create a chapter breakdown with timestamps for key sections or topics discussed.";
97-
98-
String response = TextGenerationWithVideo.generateContent(GEMINI_FLASH, prompt);
90+
public void testTextGenerationConfigWithText() {
91+
String response = TextGenerationConfigWithText.generateContent(GEMINI_FLASH);
9992
assertThat(response).isNotEmpty();
100-
assertThat(response).ignoringCase().contains("Tokyo");
101-
assertThat(response).ignoringCase().contains("Pixel");
10293
}
10394

10495
@Test
105-
public void testTextGenerationWithMultiImage() throws IOException {
106-
107-
String gcsFileImagePath = "gs://cloud-samples-data/generative-ai/image/scones.jpg";
108-
String localImageFilePath = "resources/latte.jpg";
96+
public void testTextGenerationTranscriptWithGcsAudio() {
97+
String response = TextGenerationTranscriptWithGcsAudio.generateContent(GEMINI_FLASH);
98+
assertThat(response).isNotEmpty();
99+
}
109100

110-
String response =
111-
TextGenerationWithMultiImage.generateContent(
112-
GEMINI_FLASH, gcsFileImagePath, localImageFilePath);
101+
@Test
102+
public void testTextGenerationWithGcsAudio() {
103+
String response = TextGenerationWithGcsAudio.generateContent(GEMINI_FLASH);
104+
assertThat(response).isNotEmpty();
105+
}
113106

107+
@Test
108+
public void testTextGenerationWithLocalVideo() throws IOException {
109+
String response = TextGenerationWithLocalVideo.generateContent(GEMINI_FLASH);
114110
assertThat(response).isNotEmpty();
115111
}
116112

117113
@Test
118-
public void testTextGenerationAsyncWithText() {
119-
String response = TextGenerationAsyncWithText.generateContent(GEMINI_FLASH);
114+
public void testTextGenerationWithMultiImage() throws IOException {
115+
String gcsFileImagePath = "gs://cloud-samples-data/generative-ai/image/scones.jpg";
116+
String response =
117+
TextGenerationWithMultiImage.generateContent(
118+
GEMINI_FLASH, gcsFileImagePath, LOCAL_IMG_1);
120119
assertThat(response).isNotEmpty();
121120
}
122121

@@ -125,7 +124,6 @@ public void testTextGenerationWithMultiLocalImage() throws IOException {
125124
String response =
126125
TextGenerationWithMultiLocalImage.generateContent(
127126
GEMINI_FLASH, LOCAL_IMG_1, LOCAL_IMG_2);
128-
129127
assertThat(response).isNotEmpty();
130128
}
131129

@@ -142,32 +140,47 @@ public void testTextGenerationWithPdf() {
142140
}
143141

144142
@Test
145-
public void testTextGenerationWithYoutubeVideo() {
146-
String response = TextGenerationWithYoutubeVideo.generateContent(GEMINI_FLASH);
143+
public void testTextGenerationWithSystemInstruction() {
144+
String response = TextGenerationWithSystemInstruction.generateContent(GEMINI_FLASH);
147145
assertThat(response).isNotEmpty();
148146
}
149147

150148
@Test
151-
public void testTextGenerationCodeWithPdf() {
152-
String response = TextGenerationCodeWithPdf.generateContent(GEMINI_FLASH);
149+
public void testTextGenerationWithText() {
150+
String response = TextGenerationWithText.generateContent(GEMINI_FLASH);
153151
assertThat(response).isNotEmpty();
154152
}
155153

156154
@Test
157-
public void testTextGenerationConfigWithText() {
158-
String response = TextGenerationConfigWithText.generateContent(GEMINI_FLASH);
155+
public void testTextGenerationWithTextAndImage() {
156+
String response = TextGenerationWithTextAndImage.generateContent(GEMINI_FLASH);
159157
assertThat(response).isNotEmpty();
160158
}
161159

162160
@Test
163-
public void testTextGenerationWithGcsAudio() {
164-
String response = TextGenerationWithGcsAudio.generateContent(GEMINI_FLASH);
161+
public void testTextGenerationWithTextStream() {
162+
String prompt = "Why is the sky blue?";
163+
String response = TextGenerationWithTextStream.generateContent(GEMINI_FLASH, prompt);
165164
assertThat(response).isNotEmpty();
166165
}
167166

168167
@Test
169-
public void testTextGenerationWithLocalVideo() throws IOException {
170-
String response = TextGenerationWithLocalVideo.generateContent(GEMINI_FLASH);
168+
public void testTextGenerationWithVideo() {
169+
String prompt =
170+
" Analyze the provided video file, including its audio.\n"
171+
+ " Summarize the main points of the video concisely.\n"
172+
+ " Create a chapter breakdown with timestamps for key sections or topics discussed.";
173+
174+
String response = TextGenerationWithVideo.generateContent(GEMINI_FLASH, prompt);
175+
assertThat(response).isNotEmpty();
176+
assertThat(response).ignoringCase().contains("Tokyo");
177+
assertThat(response).ignoringCase().contains("Pixel");
178+
}
179+
180+
@Test
181+
public void testTextGenerationWithYoutubeVideo() {
182+
String response = TextGenerationWithYoutubeVideo.generateContent(GEMINI_FLASH);
171183
assertThat(response).isNotEmpty();
172184
}
185+
173186
}

0 commit comments

Comments
 (0)