Skip to content

Google Gen AI Java SDK

Java idiomatic SDK for the Gemini Developer APIs and Gemini Enterprise Agent Platform APIs.

MavenJavadoc

Warning

Updates to Automatic Function Calling (AFC) in upcoming SDK version: We are changing AFC behavior in the next major version. Specifically, users will not be able to invoke AFC from direct calls to Models.generate_content or its stream and async variants. Instead, users should invoke AFC from Chats modules.

Methods/fields to be removedmigration guide
prompt/text/image arguments in Models.generate_videos (and async variants)Use source argument instead

Upcoming Change to Java 17 Support: Starting from SDK version 2.0.0, Java version 17 or later is required.

To avoid unexpected updates, pin the SDK version to < 2.0.0.

Add dependency

If you're using Maven, add the following to your dependencies:

<dependencies>
<dependency>
<groupId>com.google.genai</groupId>
<artifactId>google-genai</artifactId>
<version>1.65.0</version>
</dependency>
</dependencies>

Getting Started

Follow the instructions in this section to get started using the Google Gen AI SDK for Java.

Create a client

The Google Gen AI Java SDK provides a Client class, simplifying interaction with both the Gemini API and Gemini Enterprise Agent Platform API. With minimal configuration, you can seamlessly switch between the 2 backends without rewriting your code.

Instantiate a client that uses Gemini API

importcom.google.genai.Client;
// Use Builder class for instantiation. Explicitly set the API key to use Gemini// Developer backend.Clientclient = Client.builder().apiKey("your-api-key").build();

Instantiate a client that uses Gemini Enterprise Agent Platform API

Using project and location
importcom.google.genai.Client;
// Use Builder class for instantiation. Explicitly set the project and location,// and set `enterprise(true)` to use Gemini Enterprise Agent Platform backend.Clientclient = Client.builder()
.project("your-project")
.location("your-location")
.enterprise(true)
.build();
Using API key on Gemini Enterprise Agent Platform (GCP Express Mode)
importcom.google.genai.Client;
// Explicitly set the `apiKey` and `enterprise(true)` to use Gemini Enterprise Agent Platform backend// in express mode.Clientclient = Client.builder()
.apiKey("your-api-key")
.enterprise(true)
.build();

(Optional) Using environment variables:

You can create a client by configuring the necessary environment variables. Configuration setup instructions depends on whether you're using the Gemini Developer API or the Gemini API in Gemini Enterprise Agent Platform.

Gemini Developer API: Set the GOOGLE_API_KEY. It will automatically be picked up by the client. Note that GEMINI_API_KEY is a legacy environment variable, it's recommended to use GOOGLE_API_KEY only. But if both are set, GOOGLE_API_KEY takes precedence.

export GOOGLE_API_KEY='your-api-key'

Gemini API on Gemini Enterprise Agent Platform: Set GOOGLE_GENAI_USE_ENTERPRISE, GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_LOCATION, or GOOGLE_API_KEY for Gemini Enterprise Agent Platform express mode. It's recommended that you set only project & location, or API key. But if both are set, project & location takes precedence.

export GOOGLE_GENAI_USE_ENTERPRISE=true
// Set project and location for Gemini Enterprise Agent Platform authentication
export GOOGLE_CLOUD_PROJECT='your-project-id'export GOOGLE_CLOUD_LOCATION='us-central1'
// or API key for express mode
export GOOGLE_API_KEY='your-api-key'

After configuring the environment variables, you can instantiate a client without passing any variables.

importcom.google.genai.Client;
Clientclient = newClient();

API Selection

By default, the SDK uses the beta API endpoints provided by Google to support preview features in the APIs. The stable API endpoints can be selected by setting the API version to v1.

To set the API version use HttpOptions. For example, to set the API version to v1 for Gemini Enterprise Agent Platform:

importcom.google.genai.Client;
importcom.google.genai.types.HttpOptions;
Clientclient = Client.builder()
.project("your-project")
.location("your-location")
.enterprise(true)
.httpOptions(HttpOptions.builder().apiVersion("v1"))
.build();

To set the API version to v1alpha for the Gemini Developer API:

