-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Vertex AI Java SDK samples using the Gemini large language model #8931
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
Merged
Merged
Changes from all commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
0d3f81b
Vertex AI Java SDK samples using the Gemini large language model
glaforge e3de1dd
Add missing license headers
glaforge b6a6561
Use environment variables for the selection of the project
glaforge aecdf26
Added tests
glaforge 3b50104
Add missing license headers in test classes
glaforge de94883
Use GOOGLE_CLOUD_PROJECT name for the project env var variable
glaforge 943ab72
Use String instead of StringBuilder when not appending multiple times.
glaforge ff1321b
Add JavaDocs to the methods
glaforge 046e029
Add VertexAI initialization reuse comment
glaforge e2d676c
Keep the default model configuration
glaforge de0a62c
Tidy up
glaforge d47b15c
Use the correct version number of the snapshot of the SDK, and update…
glaforge 5f58d4b
refactor files acc to samples standard
Sita04 1fee33f
lint fix
Sita04 0e5f7a7
Merge branch 'GoogleCloudPlatform:main' into master
glaforge 1946838
add new samples and refactor existing ones
Sita04 0e29c6b
Merge remote-tracking branch 'origin/master'
Sita04 1e450b8
update files for image data
Sita04 6fd815a
update acc to review comment
Sita04 7f5b614
update test file
Sita04 e678986
add region tags and minor patches
Sita04 4ee1b54
update region tags
Sita04 590e3d2
update version to match mvn release
Sita04 40f72e1
update image URIs and removed resource
Sita04 0bfca67
update streaming sample
Sita04 2488bbc
update test image protocol
Sita04 052e4f6
ignore testcase for multiturnmultimodal
Sita04 1e35b94
lint fix
Sita04 824c821
ignore Gemini tests
Sita04 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| <?xml version="1.0" encoding="UTF-8"?> | ||
| <!-- | ||
| Copyright 2023 Google Inc. | ||
|
|
||
| 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. | ||
| --> | ||
| <project xmlns="http://maven.apache.org/POM/4.0.0" | ||
| xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||
| xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | ||
| <modelVersion>4.0.0</modelVersion> | ||
| <packaging>jar</packaging> | ||
| <build> | ||
| <plugins> | ||
| <plugin> | ||
| <groupId>org.apache.maven.plugins</groupId> | ||
| <artifactId>maven-compiler-plugin</artifactId> | ||
| <configuration> | ||
| <source>9</source> | ||
| <target>9</target> | ||
| </configuration> | ||
| </plugin> | ||
| </plugins> | ||
| </build> | ||
| <version>1.0-SNAPSHOT</version> | ||
| <groupId>com.google.vertexai.gemini</groupId> | ||
| <artifactId>gemini-sample</artifactId> | ||
| <name>Google Cloud Vertex AI Gemini Snippets</name> | ||
|
|
||
| <!-- | ||
| The parent pom defines common style checks and testing strategies for our samples. | ||
| Removing or replacing it should not affect the execution of the samples in any way. | ||
| --> | ||
| <parent> | ||
| <groupId>com.google.cloud.samples</groupId> | ||
| <artifactId>shared-configuration</artifactId> | ||
| <version>1.2.0</version> | ||
| </parent> | ||
|
|
||
| <properties> | ||
| <maven.compiler.target>1.8</maven.compiler.target> | ||
| <maven.compiler.source>1.8</maven.compiler.source> | ||
| <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | ||
| </properties> | ||
|
|
||
| <dependencyManagement> | ||
| <dependencies> | ||
| <dependency> | ||
| <artifactId>libraries-bom</artifactId> | ||
| <groupId>com.google.cloud</groupId> | ||
| <scope>import</scope> | ||
| <type>pom</type> | ||
| <version>26.27.0</version> | ||
| </dependency> | ||
| </dependencies> | ||
| </dependencyManagement> | ||
|
|
||
| <dependencies> | ||
| <dependency> | ||
| <groupId>com.google.cloud</groupId> | ||
| <artifactId>google-cloud-vertexai</artifactId> | ||
| <version>0.1.0</version> | ||
| </dependency> | ||
|
|
||
| <!-- test dependencies --> | ||
| <dependency> | ||
| <groupId>junit</groupId> | ||
| <artifactId>junit</artifactId> | ||
| <version>4.13.2</version> | ||
| <scope>test</scope> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>com.google.truth</groupId> | ||
| <artifactId>truth</artifactId> | ||
| <version>1.1.5</version> | ||
| <scope>test</scope> | ||
| </dependency> | ||
| </dependencies> | ||
| </project> |
62 changes: 62 additions & 0 deletions
62
vertexai/snippets/src/main/java/vertexai/gemini/ChatDiscussion.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| /* | ||
| * 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 aiplatform_gemini_multiturn_chat] | ||
| import com.google.cloud.vertexai.VertexAI; | ||
| import com.google.cloud.vertexai.api.GenerateContentResponse; | ||
| import com.google.cloud.vertexai.generativeai.preview.ChatSession; | ||
| import com.google.cloud.vertexai.generativeai.preview.GenerativeModel; | ||
| import com.google.cloud.vertexai.generativeai.preview.ResponseHandler; | ||
| import java.io.IOException; | ||
|
|
||
| public class ChatDiscussion { | ||
|
|
||
| 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-pro-vision"; | ||
|
|
||
| chatDiscussion(projectId, location, modelName); | ||
| } | ||
|
|
||
| // Ask interrelated questions in a row using a ChatSession object. | ||
| public static void chatDiscussion(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)) { | ||
| GenerateContentResponse response; | ||
|
|
||
| GenerativeModel model = new GenerativeModel(modelName, vertexAI); | ||
| // Create a chat session to be used for interactive conversation. | ||
| ChatSession chatSession = new ChatSession(model); | ||
|
|
||
| response = chatSession.sendMessage("Hello."); | ||
| System.out.println(ResponseHandler.getText(response)); | ||
|
|
||
| response = chatSession.sendMessage("What are all the colors in a rainbow?"); | ||
| System.out.println(ResponseHandler.getText(response)); | ||
|
|
||
| response = chatSession.sendMessage("Why does it appear when it rains?"); | ||
| System.out.println(ResponseHandler.getText(response)); | ||
| System.out.println("Chat Ended."); | ||
| } | ||
| } | ||
| } | ||
| // [END aiplatform_gemini_multiturn_chat] |
79 changes: 79 additions & 0 deletions
79
vertexai/snippets/src/main/java/vertexai/gemini/MultiTurnMultimodal.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| /* | ||
| * 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.api.GenerationConfig; | ||
| import com.google.cloud.vertexai.generativeai.preview.ChatSession; | ||
| import com.google.cloud.vertexai.generativeai.preview.ContentMaker; | ||
| import com.google.cloud.vertexai.generativeai.preview.GenerativeModel; | ||
| import com.google.cloud.vertexai.generativeai.preview.PartMaker; | ||
| import com.google.cloud.vertexai.generativeai.preview.ResponseHandler; | ||
| import java.io.IOException; | ||
|
|
||
| public class MultiTurnMultimodal { | ||
|
|
||
| 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-ultra-vision"; | ||
|
|
||
| multiTurnMultimodal(projectId, location, modelName); | ||
| } | ||
|
|
||
| // Analyses the given multi-turn multimodal input. | ||
| public static void multiTurnMultimodal(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)) { | ||
| // Update the values for your query. | ||
| String firstTextPrompt = "What is this image"; | ||
| String imageUri = "gs://generativeai-downloads/images/scones.jpg"; | ||
| String secondTextPrompt = "what did I just show you"; | ||
|
|
||
| GenerationConfig generationConfig = | ||
| GenerationConfig.newBuilder() | ||
| .setMaxOutputTokens(2048) | ||
| .setTemperature(0.4F) | ||
| .setTopK(32) | ||
| .setTopP(1) | ||
| .build(); | ||
|
|
||
| GenerativeModel model = new GenerativeModel(modelName, generationConfig, vertexAI); | ||
| // For multi-turn responses, start a chat session. | ||
| ChatSession chatSession = model.startChat(); | ||
|
|
||
| GenerateContentResponse response; | ||
| // First message with multimodal input | ||
| response = chatSession.sendMessage(ContentMaker.fromMultiModalData( | ||
| firstTextPrompt, | ||
| PartMaker.fromMimeTypeAndData( | ||
| // Update Mime type according to your image. | ||
| "image/jpeg", | ||
kweinmeister marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| imageUri) | ||
| )); | ||
| System.out.println(ResponseHandler.getText(response)); | ||
|
|
||
| // Second message with text input | ||
| response = chatSession.sendMessage(secondTextPrompt); | ||
| System.out.println(ResponseHandler.getText(response)); | ||
| } | ||
| } | ||
| } | ||
94 changes: 94 additions & 0 deletions
94
vertexai/snippets/src/main/java/vertexai/gemini/MultimodalMultiImage.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| /* | ||
| * 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 aiplatform_gemini_single_turn_multi_image] | ||
| import com.google.cloud.vertexai.VertexAI; | ||
| import com.google.cloud.vertexai.api.Content; | ||
| import com.google.cloud.vertexai.api.GenerateContentResponse; | ||
| import com.google.cloud.vertexai.generativeai.preview.ContentMaker; | ||
| import com.google.cloud.vertexai.generativeai.preview.GenerativeModel; | ||
| import com.google.cloud.vertexai.generativeai.preview.PartMaker; | ||
| import com.google.cloud.vertexai.generativeai.preview.ResponseHandler; | ||
| import java.io.ByteArrayOutputStream; | ||
| import java.io.IOException; | ||
| import java.io.InputStream; | ||
| import java.net.HttpURLConnection; | ||
| import java.net.URL; | ||
|
|
||
| public class MultimodalMultiImage { | ||
|
|
||
| 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-pro-vision"; | ||
|
|
||
| multimodalMultiImage(projectId, location, modelName); | ||
| } | ||
|
|
||
| // Generates content from multiple input images. | ||
| public static void multimodalMultiImage(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); | ||
|
|
||
| Content content = ContentMaker.fromMultiModalData( | ||
| PartMaker.fromMimeTypeAndData("image/png", readImageFile( | ||
| "https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark1.png")), | ||
kweinmeister marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| "city: Rome, Landmark: the Colosseum", | ||
| PartMaker.fromMimeTypeAndData("image/png", readImageFile( | ||
| "https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark2.png")), | ||
| "city: Beijing, Landmark: Forbidden City", | ||
| PartMaker.fromMimeTypeAndData("image/png", readImageFile( | ||
| "https://storage.googleapis.com/cloud-samples-data/vertex-ai/llm/prompts/landmark3.png")) | ||
| ); | ||
|
|
||
| GenerateContentResponse response = model.generateContent(content); | ||
|
|
||
| String output = ResponseHandler.getText(response); | ||
| System.out.println(output); | ||
| } | ||
| } | ||
|
|
||
| // Reads the image data from the given URL. | ||
| public static byte[] readImageFile(String url) throws IOException { | ||
| URL urlObj = new URL(url); | ||
| HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); | ||
| connection.setRequestMethod("GET"); | ||
|
|
||
| int responseCode = connection.getResponseCode(); | ||
|
|
||
| if (responseCode == HttpURLConnection.HTTP_OK) { | ||
| InputStream inputStream = connection.getInputStream(); | ||
| ByteArrayOutputStream 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 RuntimeException("Error fetching file: " + responseCode); | ||
| } | ||
| } | ||
| } | ||
| // [END aiplatform_gemini_single_turn_multi_image] | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.