diff --git a/vertexai/snippets/pom.xml b/vertexai/snippets/pom.xml deleted file mode 100644 index b4a5764881b..00000000000 --- a/vertexai/snippets/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - 4.0.0 - jar - com.google.vertexai.gemini - gemini-sample - Google Cloud Vertex AI Gemini Snippets - - - - com.google.cloud.samples - shared-configuration - 1.2.0 - - - - 11 - 11 - UTF-8 - - - - - - libraries-bom - com.google.cloud - import - pom - 26.43.0 - - - - - - - com.google.cloud - google-cloud-vertexai - - - - - junit - junit - 4.13.2 - test - - - com.google.truth - truth - 1.4.0 - test - - - diff --git a/vertexai/snippets/src/main/java/vertexai/gemini/FunctionCalling.java b/vertexai/snippets/src/main/java/vertexai/gemini/FunctionCalling.java deleted file mode 100644 index 9a8019524eb..00000000000 --- a/vertexai/snippets/src/main/java/vertexai/gemini/FunctionCalling.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright 2024 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 vertexai.gemini; - -import com.google.cloud.vertexai.VertexAI; -import com.google.cloud.vertexai.api.Content; -import com.google.cloud.vertexai.api.FunctionDeclaration; -import com.google.cloud.vertexai.api.GenerateContentResponse; -import com.google.cloud.vertexai.api.Schema; -import com.google.cloud.vertexai.api.Tool; -import com.google.cloud.vertexai.api.Type; -import com.google.cloud.vertexai.generativeai.ChatSession; -import com.google.cloud.vertexai.generativeai.ContentMaker; -import com.google.cloud.vertexai.generativeai.GenerativeModel; -import com.google.cloud.vertexai.generativeai.PartMaker; -import com.google.cloud.vertexai.generativeai.ResponseHandler; -import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; - -public class FunctionCalling { - public static void main(String[] args) throws IOException { - // TODO(developer): Replace these variables before running the sample. - String projectId = "your-google-cloud-project-id"; - String location = "us-central1"; - String modelName = "gemini-2.5-flash"; - - String promptText = "What's the weather like in Paris?"; - - whatsTheWeatherLike(projectId, location, modelName, promptText); - } - - // A request involving the interaction with an external tool - public static String whatsTheWeatherLike(String projectId, String location, - String modelName, String promptText) - 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 (VertexAI vertexAI = new VertexAI(projectId, location)) { - - FunctionDeclaration functionDeclaration = FunctionDeclaration.newBuilder() - .setName("getCurrentWeather") - .setDescription("Get the current weather in a given location") - .setParameters( - Schema.newBuilder() - .setType(Type.OBJECT) - .putProperties("location", Schema.newBuilder() - .setType(Type.STRING) - .setDescription("location") - .build() - ) - .addRequired("location") - .build() - ) - .build(); - - System.out.println("Function declaration:"); - System.out.println(functionDeclaration); - - // Add the function to a "tool" - Tool tool = Tool.newBuilder() - .addFunctionDeclarations(functionDeclaration) - .build(); - - // Start a chat session from a model, with the use of the declared function. - GenerativeModel model = new GenerativeModel(modelName, vertexAI) - .withTools(Arrays.asList(tool)); - ChatSession chat = model.startChat(); - - System.out.println(String.format("Ask the question: %s", promptText)); - GenerateContentResponse response = chat.sendMessage(promptText); - - // The model will most likely return a function call to the declared - // function `getCurrentWeather` with "Paris" as the value for the - // argument `location`. - System.out.println("\nPrint response: "); - System.out.println(ResponseHandler.getContent(response)); - - // Provide an answer to the model so that it knows what the result - // of a "function call" is. - Content content = - ContentMaker.fromMultiModalData( - PartMaker.fromFunctionResponse( - "getCurrentWeather", - Collections.singletonMap("currentWeather", "sunny"))); - System.out.println("Provide the function response: "); - System.out.println(content); - response = chat.sendMessage(content); - - // See what the model replies now - System.out.println("Print response: "); - String finalAnswer = ResponseHandler.getText(response); - System.out.println(finalAnswer); - - return finalAnswer; - } - } -} diff --git a/vertexai/snippets/src/main/java/vertexai/gemini/GetTokenCount.java b/vertexai/snippets/src/main/java/vertexai/gemini/GetTokenCount.java deleted file mode 100644 index 81835b64d36..00000000000 --- a/vertexai/snippets/src/main/java/vertexai/gemini/GetTokenCount.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2023 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 vertexai.gemini; - -// [START generativeaionvertexai_gemini_token_count] -import com.google.cloud.vertexai.VertexAI; -import com.google.cloud.vertexai.api.CountTokensResponse; -import com.google.cloud.vertexai.api.GenerateContentResponse; -import com.google.cloud.vertexai.generativeai.GenerativeModel; -import java.io.IOException; - -public class GetTokenCount { - public static void main(String[] args) throws IOException { - // TODO(developer): Replace these variables before running the sample. - String projectId = "your-google-cloud-project-id"; - String location = "us-central1"; - String modelName = "gemini-2.5-flash"; - - getTokenCount(projectId, location, modelName); - } - - // Gets the number of tokens for the prompt and the model's response. - public static int getTokenCount(String projectId, String location, String modelName) - 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 (VertexAI vertexAI = new VertexAI(projectId, location)) { - GenerativeModel model = new GenerativeModel(modelName, vertexAI); - - String textPrompt = "Why is the sky blue?"; - CountTokensResponse response = model.countTokens(textPrompt); - - int promptTokenCount = response.getTotalTokens(); - int promptCharCount = response.getTotalBillableCharacters(); - - System.out.println("Prompt token Count: " + promptTokenCount); - System.out.println("Prompt billable character count: " + promptCharCount); - - GenerateContentResponse contentResponse = model.generateContent(textPrompt); - - int tokenCount = contentResponse.getUsageMetadata().getPromptTokenCount(); - int candidateTokenCount = contentResponse.getUsageMetadata().getCandidatesTokenCount(); - int totalTokenCount = contentResponse.getUsageMetadata().getTotalTokenCount(); - - System.out.println("Prompt token Count: " + tokenCount); - System.out.println("Candidate Token Count: " + candidateTokenCount); - System.out.println("Total token Count: " + totalTokenCount); - - return promptTokenCount; - } - } -} -// [END generativeaionvertexai_gemini_token_count] diff --git a/vertexai/snippets/src/main/java/vertexai/gemini/Multimodal.java b/vertexai/snippets/src/main/java/vertexai/gemini/Multimodal.java deleted file mode 100644 index c9b22e4a14b..00000000000 --- a/vertexai/snippets/src/main/java/vertexai/gemini/Multimodal.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2024 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 vertexai.gemini; - -// [START generativeaionvertexai_non_stream_multimodality_basic] -import com.google.cloud.vertexai.VertexAI; -import com.google.cloud.vertexai.api.GenerateContentResponse; -import com.google.cloud.vertexai.generativeai.ContentMaker; -import com.google.cloud.vertexai.generativeai.GenerativeModel; -import com.google.cloud.vertexai.generativeai.PartMaker; -import com.google.cloud.vertexai.generativeai.ResponseHandler; - -public class Multimodal { - public static void main(String[] args) throws Exception { - // TODO(developer): Replace these variables before running the sample. - String projectId = "your-google-cloud-project-id"; - String location = "us-central1"; - String modelName = "gemini-2.5-flash"; - - String output = nonStreamingMultimodal(projectId, location, modelName); - System.out.println(output); - } - - // Ask a simple question and get the response. - public static String nonStreamingMultimodal(String projectId, String location, String modelName) - throws Exception { - // 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 (VertexAI vertexAI = new VertexAI(projectId, location)) { - GenerativeModel model = new GenerativeModel(modelName, vertexAI); - - String videoUri = "gs://cloud-samples-data/video/animals.mp4"; - String imgUri = "gs://cloud-samples-data/generative-ai/image/character.jpg"; - - // Get the response from the model. - GenerateContentResponse response = model.generateContent( - ContentMaker.fromMultiModalData( - PartMaker.fromMimeTypeAndData("video/mp4", videoUri), - PartMaker.fromMimeTypeAndData("image/jpeg", imgUri), - "Are this video and image correlated?" - )); - - // Extract the generated text from the model's response. - String output = ResponseHandler.getText(response); - return output; - } - } -} -// [END generativeaionvertexai_non_stream_multimodality_basic] \ No newline at end of file diff --git a/vertexai/snippets/src/main/java/vertexai/gemini/QuestionAnswer.java b/vertexai/snippets/src/main/java/vertexai/gemini/QuestionAnswer.java deleted file mode 100644 index 19766948d03..00000000000 --- a/vertexai/snippets/src/main/java/vertexai/gemini/QuestionAnswer.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2023 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 vertexai.gemini; - -import com.google.cloud.vertexai.VertexAI; -import com.google.cloud.vertexai.api.GenerateContentResponse; -import com.google.cloud.vertexai.generativeai.GenerativeModel; -import com.google.cloud.vertexai.generativeai.ResponseHandler; - -public class QuestionAnswer { - - public static void main(String[] args) throws Exception { - // TODO(developer): Replace these variables before running the sample. - String projectId = "your-google-cloud-project-id"; - String location = "us-central1"; - String modelName = "gemini-2.5-flash"; - - String output = simpleQuestion(projectId, location, modelName); - System.out.println(output); - } - - // Asks a question to the specified Vertex AI Gemini model and returns the generated answer. - public static String simpleQuestion(String projectId, String location, String modelName) - throws Exception { - // 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 (VertexAI vertexAI = new VertexAI(projectId, location)) { - String output; - GenerativeModel model = new GenerativeModel(modelName, vertexAI); - // Send the question to the model for processing. - GenerateContentResponse response = model.generateContent("Why is the sky blue?"); - // Extract the generated text from the model's response. - output = ResponseHandler.getText(response); - return output; - } - } -} \ No newline at end of file diff --git a/vertexai/snippets/src/main/java/vertexai/gemini/Quickstart.java b/vertexai/snippets/src/main/java/vertexai/gemini/Quickstart.java deleted file mode 100644 index 910d74aa71e..00000000000 --- a/vertexai/snippets/src/main/java/vertexai/gemini/Quickstart.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2023 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 vertexai.gemini; - -// [START generativeaionvertexai_gemini_get_started] -import com.google.cloud.vertexai.VertexAI; -import com.google.cloud.vertexai.api.GenerateContentResponse; -import com.google.cloud.vertexai.generativeai.ContentMaker; -import com.google.cloud.vertexai.generativeai.GenerativeModel; -import com.google.cloud.vertexai.generativeai.PartMaker; -import java.io.IOException; - -public class Quickstart { - - public static void main(String[] args) throws IOException { - // TODO(developer): Replace these variables before running the sample. - String projectId = "your-google-cloud-project-id"; - String location = "us-central1"; - String modelName = "gemini-2.5-flash"; - - String output = quickstart(projectId, location, modelName); - System.out.println(output); - } - - // Analyzes the provided Multimodal input. - public static String quickstart(String projectId, String location, String modelName) - 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 (VertexAI vertexAI = new VertexAI(projectId, location)) { - String imageUri = "gs://generativeai-downloads/images/scones.jpg"; - - GenerativeModel model = new GenerativeModel(modelName, vertexAI); - GenerateContentResponse response = model.generateContent(ContentMaker.fromMultiModalData( - PartMaker.fromMimeTypeAndData("image/png", imageUri), - "What's in this photo" - )); - - return response.toString(); - } - } -} -// [END generativeaionvertexai_gemini_get_started] diff --git a/vertexai/snippets/src/main/java/vertexai/gemini/StreamingMultimodal.java b/vertexai/snippets/src/main/java/vertexai/gemini/StreamingMultimodal.java deleted file mode 100644 index 9e756abcb9f..00000000000 --- a/vertexai/snippets/src/main/java/vertexai/gemini/StreamingMultimodal.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2024 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 vertexai.gemini; - -// [START generativeaionvertexai_stream_multimodality_basic] -import com.google.cloud.vertexai.VertexAI; -import com.google.cloud.vertexai.generativeai.ContentMaker; -import com.google.cloud.vertexai.generativeai.GenerativeModel; -import com.google.cloud.vertexai.generativeai.PartMaker; - -public class StreamingMultimodal { - public static void main(String[] args) throws Exception { - // TODO(developer): Replace these variables before running the sample. - String projectId = "your-google-cloud-project-id"; - String location = "us-central1"; - String modelName = "gemini-2.5-flash"; - - streamingMultimodal(projectId, location, modelName); - } - - // Ask a simple question and get the response via streaming. - public static void streamingMultimodal(String projectId, String location, String modelName) - throws Exception { - // 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 (VertexAI vertexAI = new VertexAI(projectId, location)) { - GenerativeModel model = new GenerativeModel(modelName, vertexAI); - - String videoUri = "gs://cloud-samples-data/video/animals.mp4"; - String imgUri = "gs://cloud-samples-data/generative-ai/image/character.jpg"; - - // Stream the result. - model.generateContentStream( - ContentMaker.fromMultiModalData( - PartMaker.fromMimeTypeAndData("video/mp4", videoUri), - PartMaker.fromMimeTypeAndData("image/jpeg", imgUri), - "Are this video and image correlated?" - )) - .stream() - .forEach(System.out::println); - } - } -} -// [END generativeaionvertexai_stream_multimodality_basic] \ No newline at end of file diff --git a/vertexai/snippets/src/main/java/vertexai/gemini/StreamingQuestionAnswer.java b/vertexai/snippets/src/main/java/vertexai/gemini/StreamingQuestionAnswer.java deleted file mode 100644 index a8a1db35309..00000000000 --- a/vertexai/snippets/src/main/java/vertexai/gemini/StreamingQuestionAnswer.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2023 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 vertexai.gemini; - -// [START generativeaionvertexai_stream_text_basic] -import com.google.cloud.vertexai.VertexAI; -import com.google.cloud.vertexai.generativeai.GenerativeModel; - -public class StreamingQuestionAnswer { - - public static void main(String[] args) throws Exception { - // TODO(developer): Replace these variables before running the sample. - String projectId = "your-google-cloud-project-id"; - String location = "us-central1"; - String modelName = "gemini-2.5-flash"; - - streamingQuestion(projectId, location, modelName); - } - - // Ask a simple question and get the response via streaming. - public static void streamingQuestion(String projectId, String location, String modelName) - throws Exception { - // 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 (VertexAI vertexAI = new VertexAI(projectId, location)) { - GenerativeModel model = new GenerativeModel(modelName, vertexAI); - - // Stream the result. - model.generateContentStream("Write a story about a magic backpack.") - .stream() - .forEach(System.out::println); - - System.out.println("Streaming complete."); - } - } -} -// [END generativeaionvertexai_stream_text_basic] \ No newline at end of file diff --git a/vertexai/snippets/src/main/java/vertexai/gemini/TextInput.java b/vertexai/snippets/src/main/java/vertexai/gemini/TextInput.java deleted file mode 100644 index 9f17e04d8b4..00000000000 --- a/vertexai/snippets/src/main/java/vertexai/gemini/TextInput.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2024 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 vertexai.gemini; - -import com.google.cloud.vertexai.VertexAI; -import com.google.cloud.vertexai.api.GenerateContentResponse; -import com.google.cloud.vertexai.generativeai.GenerativeModel; -import com.google.cloud.vertexai.generativeai.ResponseHandler; -import java.io.IOException; - -public class TextInput { - - public static void main(String[] args) throws IOException { - // TODO(developer): Replace these variables before running the sample. - String projectId = "your-google-cloud-project-id"; - String location = "us-central1"; - String modelName = "gemini-2.5-flash"; - String textPrompt = - "What's a good name for a flower shop that specializes in selling bouquets of" - + " dried flowers?"; - - String output = textInput(projectId, location, modelName, textPrompt); - System.out.println(output); - } - - // Passes the provided text input to the Gemini model and returns the text-only response. - // For the specified textPrompt, the model returns a list of possible store names. - public static String textInput( - String projectId, String location, String modelName, String textPrompt) 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 (VertexAI vertexAI = new VertexAI(projectId, location)) { - GenerativeModel model = new GenerativeModel(modelName, vertexAI); - - GenerateContentResponse response = model.generateContent(textPrompt); - String output = ResponseHandler.getText(response); - return output; - } - } -} \ No newline at end of file diff --git a/vertexai/snippets/src/main/java/vertexai/gemini/VideoInputWithAudio.java b/vertexai/snippets/src/main/java/vertexai/gemini/VideoInputWithAudio.java deleted file mode 100644 index fd65ff36ecf..00000000000 --- a/vertexai/snippets/src/main/java/vertexai/gemini/VideoInputWithAudio.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2024 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 vertexai.gemini; - -// [START generativeaionvertexai_gemini_video_with_audio] - -import com.google.cloud.vertexai.VertexAI; -import com.google.cloud.vertexai.api.GenerateContentResponse; -import com.google.cloud.vertexai.generativeai.ContentMaker; -import com.google.cloud.vertexai.generativeai.GenerativeModel; -import com.google.cloud.vertexai.generativeai.PartMaker; -import com.google.cloud.vertexai.generativeai.ResponseHandler; -import java.io.IOException; - -public class VideoInputWithAudio { - - public static void main(String[] args) throws IOException { - // TODO(developer): Replace these variables before running the sample. - String projectId = "your-google-cloud-project-id"; - String location = "us-central1"; - String modelName = "gemini-2.5-flash"; - - videoAudioInput(projectId, location, modelName); - } - - // Analyzes the given video input, including its audio track. - public static String videoAudioInput(String projectId, String location, String modelName) - 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 (VertexAI vertexAI = new VertexAI(projectId, location)) { - String videoUri = "gs://cloud-samples-data/generative-ai/video/pixel8.mp4"; - - GenerativeModel model = new GenerativeModel(modelName, vertexAI); - GenerateContentResponse response = model.generateContent( - ContentMaker.fromMultiModalData( - "Provide a description of the video.\n The description should also " - + "contain anything important which people say in the video.", - PartMaker.fromMimeTypeAndData("video/mp4", videoUri) - )); - - String output = ResponseHandler.getText(response); - System.out.println(output); - - return output; - } - } -} -// [END generativeaionvertexai_gemini_video_with_audio] diff --git a/vertexai/snippets/src/test/java/vertexai/gemini/SnippetsIT.java b/vertexai/snippets/src/test/java/vertexai/gemini/SnippetsIT.java deleted file mode 100644 index df7cd40ad3f..00000000000 --- a/vertexai/snippets/src/test/java/vertexai/gemini/SnippetsIT.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright 2023 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. - */ - -// Tests for Gemini code samples. - -package vertexai.gemini; - -import static com.google.common.truth.Truth.assertThat; -import static com.google.common.truth.Truth.assertWithMessage; - -import com.google.cloud.testing.junit4.MultipleAttemptsRule; -import com.google.gson.Gson; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Arrays; -import java.util.stream.Collectors; -import javax.net.ssl.HttpsURLConnection; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -@RunWith(JUnit4.class) -public class SnippetsIT { - - private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); - private static final String LOCATION = "us-central1"; - private static final String GEMINI_FLASH = "gemini-2.5-flash"; - private static final int MAX_ATTEMPT_COUNT = 3; - private static final int INITIAL_BACKOFF_MILLIS = 120000; - - - // 2 minutes - - @Rule - public final MultipleAttemptsRule multipleAttemptsRule = - new MultipleAttemptsRule(MAX_ATTEMPT_COUNT, INITIAL_BACKOFF_MILLIS); - - private final PrintStream printStream = System.out; - private ByteArrayOutputStream bout; - - // Check if the required environment variables are set. - public static void requireEnvVar(String envVarName) { - assertWithMessage(String.format("Missing environment variable '%s' ", envVarName)) - .that(System.getenv(envVarName)) - .isNotEmpty(); - } - - @BeforeClass - public static void setUp() throws IOException { - try (PrintStream out = System.out) { - ByteArrayOutputStream stdOut = new ByteArrayOutputStream(); - System.setOut(new PrintStream(stdOut)); - - requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); - requireEnvVar("GOOGLE_CLOUD_PROJECT"); - - stdOut.close(); - System.setOut(out); - } - } - - // Reads the image data from the given URL. - public static byte[] readImageFile(String url) throws IOException { - if (url == null || url.isEmpty()) { - throw new IllegalArgumentException("Invalid URL: " + url); - } - URL urlObj = new URL(url); - HttpsURLConnection connection = null; - InputStream inputStream = null; - ByteArrayOutputStream outputStream = null; - - try { - connection = (HttpsURLConnection) urlObj.openConnection(); - connection.setRequestMethod("GET"); - - int responseCode = connection.getResponseCode(); - if (responseCode == HttpURLConnection.HTTP_OK) { - inputStream = connection.getInputStream(); - outputStream = new ByteArrayOutputStream(); - - byte[] buffer = new byte[1024]; - int bytesRead; - while ((bytesRead = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, bytesRead); - } - return outputStream.toByteArray(); - } else { - throw new IOException("Error fetching file: " + responseCode); - } - } finally { - if (inputStream != null) { - inputStream.close(); - } - if (outputStream != null) { - outputStream.close(); - } - if (connection != null) { - connection.disconnect(); - } - } - } - - @Before - public void beforeEach() { - bout = new ByteArrayOutputStream(); - System.setOut(new PrintStream(bout)); - } - - @After - public void afterEach() { - System.out.flush(); - System.setOut(printStream); - } - - @Test - public void testSimpleQuestionAnswer() throws Exception { - String output = QuestionAnswer.simpleQuestion(PROJECT_ID, LOCATION, GEMINI_FLASH); - assertThat(output).isNotEmpty(); - } - - @Test - public void testQuickstart() throws IOException { - String output = Quickstart.quickstart(PROJECT_ID, LOCATION, GEMINI_FLASH); - assertThat(output).isNotEmpty(); - } - - @Test - public void testStreamingQuestions() throws Exception { - StreamingQuestionAnswer.streamingQuestion(PROJECT_ID, LOCATION, GEMINI_FLASH); - assertThat(bout.toString()).isNotEmpty(); - } - - @Test - public void testTextInput() throws Exception { - String textPrompt = - "What's a good name for a flower shop that specializes in selling bouquets of" - + " dried flowers?"; - String output = TextInput.textInput(PROJECT_ID, LOCATION, GEMINI_FLASH, textPrompt); - assertThat(output).isNotEmpty(); - } - - @Test - public void testTokenCount() throws Exception { - int tokenCount = GetTokenCount.getTokenCount(PROJECT_ID, LOCATION, GEMINI_FLASH); - assertThat(tokenCount).isEqualTo(6); - } - - @Test - public void testFunctionCalling() throws Exception { - String textPrompt = "What's the weather in Paris?"; - - String answer = - FunctionCalling.whatsTheWeatherLike(PROJECT_ID, LOCATION, GEMINI_FLASH, textPrompt); - assertThat(answer).ignoringCase().contains("Paris"); - assertThat(answer).ignoringCase().contains("sunny"); - } - - @Test - public void testVideoAudioInput() throws IOException { - String output = VideoInputWithAudio.videoAudioInput(PROJECT_ID, LOCATION, GEMINI_FLASH); - - assertThat(output).ignoringCase().contains("Pixel"); - assertThat(output).ignoringCase().contains("Tokyo"); - } - - @Test - public void testMultimodalStreaming() throws Exception { - StreamingMultimodal.streamingMultimodal(PROJECT_ID, LOCATION, GEMINI_FLASH); - assertThat(bout.toString()).ignoringCase().contains("no"); - } - - @Test - public void testMultimodalNonStreaming() throws Exception { - String output = Multimodal.nonStreamingMultimodal(PROJECT_ID, LOCATION, GEMINI_FLASH); - - assertThat(output).ignoringCase().contains("no"); - } -}