importcom.google.genai.Client;
importcom.google.genai.types.HttpOptions;
Clientclient = Client.builder()
.apiKey("your-api-key")
.httpOptions(HttpOptions.builder().apiVersion("v1alpha"))
.build();

HttpOptions

Besides apiVersion, HttpOptions also allows for flexible customization of HTTP request parameters such as baseUrl, headers, and timeout:

HttpOptionshttpOptions = HttpOptions.builder()
.baseUrl("your-own-endpoint.com")
.headers(ImmutableMap.of("key", "value"))
.timeout(600)
.build();

Beyond client-level configuration, HttpOptions can also be set on a per-request basis, providing maximum flexibility for diverse API call settings. See this example for more details.

HttpRetryOptions

HttpRetryOptions allows you to configure the automatic retry behavior for failed API calls. You can customize key settings like:

  • Total number of attempts.
  • Which HTTP status codes should trigger a retry (e.g., 429 for rate limits).
  • Backoff strategy, including the initial delay and maximum delay between retries.
HttpOptionshttpOptions = HttpOptions.builder()
.retryOptions(
HttpRetryOptions.builder()
.attempts(3)
.httpStatusCodes(408, 429))
.build();

Since HttpRetryOptions is part of HttpOptions, it supports being set at the client level (as shown) or on a per-request basis. Note that Providing HttpRetryOptions for a specific request will completely override any default retry settings configured on the client.

ClientOptions

ClientOptions enables you to customize the behavior of the HTTP client, including connection pool settings and proxy configurations.

Connection Pool

You can configure the connection pool via maxConnections (total maximum connections) and maxConnectionsPerHost (maximum connections to a single host).

importcom.google.genai.Client;
importcom.google.genai.types.ClientOptions;
Clientclient =
Client.builder()
.apiKey("your-api-key")
.clientOptions(
ClientOptions.builder().maxConnections(64).maxConnectionsPerHost(16).build())
.build();

Proxy

If your environment requires connecting through a proxy, you can configure it using ProxyOptions. The SDK supports HTTP, SOCKS, and DIRECT (no proxy) connection types, along with basic proxy authentication.

importcom.google.genai.Client;
importcom.google.genai.types.ClientOptions;
importcom.google.genai.types.ProxyOptions;
importcom.google.genai.types.ProxyType;
ClientOptionsclientOptions =
ClientOptions.builder()
.proxyOptions(
ProxyOptions.builder()
.type(ProxyType.Known.HTTP)
.host("your-proxy-host")
.port(8080)
.username("your-proxy-username")
.password("your-proxy-password"))
.build();
Clientclient = Client.builder().apiKey("your-api-key").clientOptions(clientOptions).build();

If ProxyOptions is provided with type set to DIRECT, it will enforce a direct connection, bypassing any system-level proxy settings.

Custom HTTP Client

If you need more advanced control over the HTTP client, such as adding custom interceptors, custom SSL configurations, or sharing an existing OkHttpClient instance across your application, you can provide your own OkHttpClient instance to ClientOptions.

When a custom OkHttpClient is provided, the SDK will clone it (using newBuilder()) to retain all your custom configurations, while still automatically appending the SDK's internal RetryInterceptor.

importcom.google.genai.Client;
importcom.google.genai.types.ClientOptions;
importokhttp3.OkHttpClient;
importjava.time.Duration;
// Create your custom OkHttpClientOkHttpClientcustomHttpClient = newOkHttpClient.Builder()
.connectTimeout(Duration.ofSeconds(30))
.readTimeout(Duration.ofSeconds(30))
// Add your custom interceptors, SSL socket factory, etc.
.build();
Clientclient = Client.builder()
.apiKey("your-api-key")
.clientOptions(
ClientOptions.builder()
.customHttpClient(customHttpClient)
.build()
)
.build();

Interact with models

The Google Gen AI Java SDK allows you to access the service programmatically. The following code snippets are some basic usages of model inferencing.

Generate Content

Use generateContent method for the most basic content generation.

