Skip to content

Commit 79b4a90

Browse files
authored
feat: add gemini code sample and test for text-only input (GoogleCloudPlatform#9310)
* feat: add gemini code sample and test for text-only input * address feedback * fix test
1 parent 0387ba1 commit 79b4a90

File tree

2 files changed

+105
-17
lines changed

2 files changed

+105
-17
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*
2+
* Copyright 2024 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+
/*
18+
* laishers. "A New Era in Cartoon History." Review of Steamboat Willie.
19+
* 4 January 2001. https://www.imdb.com/review/rw0005574/?ref_=rw_urv
20+
*/
21+
22+
package vertexai.gemini;
23+
24+
// [START generativeaionvertexai_gemini_generate_from_text_input]
25+
import com.google.cloud.vertexai.VertexAI;
26+
import com.google.cloud.vertexai.api.GenerateContentResponse;
27+
import com.google.cloud.vertexai.generativeai.GenerativeModel;
28+
import com.google.cloud.vertexai.generativeai.ResponseHandler;
29+
import java.io.IOException;
30+
31+
public class TextInput {
32+
33+
public static void main(String[] args) throws IOException {
34+
// TODO(developer): Replace these variables before running the sample.
35+
String projectId = "your-google-cloud-project-id";
36+
String location = "us-central1";
37+
String modelName = "gemini-1.0-pro-002";
38+
// Movie review from https://www.imdb.com/review/rw0005574/?ref_=rw_urv.
39+
// Does the returned sentiment score match the reviewer's movie rating?
40+
String textPrompt =
41+
"Give a score from 1 - 10 to suggest if the following movie review is negative or positive"
42+
+ " (1 is most negative, 10 is most positive, 5 will be neutral). Include an"
43+
+ " explanation.\n"
44+
+ "This era was not just the dawn of sound in cartoons, but of a cartoon character"
45+
+ " which would go down in history as the world's most famous mouse. Yes, Mickey makes"
46+
+ " his debut here, in this cheery tale of life on board a steamboat. The animation is"
47+
+ " good for it's time, and the plot - though a little simple - is quite jolly. A true"
48+
+ " classic, and if you ever manage to get it on video, you won't regret it.";
49+
50+
String output = textInput(projectId, location, modelName, textPrompt);
51+
System.out.println(output);
52+
}
53+
54+
// Passes the provided text input to the Gemini model and returns the text-only response.
55+
// For the specified textPrompt, the model returns a sentiment score for the given movie review.
56+
public static String textInput(
57+
String projectId, String location, String modelName, String textPrompt) throws IOException {
58+
// Initialize client that will be used to send requests. This client only needs
59+
// to be created once, and can be reused for multiple requests.
60+
try (VertexAI vertexAI = new VertexAI(projectId, location)) {
61+
String output;
62+
GenerativeModel model = new GenerativeModel(modelName, vertexAI);
63+
64+
GenerateContentResponse response = model.generateContent(textPrompt);
65+
output = ResponseHandler.getText(response);
66+
return output;
67+
}
68+
}
69+
}
70+
// [END generativeaionvertexai_gemini_generate_from_text_input]

vertexai/snippets/src/test/java/vertexai/gemini/SnippetsIT.java

Lines changed: 35 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,11 @@ public class SnippetsIT {
5050
private static final String GEMINI_PRO_1_5 = "gemini-1.5-pro-preview-0409";
5151
private static final int MAX_ATTEMPT_COUNT = 3;
5252
private static final int INITIAL_BACKOFF_MILLIS = 120000; // 2 minutes
53+
5354
@Rule
54-
public final MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(
55-
MAX_ATTEMPT_COUNT,
56-
INITIAL_BACKOFF_MILLIS);
55+
public final MultipleAttemptsRule multipleAttemptsRule =
56+
new MultipleAttemptsRule(MAX_ATTEMPT_COUNT, INITIAL_BACKOFF_MILLIS);
57+
5758
private final PrintStream printStream = System.out;
5859
private ByteArrayOutputStream bout;
5960

@@ -145,10 +146,11 @@ public void testMultimodalMultiImage() throws IOException {
145146

146147
@Test
147148
public void testMultimodalQuery() throws Exception {
148-
String imageUri = "https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark1.png";
149+
String imageUri =
150+
"https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark1.png";
149151
String dataImageBase64 = Base64.getEncoder().encodeToString(readImageFile(imageUri));
150-
String output = MultimodalQuery.multimodalQuery(PROJECT_ID, LOCATION, GEMINI_PRO_VISION,
151-
dataImageBase64);
152+
String output =
153+
MultimodalQuery.multimodalQuery(PROJECT_ID, LOCATION, GEMINI_PRO_VISION, dataImageBase64);
152154
assertThat(output).isNotEmpty();
153155
}
154156

@@ -180,26 +182,42 @@ public void testQuickstart() throws IOException {
180182

181183
@Test
182184
public void testSingleTurnMultimodal() throws IOException {
183-
String imageUri = "https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark1.png";
185+
String imageUri =
186+
"https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark1.png";
184187
String dataImageBase64 = Base64.getEncoder().encodeToString(readImageFile(imageUri));
185-
SingleTurnMultimodal.generateContent(PROJECT_ID, LOCATION, GEMINI_PRO_VISION,
186-
"What is this image", dataImageBase64);
188+
SingleTurnMultimodal.generateContent(
189+
PROJECT_ID, LOCATION, GEMINI_PRO_VISION, "What is this image", dataImageBase64);
187190
assertThat(bout.toString()).contains("Colosseum");
188191
}
189192

190193
@Test
191194
public void testStreamingQuestions() throws Exception {
192-
StreamingQuestionAnswer.streamingQuestion(PROJECT_ID, LOCATION,
193-
GEMINI_PRO_VISION);
195+
StreamingQuestionAnswer.streamingQuestion(PROJECT_ID, LOCATION, GEMINI_PRO_VISION);
194196
assertThat(bout.toString()).contains("Rayleigh scattering");
195197
}
196198

199+
@Test
200+
public void testTextInput() throws Exception {
201+
String textPrompt =
202+
"Give a score from 1 - 10 to suggest if the following movie review is negative or positive"
203+
+ " (1 is most negative, 10 is most positive, 5 will be neutral). Include an"
204+
+ " explanation.\n"
205+
+ "This era was not just the dawn of sound in cartoons, but of a cartoon character"
206+
+ " which would go down in history as the world's most famous mouse. Yes, Mickey makes"
207+
+ " his debut here, in this cheery tale of life on board a steamboat. The animation is"
208+
+ " good for it's time, and the plot - though a little simple - is quite jolly. A true"
209+
+ " classic, and if you ever manage to get it on video, you won't regret it.";
210+
String output = TextInput.textInput(PROJECT_ID, LOCATION, GEMINI_PRO, textPrompt);
211+
assertThat(output).isNotEmpty();
212+
assertThat(output).contains("positive");
213+
}
214+
197215
@Test
198216
public void testSafetySettings() throws Exception {
199217
String textPrompt = "Hello World!";
200218

201-
String output = WithSafetySettings.safetyCheck(PROJECT_ID, LOCATION, GEMINI_PRO_VISION,
202-
textPrompt);
219+
String output =
220+
WithSafetySettings.safetyCheck(PROJECT_ID, LOCATION, GEMINI_PRO_VISION, textPrompt);
203221
assertThat(output).isNotEmpty();
204222
assertThat(output).contains("reasons?");
205223
}
@@ -208,17 +226,17 @@ public void testSafetySettings() throws Exception {
208226
public void testTokenCount() throws Exception {
209227
String textPrompt = "Why is the sky blue?";
210228

211-
int tokenCount = GetTokenCount.getTokenCount(PROJECT_ID, LOCATION, GEMINI_PRO_VISION,
212-
textPrompt);
229+
int tokenCount =
230+
GetTokenCount.getTokenCount(PROJECT_ID, LOCATION, GEMINI_PRO_VISION, textPrompt);
213231
assertThat(tokenCount).isEqualTo(6);
214232
}
215233

216234
@Test
217235
public void testFunctionCalling() throws Exception {
218236
String textPrompt = "What's the weather in Paris?";
219237

220-
String answer = FunctionCalling.whatsTheWeatherLike(PROJECT_ID, LOCATION, GEMINI_PRO,
221-
textPrompt);
238+
String answer =
239+
FunctionCalling.whatsTheWeatherLike(PROJECT_ID, LOCATION, GEMINI_PRO, textPrompt);
222240
assertThat(answer).ignoringCase().contains("Paris");
223241
assertThat(answer).ignoringCase().contains("sunny");
224242
}

0 commit comments

Comments
 (0)