Skip to content

Added java-examples folder #20

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions java-examples/GenerateContent.java
Original file line number Diff line number Diff line change
@@ -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:
*
* <p>1a. If you are using Vertex AI, setup ADC to get credentials:
* https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp
*
* <p>Then set Project, Location, and USE_VERTEXAI flag as environment variables:
*
* <p>export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT
*
* <p>export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION
*
* <p>1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a
* list of available API keys here: https://aistudio.google.com/app/apikey
*
* <p>export GOOGLE_API_KEY=YOUR_API_KEY
*
* <p>2. Compile the java package and run the sample code.
*
* <p>mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.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());
}
}
63 changes: 63 additions & 0 deletions java-examples/GenerateContentAsync.java
Original file line number Diff line number Diff line change
@@ -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:
*
* <p>1a. If you are using Vertex AI, setup ADC to get credentials:
* https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp
*
* <p>Then set Project, Location, and USE_VERTEXAI flag as environment variables:
*
* <p>export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT
*
* <p>export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION
*
* <p>1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a
* list of available API keys here: https://aistudio.google.com/app/apikey
*
* <p>export GOOGLE_API_KEY=YOUR_API_KEY
*
* <p>2. Compile the java package and run the sample code.
*
* <p>mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.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<GenerateContentResponse> 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();
}
}
66 changes: 66 additions & 0 deletions java-examples/GenerateContentStream.java
Original file line number Diff line number Diff line change
@@ -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:
*
* <p>1a. If you are using Vertex AI, setup ADC to get credentials:
* https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp
*
* <p>Then set Project, Location, and USE_VERTEXAI flag as environment variables:
*
* <p>export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT
*
* <p>export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION
*
* <p>1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a
* list of available API keys here: https://aistudio.google.com/app/apikey
*
* <p>export GOOGLE_API_KEY=YOUR_API_KEY
*
* <p>2. Compile the java package and run the sample code.
*
* <p>mvn clean compile exec:java -Dexec.mainClass="com.google.genai.examples.GenerateContentStream"
*/
package com.google.genai.examples;

import com.google.genai.Client;
import com.google.genai.ResponseStream;
import com.google.genai.types.GenerateContentResponse;
import java.io.IOException;
import org.apache.http.HttpException;

/** An example of using the Unified GenAI Java SDK to generate stream of content. */
public class GenerateContentStream {
public static void main(String[] args) throws IOException, HttpException {
// Instantiate the client using Vertex API. The client gets the project and location from the
// environment variables `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`.
Client client = Client.builder().vertexAI(true).build();

ResponseStream<GenerateContentResponse> responseStream =
client.models.generateContentStream(
"gemini-2.0-flash-001", "Tell me a story in 300 words.", null);

System.out.println("Streaming response: ");
for (GenerateContentResponse res : responseStream) {
System.out.print(res.text());
}

// To save resources and avoid connection leaks, it is recommended to close the response
// stream after consumption (or using try block to get the response stream).
responseStream.close();
}
}
95 changes: 95 additions & 0 deletions java-examples/GenerateContentWithConfigs.java
Original file line number Diff line number Diff line change
@@ -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:
*
* <p>1a. If you are using Vertex AI, setup ADC to get credentials:
* https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp
*
* <p>Then set Project, Location, and USE_VERTEXAI flag as environment variables:
*
* <p>export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT
*
* <p>export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION
*
* <p>1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a
* list of available API keys here: https://aistudio.google.com/app/apikey
*
* <p>export GOOGLE_API_KEY=YOUR_API_KEY
*
* <p>2. Compile the java package and run the sample code.
*
* <p>mvn clean compile
*
* <p>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<SafetySetting> 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());
}
}
85 changes: 85 additions & 0 deletions java-examples/GenerateContentWithFunctionCall.java
Original file line number Diff line number Diff line change
@@ -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:
*
* <p>1a. If you are using Vertex AI, setup ADC to get credentials:
* https://cloud.google.com/docs/authentication/provide-credentials-adc#google-idp
*
* <p>Then set Project, Location, and USE_VERTEXAI flag as environment variables:
*
* <p>export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT
*
* <p>export GOOGLE_CLOUD_LOCATION=YOUR_LOCATION
*
* <p>1b. If you are using Gemini Developer AI, set an API key environment variable. You can find a
* list of available API keys here: https://aistudio.google.com/app/apikey
*
* <p>export GOOGLE_API_KEY=YOUR_API_KEY
*
* <p>2. Compile the java package and run the sample code.
*
* <p>mvn clean compile
*
* <p>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());
}
}
Loading