with text input
package <yourpackagename>;
importcom.google.genai.Client;
importcom.google.genai.types.GenerateContentResponse;
publicclassGenerateContentWithTextInput {
publicstaticvoidmain(String[] args) {
// Instantiate the client. The client by default uses the Gemini API. It// gets the API key from the environment variable `GOOGLE_API_KEY`.Clientclient = newClient();
GenerateContentResponseresponse =
client.models.generateContent("gemini-2.5-flash", "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());
// Gets the http headers from the response.response
.sdkHttpResponse()
.ifPresent(
httpResponse ->
System.out.println("Response headers: " + httpResponse.headers().orElse(null)));
}
}
with text and image input
package <yourpackagename>;
importcom.google.common.collect.ImmutableList;
importcom.google.genai.Client;
importcom.google.genai.types.Content;
importcom.google.genai.types.GenerateContentResponse;
importcom.google.genai.types.Part;
publicclassGenerateContentWithImageInput {
publicstaticvoidmain(String[] args) {
// Instantiate the client using Gemini Enterprise Agent Platform API. The client gets the project and// location from the environment variables `GOOGLE_CLOUD_PROJECT` and// `GOOGLE_CLOUD_LOCATION`.Clientclient = Client.builder().enterprise(true).build();
// Construct a multimodal content with quick constructorsContentcontent =
Content.fromParts(
Part.fromText("describe the image"),
Part.fromUri("gs://path/to/image.jpg", "image/jpeg"));
GenerateContentResponseresponse =
client.models.generateContent("gemini-2.5-flash", content, null);
System.out.println("Response: " + response.text());
}
}
Generate Content with extra configs

To set configurations like System Instructions and Safety Settings, you can pass a GenerateContentConfig to the GenerateContent method.

package <yourpackagename>;
importcom.google.common.collect.ImmutableList;
importcom.google.genai.Client;
importcom.google.genai.types.Content;
importcom.google.genai.types.GenerateContentConfig;
importcom.google.genai.types.GenerateContentResponse;
importcom.google.genai.types.GoogleSearch;
importcom.google.genai.types.HarmBlockThreshold;
importcom.google.genai.types.HarmCategory;
importcom.google.genai.types.Part;
importcom.google.genai.types.SafetySetting;
importcom.google.genai.types.ThinkingConfig;
importcom.google.genai.types.Tool;
publicclassGenerateContentWithConfigs {
publicstaticvoidmain(String[] args) {
Clientclient = newClient();
// Sets the safety settings in the config.ImmutableList<SafetySetting> safetySettings =
ImmutableList.of(
SafetySetting.builder()
.category(HarmCategory.Known.HARM_CATEGORY_HATE_SPEECH)
.threshold(HarmBlockThreshold.Known.BLOCK_ONLY_HIGH)
.build(),
SafetySetting.builder()
.category(HarmCategory.Known.HARM_CATEGORY_DANGEROUS_CONTENT)
.threshold(HarmBlockThreshold.Known.BLOCK_LOW_AND_ABOVE)
.build());
// Sets the system instruction in the config.ContentsystemInstruction = Content.fromParts(Part.fromText("You are a history teacher."));
// Sets the Google Search tool in the config.ToolgoogleSearchTool = Tool.builder().googleSearch(GoogleSearch.builder()).build();
GenerateContentConfigconfig =
GenerateContentConfig.builder()
// Sets the thinking budget to 0 to disable thinking mode
.thinkingConfig(ThinkingConfig.builder().thinkingBudget(0))
.candidateCount(1)
.maxOutputTokens(1024)
.safetySettings(safetySettings)
.systemInstruction(systemInstruction)
.tools(googleSearchTool)
.build();
GenerateContentResponseresponse =
client.models.generateContent("gemini-2.5-flash", "Tell me the history of LLM", config);
System.out.println("Response: " + response.text());
}
}
Automatic function calling with generate content

The Models.generateContent methods supports automatic function calling (AFC). If the user passes in a list of public static method in the tool list of the GenerateContentConfig, by default AFC will be enabled with maximum remote calls to be 10 times. Follow the following steps to experience this feature.

Step 1: enable the compiler to parse parameter name of your methods. In your pom.xml, include the following compiler configuration.

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.0</version>
<configuration>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>

Step 2: see the following code example to use AFC, pay special attention to the code line where the java.lang.reflect.Method instance was extracted.

importcom.google.common.collect.ImmutableList;
importcom.google.genai.Client;
importcom.google.genai.types.GenerateContentConfig;
importcom.google.genai.types.GenerateContentResponse;
importcom.google.genai.types.Tool;
importjava.lang.reflect.Method;
publicclassGenerateContentWithFunctionCall {
publicstaticStringgetCurrentWeather(Stringlocation, Stringunit) {
return"The weather in " + location + " is " + "very nice.";
}
publicstaticvoidmain(String[] args) throwsNoSuchMethodException {
Clientclient = newClient();
// Load the method as a reflected Method object so that it can be// automatically executed on the client side.Methodmethod =
GenerateContentWithFunctionCall.class.getMethod(
"getCurrentWeather", String.class, String.class);
GenerateContentConfigconfig =
GenerateContentConfig.builder()
.tools(Tool.builder().functions(method))
.build();
GenerateContentResponseresponse =
client.models.generateContent(
"gemini-2.5-flash",
"What is the weather in Vancouver?",
config);
System.out.println("The response is: " + response.text());
System.out.println(
"The automatic function calling history is: "
+ response.automaticFunctionCallingHistory().get());
}
}
Stream Generated Content

To get a streamed response, you can use the generateContentStream method:

package <yourpackagename>;
importcom.google.genai.Client;
importcom.google.genai.ResponseStream;
importcom.google.genai.types.GenerateContentResponse;
publicclassStreamGeneration {
publicstaticvoidmain(String[] args) {
Clientclient = newClient();
ResponseStream<GenerateContentResponse> responseStream =
client.models.generateContentStream(
"gemini-2.5-flash", "Tell me a story in 300 words.", null);
System.out.println("Streaming response: ");
for (GenerateContentResponseres : 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();
}
}
Async Generate Content

To get a response asynchronously, you can use the generateContent method from the client.async.models namespace.

package <yourpackagename>;
importcom.google.genai.Client;
importcom.google.genai.types.GenerateContentResponse;
importjava.util.concurrent.CompletableFuture;
publicclassGenerateContentAsync {
publicstaticvoidmain(String[] args) {
Clientclient = newClient();
CompletableFuture<GenerateContentResponse> responseFuture =
client.async.models.generateContent(
"gemini-2.5-flash", "Introduce Google AI Studio.", null);
responseFuture
.thenAccept(
response -> {
System.out.println("Async response: " + response.text());
})
.join();
}
}
Generate Content with JSON response schema

To get a response in JSON by passing in a response schema to the GenerateContent API.

package <yourpackagename>;
importcom.google.common.collect.ImmutableList;
importcom.google.common.collect.ImmutableMap;
importcom.google.genai.Client;
importcom.google.genai.types.GenerateContentConfig;
importcom.google.genai.types.GenerateContentResponse;
importcom.google.genai.types.Schema;
importcom.google.genai.types.Type;
publicclassGenerateContentWithSchema {
publicstaticvoidmain(String[] args) {
Clientclient = newClient();
// Define the schema for the response, in Json format.ImmutableMap<String, Object> schema = ImmutableMap.of(
"type", "object",
"properties", ImmutableMap.of(
"recipe_name", ImmutableMap.of("type", "string"),
"ingredients", ImmutableMap.of(
"type", "array",
"items", ImmutableMap.of("type", "string")
)
),
"required", ImmutableList.of("recipe_name", "ingredients")
);
// Set the response schema in GenerateContentConfigGenerateContentConfigconfig =
GenerateContentConfig.builder()
.responseMimeType("application/json")
.candidateCount(1)
.responseSchema(schema)
.build();
GenerateContentResponseresponse =
client.models.generateContent("gemini-2.5-flash", "Tell me your name", config);
System.out.println("Response: " + response.text());
}
}

Count Tokens and Compute Tokens

The countTokens method allows you to calculate the number of tokens your prompt will use before sending it to the model, helping you manage costs and stay within the context window.

package <yourpackagename>;
importcom.google.genai.Client;
importcom.google.genai.types.CountTokensResponse;
publicclassCountTokens {
publicstaticvoidmain(String[] args) {
Clientclient = newClient();
CountTokensResponseresponse =
client.models.countTokens("gemini-2.5-flash", "What is your name?", null);
System.out.println("Count tokens response: " + response);
}
}

The computeTokens method returns the Tokens Info that contains tokens and token IDs given your prompt. This method is only supported in Gemini Enterprise Agent Platform.

package <yourpackagename>;
importcom.google.genai.Client;
importcom.google.genai.types.ComputeTokensResponse;
publicclassComputeTokens {
publicstaticvoidmain(String[] args) {
Clientclient = Client.builder().enterprise(true).build();
ComputeTokensResponseresponse =
client.models.computeTokens("gemini-2.5-flash", "What is your name?", null);
System.out.println("Compute tokens response: " + response);
}
}

Embed Content

The embedContent method allows you to generate embeddings for words, phrases, sentences, and code, as well as multimodal content like images or videos via Gemini Enterprise Agent Platform.

package <yourpackagename>;
importcom.google.genai.Client;
importcom.google.genai.types.EmbedContentConfig;
importcom.google.genai.types.EmbedContentResponse;
publicclassEmbedContent {
publicstaticvoidmain(String[] args) {
Clientclient = newClient();
EmbedContentResponseresponse =
client.models.embedContent("gemini-embedding-001", "why is the sky blue?", null);
System.out.println("Embedding response: " + response);
// Multimodal embedding with Gemini Enterprise Agent PlatformCliententerpriseClient = Client.builder().enterprise(true).build();
EmbedContentConfigconfig =
EmbedContentConfig.builder()
.outputDimensionality(10)
.title("test_title")
.taskType("RETRIEVAL_DOCUMENT")
.build();
EmbedContentResponsemmResponse =
enterpriseClient.models.embedContent(
"gemini-embedding-2-exp-11-2025",
Content.fromParts(
Part.fromText("Hello"),
Part.fromUri("gs://cloud-samples-data/generative-ai/image/a-man-and-a-dog.png", "image/png")),
config);
System.out.println("Multimodal embedding response: " + mmResponse);
}
}

Imagen

Imagen is a text-to-image GenAI service.

Generate Images

The generateImages method helps you create high-quality, unique images given a text prompt.

package <yourpackagename>;
importcom.google.genai.Client;
importcom.google.genai.types.GenerateImagesConfig;
importcom.google.genai.types.GenerateImagesResponse;
importcom.google.genai.types.Image;
publicclassGenerateImages {
publicstaticvoidmain(String[] args) {
Clientclient = newClient();
GenerateImagesConfigconfig =
GenerateImagesConfig.builder()
.numberOfImages(1)
.outputMimeType("image/jpeg")
.includeSafetyAttributes(true)
.build();
GenerateImagesResponseresponse =
client.models.generateImages(
"imagen-3.0-generate-002", "Robot holding a red skateboard", config);
if (generatedImagesResponse.images().isEmpty()) {
System.out.println("Unable to generate images.");
}
System.out.println("Generated " + generatedImagesResponse.images().size() + " images.");
ImagegeneratedImage = generatedImagesResponse.images().get(0);
}
}

Upscale Image

The upscaleImage method allows you to upscale an image. This feature is only supported in Gemini Enterprise Agent Platform.

package <yourpackagename>;
importcom.google.genai.Client;
importcom.google.genai.types.Image;
importcom.google.genai.types.UpscaleImageConfig;
importcom.google.genai.types.UpscaleImageResponse;
publicclassUpscaleImage {
publicstaticvoidmain(String[] args) {
Clientclient = Client.builder().enterprise(true).build();
Imageimage = Image.fromFile("path/to/your/image");
UpscaleImageConfigconfig =
UpscaleImageConfig.builder()
.outputMimeType("image/jpeg")
.enhanceInputImage(true)
.imagePreservationFactor(0.6f)
.build();
UpscaleImageResponseresponse =
client.models.upscaleImage("imagen-3.0-generate-002", image, "x2", config);
response.generatedImages().ifPresent(
images -> {
ImageupscaledImage = images.get(0).image().orElse(null);
// Do something with the upscaled image.
}
);
}
}

Edit Image

The editImage method lets you edit an image. You can input reference images (ex. mask reference for inpainting, or style reference for style transfer) in addition to a text prompt to guide the editing.

This feature uses a different model than generateImages and upscaleImage. It is only supported in Gemini Enterprise Agent Platform.

package <yourpackagename>;
importcom.google.genai.Client;
importcom.google.genai.types.EditImageConfig;
importcom.google.genai.types.EditImageResponse;
importcom.google.genai.types.EditMode;
importcom.google.genai.types.Image;
importcom.google.genai.types.MaskReferenceConfig;
importcom.google.genai.types.MaskReferenceImage;
importcom.google.genai.types.MaskReferenceMode;
importcom.google.genai.types.RawReferenceImage;
importcom.google.genai.types.ReferenceImage;
importjava.util.ArrayList;
publicclassEditImage {
publicstaticvoidmain(String[] args) {
Clientclient = Client.builder().enterprise(true).build();
Imageimage = Image.fromFile("path/to/your/image");
// Edit image with a mask.EditImageConfigconfig =
EditImageConfig.builder()
.editMode(EditMode.Known.EDIT_MODE_INPAINT_INSERTION)
.numberOfImages(1)
.outputMimeType("image/jpeg")
.build();
ArrayList<ReferenceImage> referenceImages = newArrayList<>();
RawReferenceImagerawReferenceImage =
RawReferenceImage.builder().referenceImage(image).referenceId(1).build();
referenceImages.add(rawReferenceImage);
MaskReferenceImagemaskReferenceImage =
MaskReferenceImage.builder()
.referenceId(2)
.config(
MaskReferenceConfig.builder()
.maskMode(MaskReferenceMode.Known.MASK_MODE_BACKGROUND)
.maskDilation(0.0f))
.build();
referenceImages.add(maskReferenceImage);
EditImageResponseresponse =
client.models.editImage(
"imagen-3.0-capability-001", "Sunlight and clear sky", referenceImages, config);
response.generatedImages().ifPresent(
images -> {
ImageeditedImage = images.get(0).image().orElse(null);
// Do something with the edited image.
}
);
}
}

Veo

Veo is a video generation GenAI service.

Generate Videos (Text to Video)

package <yourpackagename>;
importcom.google.genai.Client;
importcom.google.genai.types.GenerateVideosConfig;
importcom.google.genai.types.GenerateVideosOperation;
importcom.google.genai.types.Video;
publicclassGenerateVideosWithText {
publicstaticvoidmain(String[] args) {
Clientclient = newClient();
GenerateVideosConfigconfig =
GenerateVideosConfig.builder()
.numberOfVideos(1)
.enhancePrompt(true)
.durationSeconds(5)
.build();
// generateVideos returns an operationGenerateVideosOperationoperation =
client.models.generateVideos(
"veo-2.0-generate-001", "A neon hologram of a cat driving at top speed", null, config);
// When the operation hasn't been finished, operation.done() is emptywhile (!operation.done().isPresent()) {
try {
System.out.println("Waiting for operation to complete...");
Thread.sleep(10000);
// Sleep for 10 seconds and check the operation againoperation = client.operations.getVideosOperation(operation, null);
} catch (InterruptedExceptione) {
System.out.println("Thread was interrupted while sleeping.");
Thread.currentThread().interrupt();
}
}
operation.response().ifPresent(
response -> {
response.generatedVideos().ifPresent(
videos -> {
System.out.println("Generated " + videos.size() + " videos.");
Videovideo = videos.get(0).video().orElse(null);
// Do something with the generated video
}
);
}
);
}
}

