diff --git a/java-examples/GenerateContent.java b/java-examples/GenerateContent.java new file mode 100644 index 0000000..ee03710 --- /dev/null +++ b/java-examples/GenerateContent.java @@ -0,0 +1,58 @@ +/* + * 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: + * + *

1a. If you are using Vertex AI, setup ADC to get credentials: + * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp + * + *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: + * + *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT + * + *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION + * + *

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 + * + *

export GOOGLE_API_KEY=YOUR_API_KEY + * + *

2. Compile the java package and run the sample code. + * + *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContent" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.GenerateContentResponse; +import java.io.IOException; +import org.apache.http.HttpException; + +/** An example of using the Unified Gen AI Java SDK to generate content. */ +public class GenerateContent { + public static void main(String[] args) throws IOException, HttpException { + // Instantiate the client. The client by default uses the Gemini Developer API. It gets the API + // key from the environment variable `GOOGLE_API_KEY`. + Client client = new Client(); + + GenerateContentResponse response = + client.models.generateContent("gemini-2.0-flash-001", "What is your name?", null); + + // Gets the text string from the response by the quick accessor method `text()`. + System.out.println("Unary response: " + response.text()); + } +} diff --git a/java-examples/GenerateContentAsync.java b/java-examples/GenerateContentAsync.java new file mode 100644 index 0000000..df0786e --- /dev/null +++ b/java-examples/GenerateContentAsync.java @@ -0,0 +1,63 @@ +/* + * 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: + * + *

1a. If you are using Vertex AI, setup ADC to get credentials: + * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp + * + *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: + * + *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT + * + *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION + * + *

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 + * + *

export GOOGLE_API_KEY=YOUR_API_KEY + * + *

2. Compile the java package and run the sample code. + * + *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContentAsync" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.GenerateContentResponse; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import org.apache.http.HttpException; + +/** An example of using the Unified Gen AI Java SDK to generate content asynchronously. */ +public class GenerateContentAsync { + public static void main(String[] args) throws IOException, HttpException { + // Instantiates the client using Gemini Developer API, and sets the API key in the builder. + Client client = Client.builder().apiKey(System.getenv("GOOGLE_API_KEY")).build(); + + CompletableFuture responseFuture = + client.async.models.generateContent( + "gemini-2.0-flash-001", "Introduce Google AI Studio.", null); + + responseFuture + .thenAccept( + response -> { + System.out.println("Async response: " + response.text()); + }) + .join(); + } +} diff --git a/java-examples/GenerateContentStream.java b/java-examples/GenerateContentStream.java new file mode 100644 index 0000000..f82cef2 --- /dev/null +++ b/java-examples/GenerateContentStream.java @@ -0,0 +1,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: + * + *

1a. If you are using Vertex AI, setup ADC to get credentials: + * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp + * + *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: + * + *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT + * + *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION + * + *

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 + * + *

export GOOGLE_API_KEY=YOUR_API_KEY + * + *

2. Compile the java package and run the sample code. + * + *

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 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(); + } +} diff --git a/java-examples/GenerateContentWithConfigs.java b/java-examples/GenerateContentWithConfigs.java new file mode 100644 index 0000000..300ddd1 --- /dev/null +++ b/java-examples/GenerateContentWithConfigs.java @@ -0,0 +1,95 @@ +/* + * 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: + * + *

1a. If you are using Vertex AI, setup ADC to get credentials: + * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp + * + *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: + * + *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT + * + *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION + * + *

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 + * + *

export GOOGLE_API_KEY=YOUR_API_KEY + * + *

2. Compile the java package and run the sample code. + * + *

mvn clean compile + * + *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContentWithConfigs" + */ +package com.google.genai.examples; + +import com.google.common.collect.ImmutableList; +import com.google.genai.Client; +import com.google.genai.types.Content; +import com.google.genai.types.GenerateContentConfig; +import com.google.genai.types.GenerateContentResponse; +import com.google.genai.types.GoogleSearch; +import com.google.genai.types.Part; +import com.google.genai.types.SafetySetting; +import com.google.genai.types.Tool; +import java.io.IOException; +import org.apache.http.HttpException; + +/** An example of using the Unified Gen AI Java SDK to generate content with extra configs. */ +public class GenerateContentWithConfigs { + public static void main(String[] args) throws IOException, HttpException { + // Instantiate the client using Gemini Developer API. + Client client = new Client(); + + // Sets the safety settings in the config. + ImmutableList safetySettings = + ImmutableList.of( + SafetySetting.builder() + .category("HARM_CATEGORY_HATE_SPEECH") + .threshold("BLOCK_ONLY_HIGH") + .build(), + SafetySetting.builder() + .category("HARM_CATEGORY_DANGEROUS_CONTENT") + .threshold("BLOCK_LOW_AND_ABOVE") + .build()); + + // Sets the system instruction in the config. + Content systemInstruction = + Content.builder() + .parts(ImmutableList.of(Part.builder().text("Answer as concisely as possible").build())) + .build(); + + // Sets the Google Search tool in the config. + Tool googleSearchTool = Tool.builder().googleSearch(GoogleSearch.builder().build()).build(); + + GenerateContentConfig config = + GenerateContentConfig.builder() + .candidateCount(1) + .maxOutputTokens(1024) + .safetySettings(safetySettings) + .systemInstruction(systemInstruction) + .tools(ImmutableList.of(googleSearchTool)) + .build(); + + GenerateContentResponse response = + client.models.generateContent("gemini-2.0-flash-001", "Tell me the history of LLM", config); + + System.out.println("Response: " + response.text()); + } +} diff --git a/java-examples/GenerateContentWithFunctionCall.java b/java-examples/GenerateContentWithFunctionCall.java new file mode 100644 index 0000000..117659c --- /dev/null +++ b/java-examples/GenerateContentWithFunctionCall.java @@ -0,0 +1,85 @@ +/* + * 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: + * + *

1a. If you are using Vertex AI, setup ADC to get credentials: + * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp + * + *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: + * + *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT + * + *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION + * + *

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 + * + *

export GOOGLE_API_KEY=YOUR_API_KEY + * + *

2. Compile the java package and run the sample code. + * + *

mvn clean compile + * + *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContentWithFunctionCall" + */ +package com.google.genai.examples; + +import com.google.common.collect.ImmutableMap; +import com.google.genai.Client; +import com.google.genai.types.FunctionDeclaration; +import com.google.genai.types.GenerateContentConfig; +import com.google.genai.types.GenerateContentResponse; +import com.google.genai.types.Schema; +import java.io.IOException; +import org.apache.http.HttpException; + +/** An example of using the Unified Gen AI Java SDK to generate content with function calling. */ +public class GenerateContentWithFunctionCall { + public static void main(String[] args) throws IOException, HttpException { + // Instantiate the client using Gemini Developer API. + Client client = new Client(); + + FunctionDeclaration functionDeclaration = + FunctionDeclaration.builder() + .name("get_current_weather") + .parameters( + Schema.builder() + .type("object") + .properties( + ImmutableMap.of( + "location", + Schema.builder() + .type("string") + .description("The location to get the weather for.") + .build())) + .build()) + .build(); + + GenerateContentConfig config = + GenerateContentConfig.fromJson( + String.format( + "{\"tools\":[{\"functionDeclarations\":[%s]}]}", functionDeclaration.toJson())); + + GenerateContentResponse response = + client.models.generateContent( + "gemini-2.0-flash-001", "What is the weather in Vancouver?", config); + + // Gets the function calls from the response by the quick accessor method `functionCalls()`. + System.out.println("Response: " + response.functionCalls()); + } +} diff --git a/java-examples/GenerateContentWithImageInput.java b/java-examples/GenerateContentWithImageInput.java new file mode 100644 index 0000000..38926d1 --- /dev/null +++ b/java-examples/GenerateContentWithImageInput.java @@ -0,0 +1,71 @@ +/* + * 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: + * + *

1a. If you are using Vertex AI, setup ADC to get credentials: + * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp + * + *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: + * + *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT + * + *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION + * + *

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 + * + *

export GOOGLE_API_KEY=YOUR_API_KEY + * + *

2. Compile the java package and run the sample code. + * + *

mvn clean compile + * + *

mvn exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContentWithImageInput" + */ +package com.google.genai.examples; + +import com.google.common.collect.ImmutableList; +import com.google.genai.Client; +import com.google.genai.types.Content; +import com.google.genai.types.GenerateContentResponse; +import com.google.genai.types.Part; +import java.io.IOException; +import org.apache.http.HttpException; + +/** An example of using the Unified Gen AI Java SDK to generate content with image input. */ +public class GenerateContentWithImageInput { + 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(); + + // Create parts from builder or `fromJson` method. + Part textPart = Part.builder().text("describe the image").build(); + Part imagePart = + Part.fromJson( + "{\"fileData\":{\"mimeType\":\"image/jpeg\",\"fileUri\":\"gs://path/to/image.jpg\"}}"); + + Content content = + Content.builder().role("user").parts(ImmutableList.of(textPart, imagePart)).build(); + + GenerateContentResponse response = + client.models.generateContent("gemini-2.0-flash-001", content, null); + + System.out.println("Response: " + response.text()); + } +} diff --git a/java-examples/GenerateImages.java b/java-examples/GenerateImages.java new file mode 100644 index 0000000..dae3047 --- /dev/null +++ b/java-examples/GenerateImages.java @@ -0,0 +1,75 @@ +/* + * 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: + * + *

1a. If you are using Vertex AI, setup ADC to get credentials: + * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp + * + *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: + * + *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT + * + *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION + * + *

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 + * + *

export GOOGLE_API_KEY=YOUR_API_KEY + * + *

2. Compile the java package and run the sample code. + * + *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.GenerateImages" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.GenerateImagesConfig; +import com.google.genai.types.GenerateImagesResponse; +import java.io.IOException; +import org.apache.http.HttpException; + +/** An example of using the Unified Gen AI Java SDK to generate images. */ +public class GenerateImages { + public static void main(String[] args) throws IOException, HttpException { + // Instantiates the client using Vertex AI, and sets the project and location in the builder. + Client client = + Client.builder() + .vertexAI(true) + .project(System.getenv("GOOGLE_CLOUD_PROJECT")) + .location(System.getenv("GOOGLE_CLOUD_LOCATION")) + .build(); + + GenerateImagesConfig generateImagesConfig = + GenerateImagesConfig.builder().numberOfImages(1).outputMimeType("image/jpeg").build(); + + GenerateImagesResponse generatedImagesResponse = + client.models.generateImages( + "imagen-3.0-generate-001", "Robot holding a red skateboard", generateImagesConfig); + + System.out.println( + "Image:\n" + + generatedImagesResponse + .generatedImages() + .get() + .get(0) + .image() + .get() + .imageBytes() + .get()); + } +} diff --git a/java-examples/GenerateImagesAsync.java b/java-examples/GenerateImagesAsync.java new file mode 100644 index 0000000..3eeb1d0 --- /dev/null +++ b/java-examples/GenerateImagesAsync.java @@ -0,0 +1,74 @@ +/* + * 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: + * + *

1a. If you are using Vertex AI, setup ADC to get credentials: + * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp + * + *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: + * + *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT + * + *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION + * + *

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 + * + *

export GOOGLE_API_KEY=YOUR_API_KEY + * + *

2. Compile the java package and run the sample code. + * + *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.GenerateImagesAsync" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.GenerateImagesConfig; +import com.google.genai.types.GenerateImagesResponse; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import org.apache.http.HttpException; + +/** An example of using the Unified Gen AI Java SDK to generate images asynchronously. */ +public class GenerateImagesAsync { + public static void main(String[] args) throws IOException, HttpException { + // Instantiates the client using Vertex AI, and sets the project and location in the builder. + Client client = + Client.builder() + .vertexAI(true) + .project(System.getenv("GOOGLE_CLOUD_PROJECT")) + .location(System.getenv("GOOGLE_CLOUD_LOCATION")) + .build(); + + GenerateImagesConfig generateImagesConfig = + GenerateImagesConfig.builder().numberOfImages(1).outputMimeType("image/jpeg").build(); + + CompletableFuture generateImagesResponseFuture = + client.async.models.generateImages( + "imagen-3.0-generate-001", "Robot holding a red skateboard", generateImagesConfig); + + generateImagesResponseFuture + .thenAccept( + response -> { + System.out.println( + "Image:\n" + + response.generatedImages().get().get(0).image().get().imageBytes().get()); + }) + .join(); + } +} diff --git a/java-examples/LiveTextConversationAsync.java b/java-examples/LiveTextConversationAsync.java new file mode 100644 index 0000000..76f5703 --- /dev/null +++ b/java-examples/LiveTextConversationAsync.java @@ -0,0 +1,148 @@ +/* + * 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: + * + *

1a. If you are using Vertex AI, setup ADC to get credentials: + * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp + * + *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: + * + *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT + * + *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION + * + *

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 + * + *

export GOOGLE_API_KEY=YOUR_API_KEY + * + *

2. Compile the java package and run the sample code. + * + *

mvn clean compile exec:java + * -Dexec.mainClass="com.google.genai.examples.LiveTextConversationAsync" + */ +package com.google.genai.examples; + +import com.google.common.collect.ImmutableList; +import com.google.genai.AsyncSession; +import com.google.genai.Client; +import com.google.genai.types.Content; +import com.google.genai.types.HttpOptions; +import com.google.genai.types.LiveClientContent; +import com.google.genai.types.LiveClientMessage; +import com.google.genai.types.LiveConnectConfig; +import com.google.genai.types.LiveServerContent; +import com.google.genai.types.LiveServerMessage; +import com.google.genai.types.Part; +import java.io.Console; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import org.apache.http.HttpException; + +/** Example of using the live module to send and receive messages asynchronously. */ +public class LiveTextConversationAsync { + + public static void main(String[] args) throws IOException, HttpException { + // Instantiates the client. + Client client = + Client.builder().httpOptions(HttpOptions.builder().apiVersion("v1alpha").build()).build(); + + LiveConnectConfig config = + LiveConnectConfig.builder().responseModalities(ImmutableList.of("TEXT")).build(); + + CompletableFuture allDone = new CompletableFuture<>(); + + try { + AsyncSession session = client.async.live.connect("gemini-2.0-flash-exp", config).get(); + + // Start receiving messages. + CompletableFuture receiveFuture = + session.receive(message -> printLiveServerMessage(message, allDone)); + + // Send messages. Keep sending until user quits. + System.out.print("Your Turn >> "); + boolean keepSending = true; + while (keepSending) { + keepSending = send(session).get(); + } + + allDone.get(); + receiveFuture.get(); + session.close().get(); + System.out.println("Session closed."); + + } catch (InterruptedException | ExecutionException e) { + System.err.println("An error occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + + public static LiveClientMessage liveClientMessageFromText(String text) { + return LiveClientMessage.builder() + .clientContent( + LiveClientContent.builder() + .turnComplete(true) + .turns( + ImmutableList.of( + Content.builder() + .parts(ImmutableList.of(Part.builder().text(text).build())) + .build())) + .build()) + .build(); + } + + public static void printLiveServerMessage( + LiveServerMessage message, CompletableFuture allDone) { + if (message.serverContent().isPresent()) { + LiveServerContent content = message.serverContent().get(); + content + .modelTurn() + .ifPresent( + modelTurn -> + modelTurn + .parts() + .ifPresent( + parts -> + parts.forEach(part -> part.text().ifPresent(System.out::print)))); + + if (content.turnComplete().orElse(false)) { + System.out.print("\nYour Turn >> "); + allDone.complete(null); + } + } + } + + private static CompletableFuture send(AsyncSession session) { + Console console = System.console(); + if (console == null) { + System.err.println("No console available."); + return CompletableFuture.completedFuture(false); + } + try { + String textInput = console.readLine(); + if (textInput == null || textInput.toLowerCase().matches("q|quit|exit")) { + return CompletableFuture.completedFuture(false); + } + return session.send(liveClientMessageFromText(textInput)).thenApply(unused -> true); + + } catch (Exception e) { + return CompletableFuture.completedFuture(false); + } + } +} diff --git a/java-examples/LiveTextToTextGenerationAsync.java b/java-examples/LiveTextToTextGenerationAsync.java new file mode 100644 index 0000000..16d7760 --- /dev/null +++ b/java-examples/LiveTextToTextGenerationAsync.java @@ -0,0 +1,125 @@ +/* + * 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: + * + *

1a. If you are using Vertex AI, setup ADC to get credentials: + * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp + * + *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: + * + *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT + * + *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION + * + *

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 + * + *

export GOOGLE_API_KEY=YOUR_API_KEY + * + *

2. Compile the java package and run the sample code. + * + *

mvn clean compile exec:java + * -Dexec.mainClass="com.google.genai.examples.LiveTextToTextGenerationAsync" + */ +package com.google.genai.examples; + +import com.google.common.collect.ImmutableList; +import com.google.genai.Client; +import com.google.genai.types.Content; +import com.google.genai.types.HttpOptions; +import com.google.genai.types.LiveClientContent; +import com.google.genai.types.LiveClientMessage; +import com.google.genai.types.LiveConnectConfig; +import com.google.genai.types.LiveServerContent; +import com.google.genai.types.LiveServerMessage; +import com.google.genai.types.Part; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import org.apache.http.HttpException; + +/** Example of using the live module to send and receive messages asynchronously. */ +public class LiveTextToTextGenerationAsync { + + public static void main(String[] args) throws IOException, HttpException { + // Instantiates the client. + Client client = + Client.builder().httpOptions(HttpOptions.builder().apiVersion("v1alpha").build()).build(); + + LiveConnectConfig config = + LiveConnectConfig.builder().responseModalities(ImmutableList.of("TEXT")).build(); + + CompletableFuture allDone = new CompletableFuture<>(); + + client + .async + .live + .connect("gemini-2.0-flash-exp", config) + .thenCompose( + session -> { + String inputText = "Write a short poem about a cat."; + System.out.println("\n**Input**\n" + inputText); + + LiveClientMessage input = liveClientMessageFromText(inputText); + + return session + // Send the input message. + .send(input) + .thenCompose( + unused -> { + System.out.print("\n**Response**\n"); + // Receive messages from the live session. + return session.receive(message -> printLiveServerMessage(message, allDone)); + }) + .thenCompose(unused -> allDone) + .thenCompose(unused -> session.close()); + }); + } + + public static LiveClientMessage liveClientMessageFromText(String text) { + return LiveClientMessage.builder() + .clientContent( + LiveClientContent.builder() + .turnComplete(true) + .turns( + ImmutableList.of( + Content.builder() + .parts(ImmutableList.of(Part.builder().text(text).build())) + .build())) + .build()) + .build(); + } + + public static void printLiveServerMessage( + LiveServerMessage message, CompletableFuture allDone) { + if (message.serverContent().isPresent()) { + LiveServerContent content = message.serverContent().get(); + if (content.modelTurn().isPresent()) { + Content modelTurn = content.modelTurn().get(); + for (Part part : modelTurn.parts().orElse(ImmutableList.of())) { + if (part.text().isPresent()) { + System.out.print(part.text().get()); + } + } + } + if (content.turnComplete().orElse(false)) { + System.out.println(); + allDone.complete(null); + } + } + } +} diff --git a/java-examples/UpscaleImage.java b/java-examples/UpscaleImage.java new file mode 100644 index 0000000..4f2ffd2 --- /dev/null +++ b/java-examples/UpscaleImage.java @@ -0,0 +1,80 @@ +/* + * 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: + * + *

1a. If you are using Vertex AI, setup ADC to get credentials: + * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp + * + *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: + * + *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT + * + *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION + * + *

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 + * + *

export GOOGLE_API_KEY=YOUR_API_KEY + * + *

2. Compile the java package and run the sample code. + * + *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.UpscaleImage" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.GenerateImagesConfig; +import com.google.genai.types.GenerateImagesResponse; +import com.google.genai.types.Image; +import com.google.genai.types.UpscaleImageConfig; +import com.google.genai.types.UpscaleImageResponse; +import java.io.IOException; +import org.apache.http.HttpException; + +/** An example of using the Unified Gen AI Java SDK to upscale an image. */ +public class UpscaleImage { + public static void main(String[] args) throws IOException, HttpException { + // Instantiates the client using Vertex AI, and sets the project and location in the builder. + Client client = + Client.builder() + .vertexAI(true) + .project(System.getenv("GOOGLE_CLOUD_PROJECT")) + .location(System.getenv("GOOGLE_CLOUD_LOCATION")) + .build(); + + GenerateImagesConfig generateImagesConfig = + GenerateImagesConfig.builder().numberOfImages(1).outputMimeType("image/jpeg").build(); + + GenerateImagesResponse generatedImagesResponse = + client.models.generateImages( + "imagen-3.0-generate-001", "Robot holding a red skateboard", generateImagesConfig); + + Image image = generatedImagesResponse.generatedImages().get().get(0).image().get(); + + UpscaleImageResponse upscaleImageResponse = + client.models.upscaleImage( + "imagen-3.0-generate-001", + image, + "x2", + UpscaleImageConfig.builder().outputMimeType("image/jpeg").build()); + + System.out.println( + "Image:\n" + + upscaleImageResponse.generatedImages().get().get(0).image().get().imageBytes().get()); + } +} diff --git a/java-examples/UpscaleImageAsync.java b/java-examples/UpscaleImageAsync.java new file mode 100644 index 0000000..a3f7b6d --- /dev/null +++ b/java-examples/UpscaleImageAsync.java @@ -0,0 +1,86 @@ +/* + * 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: + * + *

1a. If you are using Vertex AI, setup ADC to get credentials: + * https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp + * + *

Then set Project, Location, and USE_VERTEXAI flag as environment variables: + * + *

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT + * + *

export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION + * + *

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 + * + *

export GOOGLE_API_KEY=YOUR_API_KEY + * + *

2. Compile the java package and run the sample code. + * + *

mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.UpscaleImageAsync" + */ +package com.google.genai.examples; + +import com.google.genai.Client; +import com.google.genai.types.GenerateImagesConfig; +import com.google.genai.types.GenerateImagesResponse; +import com.google.genai.types.Image; +import com.google.genai.types.UpscaleImageConfig; +import com.google.genai.types.UpscaleImageResponse; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import org.apache.http.HttpException; + +/** An example of using the Unified Gen AI Java SDK to upscale an image asynchronously. */ +public class UpscaleImageAsync { + public static void main(String[] args) throws IOException, HttpException { + // Instantiates the client using Vertex AI, and sets the project and location in the builder. + Client client = + Client.builder() + .vertexAI(true) + .project(System.getenv("GOOGLE_CLOUD_PROJECT")) + .location(System.getenv("GOOGLE_CLOUD_LOCATION")) + .build(); + + GenerateImagesConfig generateImagesConfig = + GenerateImagesConfig.builder().numberOfImages(1).outputMimeType("image/jpeg").build(); + + GenerateImagesResponse generatedImagesResponse = + client.models.generateImages( + "imagen-3.0-generate-001", "Robot holding a red skateboard", generateImagesConfig); + + Image image = generatedImagesResponse.generatedImages().get().get(0).image().get(); + + CompletableFuture upscaleImageResponseFuture = + client.async.models.upscaleImage( + "imagen-3.0-generate-001", + image, + "x2", + UpscaleImageConfig.builder().outputMimeType("image/jpeg").build()); + + upscaleImageResponseFuture + .thenAccept( + response -> { + System.out.println( + "Image:\n" + + response.generatedImages().get().get(0).image().get().imageBytes().get()); + }) + .join(); + } +}