Skip to content

feat: add new GenAI SDK text generation samples #10144

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
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
Binary file added genai/snippets/resources/scones.jpg
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,62 @@
/*
* 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.textgeneration;

// [START googlegenaisdk_textgen_async_with_txt]

import com.google.genai.Client;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import java.util.concurrent.CompletableFuture;

public class TextGenerationAsyncWithText {

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 asynchronously with text input
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()) {

CompletableFuture<GenerateContentResponse> asyncResponse =
client.async.models.generateContent(
modelId, "Compose a song about the adventures of a time-traveling squirrel.", null);

String response = asyncResponse.join().text();
System.out.print(response);
// Example response:
// (Verse 1)
// In an oak tree, so leafy and green,
// Lived Squeaky the squirrel, a critter unseen.
// Just burying nuts, a routine so grand,
// ...

return response;
}
}
}
// [END googlegenaisdk_textgen_async_with_txt]
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* 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.textgeneration;

// [START googlegenaisdk_textgen_with_multi_local_img]

import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Part;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class TextGenerationWithMultiLocalImage {

public static void main(String[] args) throws IOException {
// TODO(developer): Replace these variables before running the sample.
String modelId = "gemini-2.5-flash";
String localImageFilePath1 = "your/local/img1.jpg";
String localImageFilePath2 = "your/local/img2.jpg";
generateContent(modelId, localImageFilePath1, localImageFilePath2);
}

// Generates text using multiple local images
public static String generateContent(
String modelId, String localImageFilePath1, String localImageFilePath2) 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()) {

// Read content from local files.
byte[] localFileImg1Bytes = Files.readAllBytes(Paths.get(localImageFilePath1));
byte[] localFileImg2Bytes = Files.readAllBytes(Paths.get(localImageFilePath2));

GenerateContentResponse response =
client.models.generateContent(
modelId,
Content.fromParts(
Part.fromText("Generate a list of all the objects contained in both images"),
Part.fromBytes(localFileImg1Bytes, "image/jpeg"),
Part.fromBytes(localFileImg2Bytes, "image/jpeg")),
null);

System.out.print(response.text());
// Example response:
// Based on both images, here are the objects contained in both:
//
// 1. **Coffee cups (or mugs)**: Both images feature one or more cups containing a beverage.
// 2. **Coffee (or a similar beverage)**: Both images contain a liquid beverage in the cups,
// appearing to be coffee or a coffee-like drink.
// 3. **Table (or a flat surface)**: Both compositions are set on a flat surface, likely a
// table or countertop.
return response.text();
}
}
}
// [END googlegenaisdk_textgen_with_multi_local_img]
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* 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.textgeneration;

// [START googlegenaisdk_textgen_with_mute_video]

import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Part;

public class TextGenerationWithMuteVideo {

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 mute video input
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()) {

GenerateContentResponse response =
client.models.generateContent(
modelId,
Content.fromParts(
Part.fromText("What is in this video?"),
Part.fromUri(
"gs://cloud-samples-data/generative-ai/video/ad_copy_from_video.mp4",
"video/mp4")),
null);

System.out.print(response.text());
// Example response:
// This video features **surfers in the ocean**.
//
// The main focus is on **one individual who catches and rides a wave**, executing various
// turns and maneuvers as the wave breaks and dissipates into whitewater...
return response.text();
}
}
}
// [END googlegenaisdk_textgen_with_mute_video]
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* 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.textgeneration;

// [START googlegenaisdk_textgen_with_pdf]

import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Part;

public class TextGenerationWithPdf {

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 PDF file input
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()) {

String prompt = "You are a highly skilled document summarization specialist.\n"
+ " Your task is to provide a concise executive summary of no more than 300 words.\n"
+ " Please summarize the given document for a general audience";

GenerateContentResponse response =
client.models.generateContent(
modelId,
Content.fromParts(
Part.fromText(prompt),
Part.fromUri(
"gs://cloud-samples-data/generative-ai/pdf/1706.03762v7.pdf",
"application/pdf")),
null);

System.out.print(response.text());
// Example response:
// The document introduces the Transformer, a novel neural network architecture designed for
// sequence transduction tasks, such as machine translation. Unlike previous dominant models
// that rely on complex recurrent or convolutional neural networks, the Transformer proposes a
// simpler, more parallelizable design based *solely* on attention mechanisms, entirely
// dispensing with recurrence and convolutions...

return response.text();
}
}
}
// [END googlegenaisdk_textgen_with_pdf]
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,8 @@
// [START googlegenaisdk_textgen_with_txt]

import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Part;

public class TextGenerationWithText {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* 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.textgeneration;

// [START googlegenaisdk_textgen_with_youtube_video]

import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Part;

public class TextGenerationWithYoutubeVideo {

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 YouTube video input
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()) {

GenerateContentResponse response =
client.models.generateContent(
modelId,
Content.fromParts(
Part.fromText("Write a short and engaging blog post based on this video."),
Part.fromUri("https://www.youtube.com/watch?v=3KtWfp0UopM", "video/mp4")),
null);

System.out.print(response.text());
// Example response:
// 25 Years of Curiosity: A Google Anniversary Dive into What the World Searched For
//
// Remember a time before instant answers were just a click away? 25 years ago, Google
// launched, unleashing a wave of curiosity that has since charted the collective interests,
// anxieties, and celebrations of humanity...
return response.text();
}
}
}
// [END googlegenaisdk_textgen_with_youtube_video]
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,7 @@
import com.google.genai.types.Schema;
import com.google.genai.types.Tool;
import com.google.genai.types.Type;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

public class ToolFunctionDescriptionWithText {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,5 @@ public void testControlledGenerationWithEnumSchema() {
String prompt = "What type of instrument is an oboe?";
String response = ControlledGenerationWithEnumSchema.generateContent(GEMINI_FLASH, prompt);
assertThat(response).isNotEmpty();
assertThat(response).isEqualTo("Woodwind");
}
}
Loading