Generate Videos (Image to Video)

package <yourpackagename>;
importcom.google.genai.Client;
importcom.google.genai.types.GenerateVideosConfig;
importcom.google.genai.types.GenerateVideosOperation;
importcom.google.genai.types.Image;
importcom.google.genai.types.Video;
publicclassGenerateVideosWithImage {
publicstaticvoidmain(String[] args) {
Clientclient = newClient();
Imageimage = Image.fromFile("path/to/your/image");
GenerateVideosConfigconfig =
GenerateVideosConfig.builder()
.numberOfVideos(1)
.enhancePrompt(true)
.durationSeconds(5)
.build();
// generateVideos returns an operationGenerateVideosOperationoperation =
client.models.generateVideos(
"veo-2.0-generate-001",
"Night sky",
image,
config);
// When the operation hasn't been finished, operation.done() is emptywhile (!operation.done().isPresent()) {
try {
System.out.println("Waiting for operation to complete...");
Thread.sleep(10000);
// Sleep for 10 seconds and check the operation againoperation = client.operations.getVideosOperation(operation, null);
} catch (InterruptedExceptione) {
System.out.println("Thread was interrupted while sleeping.");
Thread.currentThread().interrupt();
}
}
operation.response().ifPresent(
response -> {
response.generatedVideos().ifPresent(
videos -> {
System.out.println("Generated " + videos.size() + " videos.");
Videovideo = videos.get(0).video().orElse(null);
// Do something with the generated video
}
);
}
);
}
}

