-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathGenerateContentStream.java
More file actions
66 lines (60 loc) · 2.49 KB
/
GenerateContentStream.java
File metadata and controls
66 lines (60 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
*
* https://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.
*/
/**
* Usage:
*
* <p>1a. If you are using Vertex AI, setup ADC to get credentials:
* https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp
*
* <p>Then set Project, Location, and USE_VERTEXAI flag as environment variables:
*
* <p>export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT
*
* <p>export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION
*
* <p>1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a
* list of available API keys here: https://aistudio.google.com/app/apikey
*
* <p>export GOOGLE_API_KEY=YOUR_API_KEY
*
* <p>2. Compile the java package and run the sample code.
*
* <p>mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContentStream"
*/
package com.google.genai.examples;
import com.google.genai.Client;
import com.google.genai.ResponseStream;
import com.google.genai.types.GenerateContentResponse;
import java.io.IOException;
import org.apache.http.HttpException;
/** An example of using the Unified GenAI Java SDK to generate stream of content. */
public class GenerateContentStream {
public static void main(String[] args) throws IOException, HttpException {
// Instantiate the client using Vertex API. The client gets the project and location from the
// environment variables `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`.
Client client = Client.builder().vertexAI(true).build();
ResponseStream<GenerateContentResponse> responseStream =
client.models.generateContentStream(
"gemini-2.0-flash-001", "Tell me a story in 300 words.", null);
System.out.println("Streaming response: ");
for (GenerateContentResponse res : responseStream) {
System.out.print(res.text());
}
// To save resources and avoid connection leaks, it is recommended to close the response
// stream after consumption (or using try block to get the response stream).
responseStream.close();
}
}