Skip to content

Commit 81a9890

Browse files
committed
feat(genai): Add new GenAI SDK samples
1 parent add7429 commit 81a9890

11 files changed

+790
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package snippets;
2+
3+
// [START googlegenaisdk_counttoken_with_txt]
4+
5+
import com.google.genai.Client;
6+
import com.google.genai.types.Content;
7+
import com.google.genai.types.CountTokensResponse;
8+
import com.google.genai.types.HttpOptions;
9+
import com.google.genai.types.Part;
10+
import java.util.List;
11+
import java.util.Optional;
12+
13+
public class CountTokensWithText {
14+
15+
public static void main(String[] args) {
16+
// TODO(developer): Replace these variables before running the sample.
17+
String modelId = "gemini-2.0-flash";
18+
countTokens(modelId);
19+
}
20+
21+
public static Optional<Integer> countTokens(String modelId) {
22+
// Initialize client that will be used to send requests. This client only needs to be created
23+
// once, and can be reused for multiple requests.
24+
try (Client client = Client.builder()
25+
.httpOptions(HttpOptions.builder().apiVersion("v1").build())
26+
.build()) {
27+
28+
Content content = Content.builder()
29+
.parts(List.of(
30+
Part.fromText("What's the highest mountain in Africa?")))
31+
.build();
32+
33+
CountTokensResponse response =
34+
client.models.countTokens(modelId, List.of(content), null);
35+
36+
System.out.print(response);
37+
// Example response:
38+
// CountTokensResponse{totalTokens=Optional[9], cachedContentTokenCount=Optional.empty}
39+
return response.totalTokens();
40+
}
41+
}
42+
}
43+
// [END googlegenaisdk_counttoken_with_txt]
44+
45+
46+
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package snippets;
2+
3+
// [START googlegenaisdk_counttoken_with_txt_vid]
4+
5+
import com.google.genai.Client;
6+
import com.google.genai.types.Content;
7+
import com.google.genai.types.CountTokensResponse;
8+
import com.google.genai.types.HttpOptions;
9+
import com.google.genai.types.Part;
10+
import java.util.List;
11+
import java.util.Optional;
12+
13+
public class CountTokensWithTextAndVideo {
14+
15+
public static void main(String[] args) {
16+
// TODO(developer): Replace these variables before running the sample.
17+
String modelId = "gemini-2.0-flash";
18+
countTokens(modelId);
19+
}
20+
21+
public static Optional<Integer> countTokens(String modelId) {
22+
// Initialize client that will be used to send requests. This client only needs to be created
23+
// once, and can be reused for multiple requests.
24+
try (Client client = Client.builder()
25+
.httpOptions(HttpOptions.builder().apiVersion("v1").build())
26+
.build()) {
27+
28+
Content content = Content.builder()
29+
.parts(List.of(
30+
Part.fromText("Provide a description of this video"),
31+
Part.fromUri("gs://cloud-samples-data/generative-ai/video/pixel8.mp4", "video/mp4")))
32+
.build();
33+
34+
CountTokensResponse response =
35+
client.models.countTokens(modelId, List.of(content),
36+
null);
37+
38+
System.out.print(response);
39+
// Example response:
40+
// CountTokensResponse{totalTokens=Optional[16251], cachedContentTokenCount=Optional.empty}
41+
return response.totalTokens();
42+
}
43+
}
44+
}
45+
// [END googlegenaisdk_counttoken_with_txt_vid]
46+
47+
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package snippets;
2+
3+
// [START googlegenaisdk_textgen_with_txt_stream]
4+
5+
import com.google.genai.Client;
6+
import com.google.genai.ResponseStream;
7+
import com.google.genai.types.GenerateContentConfig;
8+
import com.google.genai.types.GenerateContentResponse;
9+
import com.google.genai.types.HttpOptions;
10+
11+
public class GenerateContentStream {
12+
13+
public static void main(String[] args) {
14+
// TODO(developer): Replace these variables before running the sample.
15+
String contents = "Why is the sky blue?";
16+
String modelId = "gemini-2.0-flash";
17+
generateContent(modelId, contents);
18+
}
19+
20+
public static String generateContent(String modelId, String contents) {
21+
// Initialize client that will be used to send requests. This client only needs to be created
22+
// once, and can be reused for multiple requests.
23+
try (Client client = Client.builder()
24+
.httpOptions(HttpOptions.builder().apiVersion("v1").build())
25+
.build()) {
26+
27+
StringBuilder responseTextBuilder = new StringBuilder();
28+
ResponseStream<GenerateContentResponse> responseStream =
29+
client.models.generateContentStream(modelId, contents, null);
30+
31+
for (GenerateContentResponse chunk : responseStream) {
32+
System.out.print(chunk.text());
33+
responseTextBuilder.append(chunk.text());
34+
}
35+
// Example response:
36+
// The sky appears blue due to a phenomenon called **Rayleigh scattering**. Here's
37+
// a breakdown of why:
38+
// ...
39+
return responseTextBuilder.toString();
40+
}
41+
}
42+
}
43+
// [END googlegenaisdk_textgen_with_txt_stream]
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package snippets;
2+
3+
// [START googlegenaisdk_ctrlgen_with_enum_schema]
4+
5+
import com.google.genai.Client;
6+
import com.google.genai.types.GenerateContentConfig;
7+
import com.google.genai.types.GenerateContentResponse;
8+
import com.google.genai.types.HttpOptions;
9+
import com.google.genai.types.Schema;
10+
import com.google.genai.types.Type;
11+
import java.util.List;
12+
13+
public class GenerateContentWithEnumSchema {
14+
15+
public static void main(String[] args) {
16+
// TODO(developer): Replace these variables before running the sample.
17+
String contents = "What type of instrument is an oboe?";
18+
String modelId = "gemini-2.0-flash";
19+
generateContent(modelId, contents);
20+
}
21+
22+
public static String generateContent(String modelId, String contents) {
23+
// Initialize client that will be used to send requests. This client only needs to be created
24+
// once, and can be reused for multiple requests.
25+
try (Client client = Client.builder()
26+
.httpOptions(HttpOptions.builder().apiVersion("v1").build())
27+
.build()) {
28+
29+
// Define the response schema with an enum.
30+
Schema responseSchema =
31+
Schema.builder()
32+
.type(Type.Known.STRING)
33+
.enum_(
34+
List.of("Percussion", "String", "Woodwind", "Brass", "Keyboard"))
35+
.build();
36+
37+
GenerateContentConfig config = GenerateContentConfig.builder()
38+
.responseMimeType("text/x.enum")
39+
.responseSchema(responseSchema)
40+
.build();
41+
42+
GenerateContentResponse response =
43+
client.models.generateContent(modelId, contents, config);
44+
45+
System.out.print(response.text());
46+
// Example response:
47+
// Woodwind
48+
return response.text();
49+
}
50+
}
51+
}
52+
// [END googlegenaisdk_ctrlgen_with_enum_schema]
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
package snippets;
2+
3+
// [START googlegenaisdk_tools_func_desc_with_txt]
4+
5+
import com.google.genai.Client;
6+
import com.google.genai.types.FunctionDeclaration;
7+
import com.google.genai.types.GenerateContentConfig;
8+
import com.google.genai.types.GenerateContentResponse;
9+
import com.google.genai.types.HttpOptions;
10+
import com.google.genai.types.Schema;
11+
import com.google.genai.types.Tool;
12+
import com.google.genai.types.Type;
13+
import java.util.List;
14+
import java.util.Map;
15+
16+
public class GenerateContentWithFunctionDescription {
17+
18+
public static void main(String[] args) {
19+
// TODO(developer): Replace these variables before running the sample.
20+
String modelId = "gemini-2.0-flash";
21+
String contents =
22+
"At Stellar Sounds, a music label, 2024 was a rollercoaster. \"Echoes of the Night,\" a debut synth-pop album, '\n"
23+
+ " 'surprisingly sold 350,000 copies, while veteran rock band \"Crimson Tide's\" latest, \"Reckless Hearts,\" '\n"
24+
+ " 'lagged at 120,000. Their up-and-coming indie artist, \"Luna Bloom's\" EP, \"Whispers of Dawn,\" '\n"
25+
+ " 'secured 75,000 sales. The biggest disappointment was the highly-anticipated rap album \"Street Symphony\" '\n"
26+
+ " \"only reaching 100,000 units. Overall, Stellar Sounds moved over 645,000 units this year, revealing unexpected \"\n"
27+
+ " \"trends in music consumption.";
28+
29+
generateContent(modelId, contents);
30+
}
31+
32+
public static String generateContent(String modelId, String contents) {
33+
// Initialize client that will be used to send requests. This client only needs to be created
34+
// once, and can be reused for multiple requests.
35+
try (Client client = Client.builder()
36+
.httpOptions(HttpOptions.builder().apiVersion("v1").build())
37+
.build()) {
38+
39+
FunctionDeclaration getAlbumSales = FunctionDeclaration.builder()
40+
.name("get_album_sales")
41+
.description("Gets the number of albums sold")
42+
// Function parameters are specified in schema format
43+
.parameters(Schema.builder()
44+
.type(Type.Known.OBJECT)
45+
.properties(Map.of(
46+
"albums", Schema.builder()
47+
.type(Type.Known.ARRAY)
48+
.description("List of albums")
49+
.items(Schema.builder()
50+
.description("Album and its sales")
51+
.type(Type.Known.OBJECT)
52+
.properties(Map.of(
53+
"album_name", Schema.builder()
54+
.type(Type.Known.STRING)
55+
.description("Name of the music album")
56+
.build(),
57+
"copies_sold", Schema.builder()
58+
.type(Type.Known.INTEGER)
59+
.description("Number of copies sold")
60+
.build()
61+
))
62+
.build()) // End items schema for albums
63+
.build() // End "albums" property schema
64+
))
65+
.build()) // End parameters schema
66+
.build(); // End function declaration
67+
68+
Tool salesTool = Tool.builder()
69+
.functionDeclarations(List.of(getAlbumSales))
70+
.build();
71+
72+
GenerateContentConfig config = GenerateContentConfig.builder()
73+
.tools(List.of(salesTool))
74+
.temperature(0.0f)
75+
.build();
76+
77+
GenerateContentResponse response = client.models.generateContent(
78+
modelId,
79+
contents,
80+
config);
81+
82+
// response.functionCalls() returns an Optional<List<FunctionCall>>.
83+
// We get the list, then get the first FunctionCall from the list.
84+
System.out.println(response.functionCalls().get(0));
85+
return response.functionCalls().toString();
86+
// Example response:
87+
// FunctionCall{id=Optional.empty, args=Optional[{albums=[{copies_sold=350000, album_name=Echoes of the Night},
88+
// {copies_sold=120000, album_name=Reckless Hearts}, {copies_sold=75000, album_name=Whispers of Dawn},
89+
// {album_name=Street Symphony, copies_sold=100000}]}], name=Optional[get_album_sales]}
90+
}
91+
}
92+
}
93+
// [END googlegenaisdk_tools_func_desc_with_txt]
94+
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package snippets;
2+
3+
// [START googlegenaisdk_textgen_sys_instr_with_txt]
4+
5+
import com.google.genai.Client;
6+
import com.google.genai.types.Content;
7+
import com.google.genai.types.GenerateContentConfig;
8+
import com.google.genai.types.GenerateContentResponse;
9+
import com.google.genai.types.HttpOptions;
10+
import com.google.genai.types.Part;
11+
12+
public class GenerateContentWithSystemInstruction {
13+
14+
public static void main(String[] args) {
15+
// TODO(developer): Replace these variables before running the sample.
16+
String modelId = "gemini-2.0-flash";
17+
generateContent(modelId);
18+
}
19+
20+
public static String generateContent(String modelId) {
21+
// Initialize client that will be used to send requests. This client only needs to be created
22+
// once, and can be reused for multiple requests.
23+
try (Client client = Client.builder()
24+
.httpOptions(HttpOptions.builder().apiVersion("v1").build())
25+
.build()) {
26+
27+
GenerateContentConfig config = GenerateContentConfig.builder()
28+
.systemInstruction(Content.fromParts(
29+
Part.fromText("You're a language translator."),
30+
Part.fromText("Your mission is to translate text in English to French.")))
31+
.build();
32+
33+
GenerateContentResponse response =
34+
client.models.generateContent(modelId, Content.fromParts(
35+
Part.fromText("Why is the sky blue?")),
36+
config);
37+
38+
System.out.print(response.text());
39+
// Example response:
40+
// Pourquoi le ciel est-il bleu ?
41+
return response.text();
42+
}
43+
}
44+
}
45+
// [END googlegenaisdk_textgen_sys_instr_with_txt]
46+
47+
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package snippets;
2+
3+
// [START googlegenaisdk_textgen_with_txt]
4+
5+
import com.google.genai.Client;
6+
import com.google.genai.types.Content;
7+
import com.google.genai.types.GenerateContentResponse;
8+
import com.google.genai.types.HttpOptions;
9+
import com.google.genai.types.Part;
10+
11+
public class GenerateContentWithText {
12+
13+
public static void main(String[] args) {
14+
// TODO(developer): Replace these variables before running the sample.
15+
String modelId = "gemini-2.0-flash";
16+
generateContent(modelId);
17+
}
18+
19+
public static String generateContent(String modelId) {
20+
// Initialize client that will be used to send requests. This client only needs to be created
21+
// once, and can be reused for multiple requests.
22+
try (Client client = Client.builder()
23+
.httpOptions(HttpOptions.builder().apiVersion("v1").build())
24+
.build()) {
25+
26+
GenerateContentResponse response =
27+
client.models.generateContent(modelId, Content.fromParts(
28+
Part.fromText("How does AI work?")),
29+
null);
30+
31+
System.out.print(response.text());
32+
// Example response:
33+
// Okay, let's break down how AI works. It's a broad field, so I'll focus on the ...
34+
//
35+
// Here's a simplified overview:
36+
// ...
37+
return response.text();
38+
}
39+
}
40+
}
41+
// [END googlegenaisdk_textgen_with_txt]
42+

0 commit comments

Comments
 (0)