Files API

Gemini models support various input data types, including text, images, and audio. The Files API allows you to upload and manage these media files for use with Gemini models. This feature is exclusively supported by the Gemini API.

Usage info

You can use the Files API to upload and interact with media files. The Files API lets you store up to 20 GB of files per project, with a per-file maximum size of 2 GB. Files are stored for 48 hours. During that time, you can use the API to get metadata about the files, but you can't download the files. The Files API is available at no cost in all regions where the Gemini API is available.

The basic operations are:

  1. Upload: You can use the Files API to upload a media file. Always use the Files API when the total request size (including the files, text prompt, system instructions, etc.) is larger than 20 MB.

  2. Get: You can verify that the API successfully stored the uploaded file and get its metadata.

  3. List: You can upload multiple files using the Files API. The following code gets a list of all the files uploaded.

  4. Delete: Files are automatically deleted after 48 hours. You can also manually delete an uploaded file:

Sample usage

package <yourpackagename>;
importcom.google.genai.Client;
importcom.google.genai.errors.GenAiIOException;
importcom.google.genai.types.Content;
importcom.google.genai.types.DeleteFileResponse;
importcom.google.genai.types.File;
importcom.google.genai.types.GenerateContentResponse;
importcom.google.genai.types.ListFilesConfig;
importcom.google.genai.types.Part;
importcom.google.genai.types.UploadFileConfig;
/** An example of how to use the Files module to upload, retrieve, list, and delete files. */publicfinalclassFileOperations {
publicstaticvoidmain(String[] args) {
Clientclient = newClient();
// Upload a file to the API.try {
Filefile =
client.files.upload(
"path/to/your/file.pdf",
UploadFileConfig.builder().mimeType("application/pdf").build());
// Use the uploaded file in the generateContentContentcontent =
Content.fromParts(
Part.fromText("Summary this pdf."),
Part.fromUri(file.name().get(), file.mimeType().get()));
GenerateContentResponseresponse =
client.models.generateContent("gemini-2.5-flash", content, null);
// Get the uploaded file.FileretrievedFile = client.files.get(file.name().get(), null);
// List all files.System.out.println("List files: ");
for (Filef : client.files.list(ListFilesConfig.builder().pageSize(10).build())) {
System.out.println("File name: " + f.name().get());
}
// Delete the uploaded file.client.files.delete(file.name().get(), null);
} catch (GenAiIOExceptione) {
System.out.println("An error occurred while uploading the file: " + e.getMessage());
}
}
}

Versioning

This library follows Semantic Versioning.

Contribute to this library

The Google Gen AI Java SDK will accept contributions in the future.

License

Apache 2.0 - See LICENSE for more information.

About

Google Gen AI Java SDK provides an interface for developers to integrate Google's generative models into their Java applications.

Resources

Code of conduct

Contributing

Security policy

Stars

388 stars

Watchers

22 watching

Forks

Releases

Packages

Used by

Contributors

Languages